2018-05-18 19:51:49 +02:00
|
|
|
const log = require('loglevel')
|
2018-04-28 01:15:36 +02:00
|
|
|
const util = require('./util')
|
2018-07-23 09:28:45 +02:00
|
|
|
const BigNumber = require('bignumber.js')
|
2017-10-27 19:39:40 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
function tokenInfoGetter () {
|
2017-10-27 19:39:40 +02:00
|
|
|
const tokens = {}
|
|
|
|
|
|
|
|
return async (address) => {
|
|
|
|
if (tokens[address]) {
|
|
|
|
return tokens[address]
|
|
|
|
}
|
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
tokens[address] = await getSymbolAndDecimals(address)
|
2017-10-27 19:39:40 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
return tokens[address]
|
|
|
|
}
|
|
|
|
}
|
2017-10-27 19:39:40 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
async function getSymbolAndDecimals (tokenAddress, existingTokens = []) {
|
|
|
|
const existingToken = existingTokens.find(({ address }) => tokenAddress === address)
|
|
|
|
if (existingToken) {
|
2018-04-28 02:08:57 +02:00
|
|
|
return existingToken
|
2018-04-28 01:15:36 +02:00
|
|
|
}
|
2018-07-03 00:49:33 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
let result = []
|
|
|
|
try {
|
|
|
|
const token = util.getContractAtAddress(tokenAddress)
|
|
|
|
|
|
|
|
result = await Promise.all([
|
|
|
|
token.symbol(),
|
|
|
|
token.decimals(),
|
|
|
|
])
|
|
|
|
} catch (err) {
|
2018-05-18 19:51:49 +02:00
|
|
|
log.warn(`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`, err)
|
2018-04-28 01:15:36 +02:00
|
|
|
}
|
2017-10-27 19:39:40 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
const [ symbol = [], decimals = [] ] = result
|
2017-10-27 19:39:40 +02:00
|
|
|
|
2018-04-28 01:15:36 +02:00
|
|
|
return {
|
2018-04-28 02:03:56 +02:00
|
|
|
symbol: symbol[0] || null,
|
|
|
|
decimals: decimals[0] && decimals[0].toString() || null,
|
2017-10-27 19:39:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-30 18:48:50 +01:00
|
|
|
function calcTokenAmount (value, decimals) {
|
|
|
|
const multiplier = Math.pow(10, Number(decimals || 0))
|
2018-07-23 10:23:34 +02:00
|
|
|
return new BigNumber(value).div(multiplier).toNumber()
|
2017-10-30 18:48:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-10-27 19:39:40 +02:00
|
|
|
module.exports = {
|
|
|
|
tokenInfoGetter,
|
2017-10-30 18:48:50 +01:00
|
|
|
calcTokenAmount,
|
2018-04-28 01:15:36 +02:00
|
|
|
getSymbolAndDecimals,
|
2017-10-27 19:39:40 +02:00
|
|
|
}
|