This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
71 lines (58 loc) · 1.94 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"log"
"morph-tracking-api/database"
"morph-tracking-api/router"
"morph-tracking-api/rpc"
"time"
)
// BlockRange number of blocks that will be processed each iteration
const BlockRange = 500
func main() {
db := database.New()
rpcClient := rpc.New()
// Run the RPC listener on the background.
go CrawlMorph(db, rpcClient)
router.Listen(db)
}
func CrawlMorph(db *database.AxieDB, rpcClient *rpc.Client) {
// Create the starting and ending block for polling.
currentBlock := db.GetLatestBlock()
endBlock := rpc.GetLatestBlockNumber(rpcClient)
for ; currentBlock <= endBlock; {
// Get the logs for morphing events between the current and end block numbers.
log.Println("Fetching block", currentBlock, "to", currentBlock+BlockRange)
filter := rpc.GetMorphFilter(int64(currentBlock), int64(currentBlock+BlockRange))
logs := rpc.GetLogs(rpcClient, filter)
if len(logs) == 0 {
currentBlock = GetNextStartingBlock(currentBlock, endBlock)
endBlock = GetNextEndBlock(rpcClient, currentBlock)
continue
}
// Get the timestamp of the blocks with morph event
log.Println("Processing", len(logs), "blocks")
blocksNumbers := rpc.GetBlocksFromLogs(logs)
blocks := rpc.GetBlocks(rpcClient, blocksNumbers)
// Get the morphed Axie details from the logs
axies := rpc.GetAxieFromLogs(blocks, logs)
// Save the results to the database
db.SaveAxieMultiple(axies)
currentBlock = GetNextStartingBlock(currentBlock, endBlock)
endBlock = GetNextEndBlock(rpcClient, currentBlock)
}
}
func GetNextStartingBlock(currentBlock uint64, endBlock uint64) uint64 {
nextBlock := currentBlock + BlockRange
if nextBlock > endBlock {
return endBlock
}
return nextBlock
}
func GetNextEndBlock(rpcClient *rpc.Client, currentBlock uint64) uint64 {
nextBlock := rpc.GetLatestBlockNumber(rpcClient)
for currentBlock == nextBlock {
time.Sleep(30 * time.Second)
nextBlock = rpc.GetLatestBlockNumber(rpcClient)
}
return nextBlock
}