Implement Event Handlers
Now that we have developed part of the subgraph that takes care of creating Market entities and all subgraph sources to listen to market specific events, let's start implementation of mapping code to index user investments in this market.
Our approach towards implementing subgraph will be to call investInMarket , redeemFromMarket and updateMarket function from SimpleFi mapping code library in event handlers for Mint , Burn and Sync respectively. Let's discuss every case one by one.

Invest in market

Below is initial code of handler function of Mint event
1
// Mint(address indexed sender, uint amount0, uint amount1)
2
export function handleMint(event: Mint): void {
3
4
// We need to collect data arguments of this call
5
investInMarket(
6
event,
7
account,
8
market,
9
outputTokenAmount,
10
inputTokenAmounts,
11
rewardTokenAmounts,
12
outputTokenBalance,
13
inputTokenBalances,
14
rewardTokenBalances,
15
transferredFrom
16
)
17
}
Copied!
Let's discuss each function argument and see how we can get the required data for it -
  • event : It's as handler function argument event
  • account : This is Account entity that is created for the user making this investment. We will need to create this entity by calling getOrCreateAccount function of code library
  • market : We can fetch the market entity for this pair by loading it directly from it's ID. We are sure that the market entity exists because we create the market entity before starting the source which triggers this handler function. ID of the market is same as address of the pair contract which is available as event.address in this function
  • outputTokenAmount : This is amount of output token that is minted by market for user. It's not provided in the Mint event parameters so we need to get it from somewhere else. As discussed in Understanding Smart Contracts article, we can get it's value from Transfer event
  • inputTokenAmounts : These values are available as parameters in Mint event
  • rewardTokenAmounts : This will be an empty array because there is no reward given at the time of providing liquidity to a SushiSwap pair
  • outputTokenBalance : This is not available in the Mint event. We can calculate this value by fetching this user's existing position in this market and adding outputTokenAmount to Position.outputTokenBalance but we recommend that event handlers should not interact with the Position entity directly as it can be tricky to get latest position of a user in a market because of internal structure of the entities and their relationships. We will instead define a new entity in schema to keep track of user's output token balance in a market. We call this new entity AccountLiquidity
  • inputTokenBalances : This also require us to use Market.inputTokenBalances to compute new market reserves after adding newly deposited tokens. Then divide these new reserve values with Market.outputTokenTotalSupply to get the amount of share of the user in the market reserves. Again to avoid issues arising from intermingles updates we don't use Market entity values directly and instead define a new entity to track pair's reserves and total supply. We call this new entity pair
  • rewardTokenBalance : This will be an empty array
  • transferredFrom : This will be null because user is providing the liquidity directly be depositing input tokens to the market
As discussed in Understanding Smart Contractswe need to implement handlers for Transfer, Sync and Mint events and collect data in a temporary entity to be able to create above required arguments for investInMarket function. We add following two entities in schema.graphql
1
type AccountLiquidity @entity {
2
id: ID! # {pairAddress}{accoutnAddress}
3
pair: Pair!
4
account: Account!
5
balance: BigInt!
6
}
7
8
type Mint @entity {
9
id: ID! # {trasactionHash}
10
pair: Pair
11
to: Account
12
liquityAmount: BigInt
13
amount0: BigInt
14
amount1: BigInt
15
transferEventApplied: Boolean!
16
syncEventApplied: Boolean!
17
mintEventApplied: Boolean!
18
}
Copied!
We then add following code to uniswapV2Pair.ts to handle relevant events
1
function getOrCreateMint(event: ethereum.Event, pair: PairEntity): MintEntity {
2
let mint = MintEntity.load(event.transaction.hash.toHexString())
3
if (mint != null) {
4
return mint as MintEntity
5
}
6
7
mint = new MintEntity(event.transaction.hash.toHexString())
8
mint.pair = pair.id
9
mint.transferEventApplied = false
10
mint.syncEventApplied = false
11
mint.mintEventApplied = false
12
mint.save()
13
return mint as MintEntity
14
}
15
16
function getOrCreateLiquidity(pair: PairEntity, accountAddress: Address): AccountLiquidityEntity {
17
let id = pair.id.concat("-").concat(accountAddress.toHexString())
18
let liqudity = AccountLiquidityEntity.load(id)
19
if (liqudity != null) {
20
return liqudity as AccountLiquidityEntity
21
}
22
liqudity = new AccountLiquidityEntity(id)
23
liqudity.pair = pair.id
24
liqudity.account = getOrCreateAccount(accountAddress).id
25
liqudity.balance = BigInt.fromI32(0)
26
liqudity.save()
27
return liqudity as AccountLiquidityEntity
28
}
29
30
function createOrUpdatePositionOnMint(event: ethereum.Event, pair: PairEntity, mint: MintEntity): void {
31
let isComplete = mint.transferEventApplied && mint.syncEventApplied && mint.mintEventApplied
32
if (!isComplete) {
33
return
34
}
35
36
let accountAddress = Address.fromString(mint.to)
37
let account = new AccountEntity(mint.to)
38
let market = MarketEntity.load(mint.pair) as MarketEntity
39
let accountLiquidity = getOrCreateLiquidity(pair, accountAddress)
40
41
let outputTokenAmount = mint.liquityAmount as BigInt
42
let inputTokenAmounts: TokenBalance[] = []
43
inputTokenAmounts.push(new TokenBalance(pair.token0, mint.to, mint.amount0 as BigInt))
44
inputTokenAmounts.push(new TokenBalance(pair.token1, mint.to, mint.amount1 as BigInt))
45
46
let outputTokenBalance = accountLiquidity.balance
47
let token0Balance = outputTokenBalance.times(pair.reserve0).div(pair.totalSupply)
48
let token1Balance = outputTokenBalance.times(pair.reserve1).div(pair.totalSupply)
49
let inputTokenBalances: TokenBalance[] = []
50
inputTokenBalances.push(new TokenBalance(pair.token0, mint.to, token0Balance))
51
inputTokenBalances.push(new TokenBalance(pair.token1, mint.to, token1Balance))
52
53
investInMarket(
54
event,
55
account,
56
market,
57
outputTokenAmount,
58
inputTokenAmounts,
59
[],
60
outputTokenBalance,
61
inputTokenBalances,
62
[],
63
null
64
)
65
66
// update market
67
let marketInputTokenBalances: TokenBalance[] = []
68
marketInputTokenBalances.push(new TokenBalance(pair.token0, pair.id, pair.reserve0))
69
marketInputTokenBalances.push(new TokenBalance(pair.token1, pair.id, pair.reserve1))
70
71
// Update market
72
updateMarket(
73
event,
74
market,
75
marketInputTokenBalances,
76
pair.totalSupply
77
)
78
79
store.remove('Mint', mint.id)
80
}
81
82
export function handleTransfer(event: Transfer): void {
83
if (event.params.value == BigInt.fromI32(0)) {
84
return
85
}
86
87
let pairAddressHex = event.address.toHexString()
88
let fromHex = event.params.from.toHexString()
89
let toHex = event.params.to.toHexString()
90
91
let pair = PairEntity.load(pairAddressHex) as PairEntity
92
93
// update account balances
94
if (fromHex != ADDRESS_ZERO) {
95
let accountLiquidityFrom = getOrCreateLiquidity(pair, event.params.from)
96
accountLiquidityFrom.balance = accountLiquidityFrom.balance.minus(event.params.value)
97
accountLiquidityFrom.save()
98
}
99
100
if (fromHex != pairAddressHex) {
101
let accountLiquidityTo = getOrCreateLiquidity(pair, event.params.to)
102
accountLiquidityTo.balance = accountLiquidityTo.balance.plus(event.params.value)
103
accountLiquidityTo.save()
104
}
105
106
// Check if transfer it's a mint or burn or transfer transaction
107
// minting new LP tokens
108
if (fromHex == ADDRESS_ZERO) {
109
if (toHex == ADDRESS_ZERO) {
110
pair.totalSupply = pair.totalSupply.plus(event.params.value)
111
pair.save()
112
}
113
114
let mint = getOrCreateMint(event, pair)
115
mint.transferEventApplied = true
116
mint.to = getOrCreateAccount(event.params.to).id
117
mint.liquityAmount = event.params.value
118
mint.save()
119
createOrUpdatePositionOnMint(event, pair, mint)
120
}
121
122
// send to pair contract before burn method call
123
if (fromHex != ADDRESS_ZERO && toHex == pairAddressHex) {
124
125
}
126
127
// internal _burn method call
128
if (fromHex == pairAddressHex && toHex == ADDRESS_ZERO) {
129
130
}
131
132
// everything else
133
if (fromHex != ADDRESS_ZERO && fromHex != pairAddressHex && toHex != pairAddressHex) {
134
135
}
136
}
137
138
export function handleMint(event: Mint): void {
139
let pair = PairEntity.load(event.address.toHexString()) as PairEntity
140
let mint = getOrCreateMint(event, pair)
141
mint.mintEventApplied = true
142
mint.amount0 = event.params.amount0
143
mint.amount1 = event.params.amount1
144
mint.save()
145
createOrUpdatePositionOnMint(event, pair, mint)
146
}
147
148
export function handleSync(event: Sync): void {
149
let transactionHash = event.transaction.hash.toHexString()
150
151
let pair = PairEntity.load(event.address.toHexString()) as PairEntity
152
pair.reserve0 = event.params.reserve0
153
pair.reserve1 = event.params.reserve1
154
pair.save()
155
156
let isSyncOnly = true
157
158
let possibleMint = MintEntity.load(transactionHash)
159
if (possibleMint != null) {
160
isSyncOnly = false
161
let mint = possibleMint as MintEntity
162
mint.syncEventApplied = true
163
mint.save()
164
165
pair.totalSupply = pair.totalSupply.plus(mint.liquityAmount as BigInt)
166
pair.save()
167
168
createOrUpdatePositionOnMint(event, pair, mint)
169
}
170
171
if (isSyncOnly) {
172
let inputTokenBalances: TokenBalance[] = []
173
inputTokenBalances.push(new TokenBalance(pair.token0, pair.id, pair.reserve0))
174
inputTokenBalances.push(new TokenBalance(pair.token1, pair.id, pair.reserve1))
175
176
// Update market
177
let market = MarketEntity.load(event.address.toHexString()) as MarketEntity
178
updateMarket(
179
event,
180
market,
181
inputTokenBalances,
182
pair.totalSupply
183
)
184
}
185
}
Copied!

Transfer event handler

It's pretty simple, we are simply checking if a transfer is part of a mint, burn or a user to user to transfer. In case it's a mint we increase balance of the to address in AccountLiquidity entity. We also create a Mint entity by calling getOrCreateMint function. We created this helper function because we did not want to rely on ordering of event triggers in subgraph. So no matter which event handler is triggered first our code will create the Mint entity only once and will keep populating data available in the event being processed.
Though after discussion with The Graph team we found that we can trust the ordering of event triggers in subgraph, we still found it better to use this getOrCreate pattern as it avoids a lot of errors because of edge cases. This also makes it easy to debug in case something unexpected happens. We can simply check if the entity exists and which event handlers have been processed for the transaction for which this entity was created. This pattern become most helpful when we need to implement call handlers which are triggered after triggering all event handlers for a specific transaction. For example if we had to add a call handler for mint method of UniswapV2Pair.sol smart contract then this call handler function will be executed after all the event handlers for Transfer, Sync and Mint have been executed. Now we may think intuitively that in the scope of these event handlers the Mint entity should exist but it does not exist because call handlers was never executed before these event handlers. Therefore instead of assuming existence and loading we recommend this getOrCreate pattern which will check of existence of the entity and then create if not existing or fetch if existing. Trust me when I say that this pattern has saved us a lot of hours of debugging.
After creating Mint entity we simply populate to and liquidity amount attributes in Transfer event handler as they are required in investInMarket function.

Sync event handler

In this event handlers also we need to figure out if the event is part of a Mint, Burn or Swap transaction. We know that in case of Mint there should have been a transfer event before it and there should either be a Mint entity for the transaction. We check for existing Mint entity and if it exists then we populate it.
If Mint entity does not exists then we simply update the Pair entity and call updateMarket to update market reserves.

Mint event handler

In this event handler we don't need to check anything as it is emitted only in a Mint transaction. We fetch an existing Mint entity and populate it's attributes amount0 and amount1 . This completes the Mint entity and then calling createOrUpdatePositionOnMint will find that all events have been applied and it will update the common entities Position to create or update an existing position in this market.

Redeem from market

Burn transaction works similar to Mint transaction and we need to use similar logic of populating a temporary Burn entity to get the all the required arguments for redeemFromMarket call. Code is straight forward and can be seen at UniswapV2Pair.ts .

Transfer of LP tokens

In Sushi Swap one can transfer the LP tokens they get by depositing their ERC20 tokens to the pair contract. For our subgraph we need to track these transfers as well because on a transfer position of the both the accounts is changing. To track these changes in positions we also implement a handleTransfer function which listens on Transfer event of ERC20 specification. This function calls redeemFromMarket for the user sending LP tokens and calls investInMarket for user receiving LP tokens. This way we keep track of latest balance of all the accounts while also storing information of how they got this balance - by investing or by transfer from someone.

Transfer to zero address

Almost all subgraphs need to handle this specific case we are about to discuss. The case is of transfer to zero address. It is a tricky case because a transfer to zero could be part of a redeem transaction and could be a manual (accidental) transfer by a user. In our subgraph we need to detect which case is it because in case of redeem we also need to update the market reserves and in case of manual transfer only user position changes but market reserves remain same.
In Sushi Swap we find that the transfer to zero is emitted before Burn event so while handling Transfer event we can not figure out if it's part of a Burn transaction or manual transfer. We will get to know about it only while processing next transaction because we can not call a function in subgraph at the end of a transaction to figure out if Burn event was emitted or not.
To handle this we store lastTransferToZero attribute in Pair entity that we populate every time there is a transfer to zero address. Then in every handler we check if this attribute is not null. If it's not null then we check that the current transaction is same as the transaction for which lastTransferToZero was populated. If it is then we don't do anything as we are not yet sure if it's manual transfer or burn transaction. In the Burn event handler we set lastTransferToZero to null because we don't need to process it as a manual transfer to zero. If current transaction being process is different than the lastTransferToZero then we know that there was not Burn transaction for this transfer to zero transaction because if it was a burn transaction then lastTransferToZero would have been null. So in the case when lastTransferToZero is not null and is different than current transaction being process then it's a manual transfer to zero and then we process it as a redeemFromMarket for the user sending the LP tokens.
To understand the code around this you can look for pair.lastTransferZero and checkIncompleteBurnFromLastTransaction calls in the subgraph code.

Finished

This is it fellow developers, we have completed the Sushi Swap subgraph and are now able to track all the user positions in all the pairs of Sushi Swap protocol.
Thank you for taking interest in learning about SimpleFi Dashboard. Please join our discord to get a. We will keep working on this tutorial to add more details based on your feedback and our findings to make it a self sufficient guide to subgraph development for integration with SimpleFi Dashboad.