-
Notifications
You must be signed in to change notification settings - Fork 22
/
hub.js
388 lines (340 loc) · 11.5 KB
/
hub.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import axios, {AxiosError} from 'axios';
import {cacheAdapterEnhancer, Cache} from 'axios-extensions';
import {TinyEmitter as Emitter} from 'tiny-emitter';
import stripZeros from 'pretty-num/src/strip-zeros.js';
import {isValidAddress as isValidMinterAddress} from 'minterjs-util';
import {isValidAddress as isValidEthAddress} from 'ethereumjs-util';
import {getCoinList} from '~/api/explorer.js';
import Big from '~/assets/big.js';
import {HUB_API_URL, HUB_TRANSFER_STATUS, HUB_CHAIN_ID, HUB_NETWORK_SLUG, NETWORK, MAINNET, BASE_COIN, HUB_CHAIN_BY_ID, HUB_CHAIN_DATA} from "~/assets/variables.js";
import addToCamelInterceptor from '~/assets/axios-to-camel.js';
import {getDefaultAdapter} from '~/assets/axios-default-adapter.js';
import {isHubTransferFinished} from '~/assets/utils.js';
const instance = axios.create({
baseURL: HUB_API_URL,
adapter: cacheAdapterEnhancer(getDefaultAdapter(), { enabledByDefault: false}),
});
addToCamelInterceptor(instance);
const fastCache = new Cache({ttl: 5 * 1000, max: 100});
/**
* Withdraw tx fee in dollars
* @param {HUB_CHAIN_ID} network
* @return {Promise<{min: string, fast: string}>}
*/
export function getOracleFee(network) {
return instance.get(`oracle/v1/${network}_fee`, {
cache: fastCache,
})
.then((response) => {
return response.data;
});
}
/**
* @return {Promise<Array<HubCoinItem>>}
*/
export function getOracleCoinList() {
return Promise.all([_getOracleCoinListGroupedByMinter(), getCoinList({skipMeta: true})])
.then(([oracleCoinList, minterCoinList]) => {
oracleCoinList.forEach((oracleCoin) => {
const minterCoin = minterCoinList.find((item) => item.id === Number(oracleCoin.minterId));
if (minterCoin) {
oracleCoin.symbol = minterCoin.symbol;
oracleCoin.universalSymbol = getUniversalSymbol(oracleCoin);
}
});
return oracleCoinList
// filter out not existent coins
.filter((item) => item.symbol)
.sort((a, b) => {
// base coin goes first
if (a.symbol === BASE_COIN) {
return -1;
} else if (b.symbol === BASE_COIN) {
return 1;
}
// HUB goes second
if (a.symbol === 'HUB') {
return -1;
} else if (b.symbol === 'HUB') {
return 1;
}
return 0;
});
});
}
/**
* @param {HubCoinItem} hubCoin
* @return {string|*}
*/
function getUniversalSymbol(hubCoin) {
if (hubCoin[HUB_CHAIN_ID.ETHEREUM]) {
if (hubCoin[HUB_CHAIN_ID.ETHEREUM].denom === 'oneinch') {
return '1INCH';
}
return hubCoin[HUB_CHAIN_ID.ETHEREUM].denom.toUpperCase();
}
if (hubCoin[HUB_CHAIN_ID.BSC]) {
return hubCoin.symbol.replace(/BSC$/, '');
}
return hubCoin.symbol;
}
// 1 min cache
const coinsCache = new Cache({ttl: 1 * 60 * 1000, max: 100});
/**
* @return {Promise<TokenInfo.AsObject[]>}
*/
function _getOracleCoinList() {
return instance.get('mhub2/v1/token_infos', {
cache: coinsCache,
})
.then((response) => {
return response.data.list.tokenInfos;
});
}
/**
* @return {Promise<Array<HubCoinItem>>}
*/
function _getOracleCoinListGroupedByMinter() {
return _getOracleCoinList()
.then((tokenList) => {
tokenList = tokenList.map((item) => {
if (typeof item.externalTokenId === 'string') {
item.externalTokenId = item.externalTokenId.toLowerCase();
}
return item;
});
const minterTokenList = tokenList.filter((token) => token.chainId === HUB_CHAIN_ID.MINTER);
return minterTokenList
.map((minterToken) => {
function findToken(denom, chainId) {
return tokenList.find((item) => item.denom === denom && item.chainId === chainId);
}
return {
minterId: Number(minterToken.externalTokenId),
...minterToken,
[HUB_NETWORK_SLUG.ETHEREUM]: findToken(minterToken.denom, HUB_NETWORK_SLUG.ETHEREUM),
[HUB_NETWORK_SLUG.BSC]: findToken(minterToken.denom, HUB_NETWORK_SLUG.BSC),
[HUB_NETWORK_SLUG.MEGACHAIN]: findToken(minterToken.denom, HUB_NETWORK_SLUG.MEGACHAIN),
};
});
});
}
/**
* @return {Promise<TokenInfo.AsObject[]>}
*/
export function getVerifiedMinterCoinList() {
return _getOracleCoinList()
.then((tokenList) => {
return tokenList.filter((token) => token.chainId === HUB_CHAIN_ID.MINTER);
});
}
/**
* Prices of tokens in $
* @return {Promise<Array<HubPriceItem>>}
*/
export function getOraclePriceList() {
return instance.get('oracle/v1/prices', {
cache: fastCache,
})
.then((response) => {
return response.data.prices.list
.map((item) => {
item.value = stripZeros(item.value);
return item;
});
});
}
/**
* @param {string} address
* @return {Promise<number|string>}
*/
export function getDiscountForHolder(address) {
if (!isValidMinterAddress(address) && !isValidEthAddress(address)) {
return Promise.resolve(0);
}
address = address.replace(/^Mx/, '').replace(/^0x/, '');
return instance.get(`mhub2/v1/discount_for_holder/${address}`, {
cache: fastCache,
})
.then((response) => {
return response.data.discount;
});
}
/**
* @param {string} inputTxHash
* @return {Promise<HubTransferStatus>}
*/
export function getTransferStatus(inputTxHash) {
return instance.get(`mhub2/v1/transaction_status/${inputTxHash}`, {
cache: fastCache,
})
.then((response) => {
return response.data.status;
});
}
// 1 day
const persistentCache = new Cache({ttl: 24 * 60 * 60 * 1000, max: 100});
/**
* @param {string} inputTxHash
* @return {Promise<HubTransferFee>}
*/
export function getTransferFee(inputTxHash) {
return instance.get(`mhub2/v1/transaction_fee_record/${inputTxHash}`, {
cache: persistentCache,
})
.then((response) => {
if (!response.data.record) {
response.status = 404;
response.statusText = 'Not found';
response.request = {
...response.request,
status: 404,
statusText: 'Not found',
};
throw new AxiosError(
'Request failed with status code ' + response.status,
AxiosError.ERR_BAD_REQUEST,
response.config,
response.request,
response,
);
}
return {
valCommission: new Big(response.data.record.valCommission).div(1e18).toString(),
externalFee: new Big(response.data.record.externalFee).div(1e18).toString(),
};
});
}
/**
*
* @param {string} hash
* @param [timestamp]
* @return {Promise<HubTransferStatus>}
*/
export function subscribeTransfer(hash, timestamp) {
if (!hash) {
throw new Error('Tx hash not specified');
}
let isUnsubscribed = false;
let lastStatus;
const emitter = new Emitter();
const statusPromise = pollMinterTxStatus(hash)
.then((transfer) => {
emitter.emit('finished', transfer);
return transfer;
});
// proxy `.on` and `.once`
proxyEmitter(statusPromise, emitter);
// unsubscribe from all events and disable polling
statusPromise.unsubscribe = function() {
isUnsubscribed = true;
emitter.off('update');
emitter.off('finished');
};
return statusPromise;
function proxyEmitter(target, emitter) {
target.on = function() {
emitter.on(...arguments);
return target;
};
target.once = function() {
emitter.once(...arguments);
return target;
};
// target.off = function () {
// emitter.off(...arguments);
// return target;
// }
}
function pollMinterTxStatus(hash) {
return getTransferStatus(hash)
.catch((error) => {
console.log(error);
})
.then((transfer) => {
// reject
if (isUnsubscribed) {
throw new Error('unsubscribed');
}
// no transfer when error
if (transfer) {
const txDate = timestamp ? new Date(timestamp) : new Date();
const isLong = Date.now() - txDate.getTime() > 10 * 60 * 1000;
if (isLong && transfer.status === HUB_TRANSFER_STATUS.not_found) {
transfer = {
...transfer,
status: HUB_TRANSFER_STATUS.not_found_long,
};
}
if (lastStatus !== transfer.status) {
lastStatus = transfer.status;
emitter.emit('update', transfer);
}
if (isHubTransferFinished(transfer.status)) {
return transfer;
}
}
return wait(10000).then(() => pollMinterTxStatus(hash));
});
}
}
/**
* @param {Array<HubPriceItem>} priceList
* @return {number}
*/
export function getGasPriceGwei(priceList) {
//@TODO ETH/BNB
const priceItem = priceList.find((item) => item.name === 'eth/gas');
let gasPriceGwei;
if (!priceItem) {
gasPriceGwei = 100;
} else {
gasPriceGwei = priceItem.value / 10 ** 18;
}
return NETWORK === MAINNET ? gasPriceGwei : new Big(gasPriceGwei).times(10).toNumber();
}
/**
*
* @param {Array<HubCoinItem>} hubCoinList
* @param {string} tokenSymbol
* @param {number} chainId
* @return {TokenInfo.AsObject}
*/
export function findTokenInfo(hubCoinList, tokenSymbol, chainId) {
const coinItem = hubCoinList.find((item) => item.symbol === tokenSymbol);
return coinItem?.[HUB_CHAIN_BY_ID[chainId]?.hubChainId];
}
export function findNativeCoinSymbol(hubCoinList, network) {
const contractAddress = HUB_CHAIN_DATA[network].wrappedNativeContractAddress.toLowerCase();
const coinItem = hubCoinList.find((item) => item[network]?.externalTokenId.toLowerCase() === contractAddress);
return coinItem?.symbol;
}
function wait(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
/**
* @typedef {object} HubCoinItemMinterExtra
* @property {string} symbol - minter symbol
* @property {string} minterId
*/
/**
* @typedef {TokenInfo.AsObject & HubCoinItemMinterExtra & {ethereum: TokenInfo.AsObject, bsc: TokenInfo.AsObject}} HubCoinItem
*/
/**
* @typedef {object} HubPriceItem
* @property {string} name
* @property {number|string} value
*/
/**
* @typedef {object} HubTransferStatus
* @property {HUB_TRANSFER_STATUS} status
* @property {string} inTxHash
* @property {string} outTxHash
*/
/**
* @typedef {object} HubTransferFee
* @property {number|string} externalFee
* @property {number|string} valCommission
*/