This repository has been archived by the owner on Aug 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useFilecoinNetworkInfo.js
67 lines (63 loc) · 2.07 KB
/
useFilecoinNetworkInfo.js
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
import React, { useState, useEffect } from 'react'
import fetch from 'node-fetch'
import useFilecoinConfig from '@filecoin-shipyard/use-filecoin-config'
export default function useFilecoinNetworkInfo ({
interval = 1000
}) {
const [error, setError] = useState()
const [, configNetName] = useFilecoinConfig('net')
const [netName, setNetName] = useState()
const [headBlocks, setHeadBlocks] = useState()
const [height, setHeight] = useState()
const [updateTime, setUpdateTime] = useState()
useEffect(() => {
const netName = configNetName ? configNetName : 'devnet-user'
setNetName(netName)
const state = {
timeoutId: null,
height
}
async function doWork () {
try {
let api
if (netName === 'devnet-user') {
api = 'http://user.kittyhawk.wtf:8000/api'
} else if (netName === 'devnet-nightly') {
api = 'https://explorer.nightly.kittyhawk.wtf/api'
} else if (netName === 'devnet-staging') {
api = 'https://explorer.staging.kittyhawk.wtf/api'
}
if (!api) return
const response = await fetch(`${api}/chain/head`)
const headCids = await response.json()
const headBlocks = {}
let newHeight
for (const cid of headCids) {
const cidString = cid['/']
const response = await fetch(`${api}/show/block/${cidString}`)
const block = await response.json()
headBlocks[cid.toString()] = block
newHeight = Number(block.Header.height)
}
setHeadBlocks(headBlocks)
if (newHeight !== state.height) {
state.height = newHeight
setHeight(state.height)
setUpdateTime(Date.now())
}
setError(null)
} catch (err) {
setError(err)
}
}
function schedule () {
state.timeoutId = setTimeout(async () => {
await doWork()
schedule()
}, interval)
}
doWork().then(schedule)
return () => clearTimeout(state.timeoutId)
}, [configNetName])
return [error, netName, headBlocks, height, updateTime]
}