aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/token-util.js
blob: 920442bfc2757d7a24654276d335f32007010fca (plain) (blame)
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
const util = require('./util')

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
  }
  
  let result = []
  try {
    const token = util.getContractAtAddress(tokenAddress)

    result = await Promise.all([
      token.symbol(),
      token.decimals(),
    ])
  } catch (err) {
    console.log(`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))
  const amount = Number(value / multiplier)

  return amount
}


module.exports = {
  tokenInfoGetter,
  calcTokenAmount,
  getSymbolAndDecimals,
}