-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathgetTokenBalance.ts
70 lines (65 loc) · 1.98 KB
/
getTokenBalance.ts
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
import TOKENS from "./default-tokens.json";
import { encode, uint256 } from "starknet-410";
import { formatTokenBalance } from "./formatTokenBalance";
import { getRpcBatchProviderForNetworkId } from "./getProvider";
import { NetworkId } from "./types";
export async function getBalances(
addresses: string[],
networkId: NetworkId,
tokenWhiteList: string[] = []
) {
const tokens = TOKENS.filter((token) => token.network === networkId).filter(
(token) => {
if (tokenWhiteList.length) {
return tokenWhiteList.includes(token.symbol);
} else {
return true;
}
}
);
const tokenAddresses = tokens.map((token) => token.address);
const multicall = getRpcBatchProviderForNetworkId(networkId);
const addressesTokensCombinations = tokenAddresses.flatMap((token) =>
addresses.map((address) => ({ address, token }))
);
const results = await Promise.allSettled(
addressesTokensCombinations.map(({ address, token }) =>
multicall.callContract({
contractAddress: token,
entrypoint: "balanceOf",
calldata: [address],
})
)
).then((results) =>
results.map((result) => {
if (result.status === "fulfilled" && result.value !== undefined) {
return result.value;
} else {
return null;
}
})
);
if (addressesTokensCombinations.length !== results.length) {
throw new Error("Unable to determine token balances");
}
return addressesTokensCombinations.map((addressToken, index) => {
const balance = results[index];
const rawBalance = balance
? uint256
.uint256ToBN({
low: encode.addHexPrefix(balance[0]),
high: encode.addHexPrefix(balance[1]),
})
.toString()
: "0";
return {
address: addressToken.address,
token: addressToken.token,
rawBalance,
balance: formatTokenBalance(
rawBalance,
tokens.find((x) => x.address === addressToken.token)!.decimals
),
};
});
}