-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
95 lines (85 loc) · 2.49 KB
/
utils.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
callReadOnlyFunction,
cvToJSON,
cvToValue,
standardPrincipalCV,
uintCV,
} from "@stacks/transactions";
import { StacksMainnet } from "@stacks/network";
export const STACKS_NETWORK = new StacksMainnet();
STACKS_NETWORK.coreApiUrl = "https://stacks-node-api.stacks.co";
export async function getBlockHeight() {
const url = `${STACKS_NETWORK.coreApiUrl}/v2/info`;
const result = await fetch(url);
const resultJson = await result.json();
return resultJson.stacks_tip_height;
}
export async function getRewardCycle(
contractAddress,
contractName,
blockHeight
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-reward-cycle",
functionArgs: [uintCV(blockHeight)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return parseInt(result.value.value);
}
export async function getUserId(contractAddress, contractName, address) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-user-id",
functionArgs: [standardPrincipalCV(address)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToValue(resultCv);
return parseInt(result.value);
}
export async function getStackerAtCycleOrDefault(
contractAddress,
contractName,
cycleId,
userId
) {
const resultCv = await callReadOnlyFunction({
contractAddress: contractAddress,
contractName: contractName,
functionName: "get-stacker-at-cycle-or-default",
functionArgs: [uintCV(cycleId), uintCV(userId)],
network: STACKS_NETWORK,
senderAddress: contractAddress,
});
const result = cvToJSON(resultCv);
return result;
}
export async function getStacked(contractAddress, contractName, wallet) {
const [blockHeight, userId] = await Promise.all([
getBlockHeight(),
getUserId(contractAddress, contractName, wallet),
]);
const rewardCycle = await getRewardCycle(
contractAddress,
contractName,
blockHeight
);
const stacked = await getStackerAtCycleOrDefault(
contractAddress,
contractName,
rewardCycle,
userId
);
return Number(stacked?.value?.amountStacked?.value);
}
export async function getStxBalance(address) {
const url = `${STACKS_NETWORK.coreApiUrl}/extended/v1/address/${address}/balances`;
const result = await fetch(url);
const resultJson = await result.json();
return resultJson;
}