forked from muttoni/fcl-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend-get-block-header.js
75 lines (54 loc) · 2.18 KB
/
send-get-block-header.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
68
69
70
71
72
73
74
75
import {invariant} from "@onflow/util-invariant"
import {GetLatestBlockHeaderRequest, GetBlockHeaderByIDRequest, GetBlockHeaderByHeightRequest, AccessAPI} from "@onflow/protobuf"
import {response} from "../response/response.js"
import {unary as defaultUnary} from "./unary"
const u8ToHex = u8 => Buffer.from(u8).toString("hex")
const hexBuffer = hex => Buffer.from(hex, "hex")
async function sendGetBlockHeaderByIDRequest(ix, opts) {
const unary = opts.unary || defaultUnary
const req = new GetBlockHeaderByIDRequest()
req.setId(hexBuffer(ix.block.id))
const res = await unary(opts.node, AccessAPI.GetBlockHeaderByID, req)
return constructResponse(ix, res)
}
async function sendGetBlockHeaderByHeightRequest(ix, opts) {
const unary = opts.unary || defaultUnary
const req = new GetBlockHeaderByHeightRequest()
req.setHeight(Number(ix.block.height))
const res = await unary(opts.node, AccessAPI.GetBlockHeaderByHeight, req)
return constructResponse(ix, res)
}
async function sendGetLatestBlockHeaderRequest(ix, opts) {
const unary = opts.unary || defaultUnary
const req = new GetLatestBlockHeaderRequest()
if (ix.block?.isSealed) {
req.setIsSealed(ix.block.isSealed)
}
const res = await unary(opts.node, AccessAPI.GetLatestBlockHeader, req)
return constructResponse(ix, res)
}
function constructResponse(ix, res) {
const blockHeader = res.getBlock()
const ret = response()
ret.tag = ix.tag
ret.blockHeader = {
id: u8ToHex(blockHeader.getId_asU8()),
parentId: u8ToHex(blockHeader.getParentId_asU8()),
height: blockHeader.getHeight(),
timestamp: blockHeader.getTimestamp().toDate().toISOString(),
}
return ret
}
export async function sendGetBlockHeader(ix, opts = {}) {
invariant(opts.node, `SDK Send Get Block Header Error: opts.node must be defined.`)
ix = await ix
const interactionHasBlockID = ix.block.id !== null
const interactionHasBlockHeight = ix.block.height !== null
if (interactionHasBlockID) {
return await sendGetBlockHeaderByIDRequest(ix, opts)
} else if (interactionHasBlockHeight) {
return await sendGetBlockHeaderByHeightRequest(ix, opts)
} else {
return await sendGetLatestBlockHeaderRequest(ix, opts)
}
}