UNPKG

ether-unit-converter

Version:

The utility functions provide a conversation assortment of common utility functions, and can easily convert Wei to value and value to Wei without a round number.

47 lines (41 loc) 1.17 kB
const Web3 = require('web3'); const EthJsUnit = require('./ethJsUnit'); function getUnitValue(unit) { unit = unit ? unit : ''; if (!EthJsUnit.unitMap[unit]) { throw new Error( 'This unit "' + unit + '" doesn\'t exist, please use the one of the following units' + JSON.stringify(EthJsUnit.unitMap, null, 2), ); } return unit; }; var fromWei = (number, unit) => { unit = getUnitValue(unit); if (!Web3.utils.isBN(number) && !(typeof number === 'string')) { throw new Error( 'Please pass numbers as strings or BN objects to avoid precision errors.', ); } return Web3.utils.isBN(number) ? EthJsUnit.fromWei(number, unit) : EthJsUnit.fromWei(number, unit).toString(10); }; var toWei = (number, unit) => { unit = getUnitValue(unit); if (!Web3.utils.isBN(number) && !(typeof number === 'string')) { throw new Error( 'Please pass numbers as strings or BN objects to avoid precision errors.', ); } return Web3.utils.isBN(number) ? EthJsUnit.toWei(number, unit) : EthJsUnit.toWei(number, unit).toString(10); }; module.exports = { fromWei, toWei, getUnitValue, };