aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/send_/send-footer/send-footer.utils.js
blob: 353c0e3472c7b7d24e374c6d342e1890409c2efc (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
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
import ethAbi from 'ethereumjs-abi'
import ethUtil from 'ethereumjs-util'
import { TOKEN_TRANSFER_FUNCTION_SIGNATURE } from '../send.constants'

function formShouldBeDisabled ({ inError, selectedToken, tokenBalance, gasTotal }) {
  const missingTokenBalance = selectedToken && !tokenBalance
  return inError || !gasTotal || missingTokenBalance
}

function addHexPrefixToObjectValues (obj) {
  return Object.keys(obj).reduce((newObj, key) => {
    return { ...newObj, [key]: ethUtil.addHexPrefix(obj[key]) }
  }, {})
}

function constructTxParams ({ selectedToken, to, amount, from, gas, gasPrice }) {
  const txParams = {
    from,
    value: '0',
    gas,
    gasPrice,
  }

  if (!selectedToken) {
    txParams.value = amount
    txParams.to = to
  }

  const hexPrefixedTxParams = addHexPrefixToObjectValues(txParams)

  return hexPrefixedTxParams
}

function constructUpdatedTx ({
  amount,
  editingTransactionId,
  from,
  gas,
  gasPrice,
  selectedToken,
  to,
  unapprovedTxs,
}) {
  const editingTx = {
    ...unapprovedTxs[editingTransactionId],
    txParams: addHexPrefixToObjectValues({ from, gas, gasPrice }),
  }

  if (selectedToken) {
    const data = TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call(
      ethAbi.rawEncode(['address', 'uint256'], [to, ethUtil.addHexPrefix(amount)]),
      x => ('00' + x.toString(16)).slice(-2)
    ).join('')

    Object.assign(editingTx.txParams, addHexPrefixToObjectValues({
      value: '0',
      to: selectedToken.address,
      data,
    }))
  } else {
    const { data } = unapprovedTxs[editingTransactionId].txParams

    Object.assign(editingTx.txParams, addHexPrefixToObjectValues({
      value: amount,
      to,
      data,
    }))

    if (typeof editingTx.txParams.data === 'undefined') {
      delete editingTx.txParams.data
    }
  }
}

function addressIsNew (toAccounts, newAddress) {
  return !toAccounts.find(({ address }) => newAddress === address)
}

module.exports = {
  addressIsNew,
  formShouldBeDisabled,
  constructTxParams,
  constructUpdatedTx,
}