forked from muttoni/fcl-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend-get-account.js
78 lines (59 loc) · 2.46 KB
/
send-get-account.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
76
77
78
import {invariant} from "@onflow/util-invariant"
import {GetAccountAtLatestBlockRequest, GetAccountAtBlockHeightRequest, AccessAPI} from "@onflow/protobuf"
import {response} from "../response/response.js"
import {sansPrefix, withPrefix} from "@onflow/util-address"
import {unary as defaultUnary} from "./unary"
const u8ToHex = u8 => Buffer.from(u8).toString("hex")
const paddedHexBuffer = (hex, pad) =>
Buffer.from(hex.padStart(pad * 2, 0), "hex")
const addressBuffer = addr => paddedHexBuffer(addr, 8)
async function sendGetAccountAtBlockHeightRequest(ix, opts) {
const unary = opts.unary || defaultUnary
const req = new GetAccountAtBlockHeightRequest()
req.setBlockHeight(Number(ix.block.height))
req.setAddress(addressBuffer(sansPrefix(ix.account.addr)))
const res = await unary(opts.node, AccessAPI.GetAccountAtBlockHeight, req)
return constructResponse(ix, res)
}
async function sendGetAccountAtLatestBlockRequest(ix, opts) {
const unary = opts.unary || defaultUnary
const req = new GetAccountAtLatestBlockRequest()
req.setAddress(addressBuffer(sansPrefix(ix.account.addr)))
const res = await unary(opts.node, AccessAPI.GetAccountAtLatestBlock, req)
return constructResponse(ix, res)
}
function constructResponse(ix, res) {
let ret = response()
ret.tag = ix.tag
const account = res.getAccount()
let contractsMap;
const contracts = (contractsMap = account.getContractsMap()) ? contractsMap.getEntryList().reduce((acc, contract) => ({
...acc,
[contract[0]]: Buffer.from(contract[1] || new UInt8Array()).toString("utf8")
}), {}) : {}
ret.account = {
address: withPrefix(u8ToHex(account.getAddress_asU8())),
balance: account.getBalance(),
code: Buffer.from(account.getCode_asU8() || new UInt8Array()).toString("utf8"),
contracts,
keys: account.getKeysList().map(publicKey => ({
index: publicKey.getIndex(),
publicKey: u8ToHex(publicKey.getPublicKey_asU8()),
signAlgo: publicKey.getSignAlgo(),
hashAlgo: publicKey.getHashAlgo(),
weight: publicKey.getWeight(),
sequenceNumber: publicKey.getSequenceNumber(),
revoked: publicKey.getRevoked(),
})),
}
return ret
}
export async function sendGetAccount(ix, opts = {}) {
invariant(opts.node, `SDK Send Get Account Error: opts.node must be defined.`)
ix = await ix
if (ix.block.height !== null) {
return await sendGetAccountAtBlockHeightRequest(ix, opts)
} else {
return await sendGetAccountAtLatestBlockRequest(ix, opts)
}
}