-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbalances.tsx
170 lines (147 loc) · 4.44 KB
/
balances.tsx
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import BigNumber from 'bignumber.js';
import {
getNativeToken,
getToken,
KnownToken,
} from '../../../../config/lib/helpers';
import { ID, Level } from '../../blocks/lib/blocks';
import config from './../../../../config/config/environment';
export interface Balance {
// ID = blockLevel-address-tokenId
id: ID;
level: string;
amount: string;
}
export const getBalanceId = (
level: Level,
address: string,
tokenId: KnownToken
): string => `${level}-${address}-${tokenId}`;
export type FetchNativeBalanceAtBlockResponse = string;
export const getNativeBalanceURL = (address: string, level: Level): string =>
`${config.API_URL}/v1/accounts/${address}/balance_history/${level}`;
export const fetchNativeBalanceAtBlockLevel = async (
level: Level,
address: string
): Promise<Balance> => {
const url = getNativeBalanceURL(address, level);
const response = await fetch(url);
if (!response.ok) throw new Error(await response.text());
const body =
await (response.json() as Promise<FetchNativeBalanceAtBlockResponse>);
// get the ID of the native token
const tokenId = getNativeToken().id;
const id = getBalanceId(level, address, tokenId);
const balance: Balance = {
id,
level,
amount: body,
};
return balance;
};
export interface FetchNonNativeBalanceResponseItem {
balance: string;
['token.id']: string;
}
export type FetchNonNativeBalanceResponse = FetchNonNativeBalanceResponseItem[];
export const getNonNativeBalanceURL = (
level: Level,
address: string,
tokenIds: KnownToken[]
): string => {
const queryParams: string = [
`account.eq=${address}`,
`token.id.in=${tokenIds.join(',')}`,
'select=balance,token.id',
].join('&');
return `${config.API_URL}/v1/tokens/historical_balances/${level}?${queryParams}`;
};
export const fetchNonNativeBalancesAtBlockLevel = async (
level: Level,
address: string,
tokenIds: KnownToken[]
): Promise<Balance[]> => {
if (tokenIds.length === 0)
throw new Error('You must specify at least one tokenId');
const url = getNonNativeBalanceURL(level, address, tokenIds);
const response = await fetch(url);
if (!response.ok) throw new Error(await response.text());
let body = await (response.json() as Promise<FetchNonNativeBalanceResponse>);
// if there are no balances returned ([]), then pretend we received a zero balance resposne array
if (!body.length) {
body = tokenIds.map((tokenId) => {
return {
'token.id': tokenId,
balance: '0',
};
});
}
const balances: Balance[] = body.map((balanceResponseItem) => {
const id = getBalanceId(level, address, balanceResponseItem['token.id']);
return {
id,
level,
amount: balanceResponseItem.balance,
};
});
return balances;
};
export const fetchBalancesAtBlockLevel = async (
level: Level,
address: string,
tokenIds: KnownToken[]
): Promise<Balance[]> => {
let balances: Balance[] = [];
// native balance
const nativeTokenId = getNativeToken().id;
const shouldFetchNativeBalance = tokenIds.includes(nativeTokenId);
if (shouldFetchNativeBalance) {
const nativeBalance = await fetchNativeBalanceAtBlockLevel(level, address);
balances.push(nativeBalance);
}
// non native balance
const nonNativeTokenIds = tokenIds.filter(
(tokenId) => tokenId !== nativeTokenId
);
if (nonNativeTokenIds.length > 0) {
const nonNativeBalances = await fetchNonNativeBalancesAtBlockLevel(
level,
address,
nonNativeTokenIds
);
balances = balances.concat(nonNativeBalances);
}
return balances;
};
export const fetchBalancesAtBlockLevels = async (
levels: Level[],
address: string,
tokenIds: KnownToken[]
): Promise<Balance[]> => {
const balances: Array<Promise<Balance[]>> = [];
// fetch balances for all tokenIds at all requested levels
levels.forEach((level) => {
const additionalBalances = fetchBalancesAtBlockLevel(
level,
address,
tokenIds
);
balances.push(additionalBalances);
});
const resolvedBalances = (await Promise.all(balances)).reduce(
(balances, balancesAtLevel) => {
return balances.concat(balancesAtLevel);
},
[]
);
return resolvedBalances;
};
export const MAX_DECIMALS = 6;
export const toDecimals = (balance: Balance, tokenId: KnownToken): string => {
const {
metadata: { decimals },
} = getToken(tokenId);
return new BigNumber(balance.amount)
.dividedBy(new BigNumber(10).pow(decimals))
.toFixed(MAX_DECIMALS);
};