1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-12 04:37:13 +01:00
metamask-extension/ui/app/token-util.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

const log = require('loglevel')
const util = require('./util')
2018-07-23 09:28:45 +02:00
const BigNumber = require('bignumber.js')
function tokenInfoGetter () {
const tokens = {}
return async (address) => {
if (tokens[address]) {
return tokens[address]
}
tokens[address] = await getSymbolAndDecimals(address)
return tokens[address]
}
}
async function getSymbolAndDecimals (tokenAddress, existingTokens = []) {
const existingToken = existingTokens.find(({ address }) => tokenAddress === address)
if (existingToken) {
return existingToken
}
2018-07-03 00:49:33 +02:00
let result = []
try {
const token = util.getContractAtAddress(tokenAddress)
result = await Promise.all([
token.symbol(),
token.decimals(),
])
} catch (err) {
log.warn(`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`, err)
}
const [ symbol = [], decimals = [] ] = result
return {
symbol: symbol[0] || null,
decimals: decimals[0] && decimals[0].toString() || null,
}
}
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()
}
module.exports = {
tokenInfoGetter,
calcTokenAmount,
getSymbolAndDecimals,
}