controllers/transactions/lib/util.js

  1. const {
  2. addHexPrefix,
  3. isValidAddress,
  4. } = require('ethereumjs-util')
  5. /**
  6. @module
  7. */
  8. module.exports = {
  9. normalizeTxParams,
  10. validateTxParams,
  11. validateFrom,
  12. validateRecipient,
  13. getFinalStates,
  14. }
  15. // functions that handle normalizing of that key in txParams
  16. const normalizers = {
  17. from: from => addHexPrefix(from).toLowerCase(),
  18. to: to => addHexPrefix(to).toLowerCase(),
  19. nonce: nonce => addHexPrefix(nonce),
  20. value: value => addHexPrefix(value),
  21. data: data => addHexPrefix(data),
  22. gas: gas => addHexPrefix(gas),
  23. gasPrice: gasPrice => addHexPrefix(gasPrice),
  24. }
  25. /**
  26. normalizes txParams
  27. @param txParams {object}
  28. @returns {object} normalized txParams
  29. */
  30. function normalizeTxParams (txParams) {
  31. // apply only keys in the normalizers
  32. const normalizedTxParams = {}
  33. for (const key in normalizers) {
  34. if (txParams[key]) normalizedTxParams[key] = normalizers[key](txParams[key])
  35. }
  36. return normalizedTxParams
  37. }
  38. /**
  39. validates txParams
  40. @param txParams {object}
  41. */
  42. function validateTxParams (txParams) {
  43. validateFrom(txParams)
  44. validateRecipient(txParams)
  45. if ('value' in txParams) {
  46. const value = txParams.value.toString()
  47. if (value.includes('-')) {
  48. throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)
  49. }
  50. if (value.includes('.')) {
  51. throw new Error(`Invalid transaction value of ${txParams.value} number must be in wei`)
  52. }
  53. }
  54. }
  55. /**
  56. validates the from field in txParams
  57. @param txParams {object}
  58. */
  59. function validateFrom (txParams) {
  60. if (!(typeof txParams.from === 'string')) throw new Error(`Invalid from address ${txParams.from} not a string`)
  61. if (!isValidAddress(txParams.from)) throw new Error('Invalid from address')
  62. }
  63. /**
  64. validates the to field in txParams
  65. @param txParams {object}
  66. */
  67. function validateRecipient (txParams) {
  68. if (txParams.to === '0x' || txParams.to === null) {
  69. if (txParams.data) {
  70. delete txParams.to
  71. } else {
  72. throw new Error('Invalid recipient address')
  73. }
  74. } else if (txParams.to !== undefined && !isValidAddress(txParams.to)) {
  75. throw new Error('Invalid recipient address')
  76. }
  77. return txParams
  78. }
  79. /**
  80. @returns an {array} of states that can be considered final
  81. */
  82. function getFinalStates () {
  83. return [
  84. 'rejected', // the user has responded no!
  85. 'confirmed', // the tx has been included in a block.
  86. 'failed', // the tx failed for some reason, included on tx data.
  87. 'dropped', // the tx nonce was already used
  88. ]
  89. }