# All files / web3-utils/src index.js

88.75% Statements 71/80
74.19% Branches 46/62
100% Functions 11/11
88.31% Lines 68/77

    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
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321

    2x
    2x
    2x
    2x
    2x

    2x

    13x

    13x

    13x
    4x

    13x

    13x

    3x

    10x

    4x

    13x
    13x

    13x

    7x
    7x
    7x

    13x

    2x
    567x

    1003x
    567x

    2x
    3x

    3x
    3x
    3x
    3x

    3x
    97x
    97x

    3x

    2x
    3x
    3x
    97x
    97x
    97x

    3x

    2x
    41x
    41x
    1x

    40x

    2x
    12x

    12x

    12x

    2x
    29x

    28x

    28x

    2x
    347x

    345x

    345x
    345x
    345x

    345x

    13800x
    6935x

    6865x

    345x

    2x

     /*
     This file is part of web3.js.

     web3.js is free software: you can redistribute it and/or modify
     it under the terms of the GNU Lesser General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     web3.js is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.

     You should have received a copy of the GNU Lesser General Public License
     along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
     */
    /**
     * @file utils.js
     * @author Marek Kotewicz <marek@parity.io>
     * @author Fabian Vogelsteller <fabian@ethereum.org>
     * @date 2017
     */

    var _ = require('underscore');
    var ethjsUnit = require('ethjs-unit');
    var utils = require('./utils.js');
    var soliditySha3 = require('./soliditySha3.js');
    var randomHex = require('randomhex');

    /**
     * Fires an error in an event emitter and callback and returns the eventemitter
     *
     * @method _fireError
     * @param {Object} error a string, a error, or an object with {message, data}
     * @param {Object} emitter
     * @param {Function} reject
     * @param {Function} callback
     * @return {Object} the emitter
     */
    var _fireError = function (error, emitter, reject, callback) {
        // add data if given
        Iif(_.isObject(error) && !(error instanceof Error) &&  error.data) {
            if(_.isObject(error.data) || _.isArray(error.data)) {
                error.data = JSON.stringify(error.data, null, 2);
            }

            error = error.message +"\n"+ error.data;
        }

        Iif(_.isString(error)) {
            error = new Error(error);
        }

        if (_.isFunction(callback)) {
            callback(error);
        }
        Eif (_.isFunction(reject)) {
            // suppress uncatched error if an error listener is present
            if (emitter &&
                _.isFunction(emitter.listeners) &&
                emitter.listeners('error').length &&
                _.isFunction(emitter.suppressUnhandledRejections)) {
                emitter.suppressUnhandledRejections();
            // OR suppress uncatched error if an callback listener is present
            } else if(_.isFunction(callback) &&
                _.isFunction(emitter.suppressUnhandledRejections)) {
                emitter.suppressUnhandledRejections();
            }
            // reject later, to be able to return emitter
            setTimeout(function () {
                reject(error);
            }, 1);
        }

        if(emitter && _.isFunction(emitter.emit)) {
            // emit later, to be able to return emitter
            setTimeout(function () {
                emitter.emit('error', error);
                emitter.removeAllListeners();
            }, 1);
        }

        return emitter;
    };

    /**
     * Should be used to create full function/event name from json abi
     *
     * @method _jsonInterfaceMethodToString
     * @param {Object} json
     * @return {String} full function/event name
     */
    var _jsonInterfaceMethodToString = function (json) {
        Iif (_.isObject(json) && json.name && json.name.indexOf('(') !== -1) {
            return json.name;
        }

        var typeName = json.inputs.map(function(i){return i.type; }).join(',');
        return json.name + '(' + typeName + ')';
    };

    /**
     * Should be called to get ascii from it's hex representation
     *
     * @method hexToAscii
     * @param {String} hex
     * @returns {String} ascii string representation of hex value
     */
    var hexToAscii = function(hex) {
        Iif (!utils.isHexStrict(hex))
            throw new Error('The parameter must be a valid HEX string.');

        var str = "";
        var i = 0, l = hex.length;
        Eif (hex.substring(0, 2) === '0x') {
            i = 2;
        }
        for (; i < l; i+=2) {
            var code = parseInt(hex.substr(i, 2), 16);
            str += String.fromCharCode(code);
        }

        return str;
    };

    /**
     * Should be called to get hex representation (prefixed by 0x) of ascii string
     *
     * @method asciiToHex
     * @param {String} str
     * @returns {String} hex representation of input string
     */
    var asciiToHex = function(str) {
        var hex = "";
        for(var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i);
            var n = code.toString(16);
            hex += n.length < 2 ? '0' + n : n;
        }

        return "0x" + hex;
    };

    /**
     * Returns value of unit in Wei
     *
     * @method getUnitValue
     * @param {String} unit the unit to convert to, default ether
     * @returns {BN} value of the unit (in Wei)
     * @throws error if the unit is not correct:w
     */
    var getUnitValue = function (unit) {
        unit = unit ? unit.toLowerCase() : 'ether';
        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;
    };

    /**
     * Takes a number of wei and converts it to any other ether unit.
     *
     * Possible units are:
     *   SI Short   SI Full        Effigy       Other
     * - kwei       femtoether     babbage
     * - mwei       picoether      lovelace
     * - gwei       nanoether      shannon      nano
     * - --         microether     szabo        micro
     * - --         milliether     finney       milli
     * - ether      --             --
     * - kether                    --           grand
     * - mether
     * - gether
     * - tether
     *
     * @method fromWei
     * @param {Number|String} number can be a number, number string or a HEX of a decimal
     * @param {String} unit the unit to convert to, default ether
     * @return {String|Object} When given a BN object it returns one as well, otherwise a number
     */
    var fromWei = function(number, unit) {
        unit = getUnitValue(unit);

        Iif(!utils.isBN(number) && !_.isString(number)) {
            throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.');
        }

        return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10);
    };

    /**
     * Takes a number of a unit and converts it to wei.
     *
     * Possible units are:
     *   SI Short   SI Full        Effigy       Other
     * - kwei       femtoether     babbage
     * - mwei       picoether      lovelace
     * - gwei       nanoether      shannon      nano
     * - --         microether     szabo        micro
     * - --         microether     szabo        micro
     * - --         milliether     finney       milli
     * - ether      --             --
     * - kether                    --           grand
     * - mether
     * - gether
     * - tether
     *
     * @method toWei
     * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal
     * @param {String} unit the unit to convert from, default ether
     * @return {String|Object} When given a BN object it returns one as well, otherwise a number
     */
    var toWei = function(number, unit) {
        unit = getUnitValue(unit);

        Iif(!utils.isBN(number) && !_.isString(number)) {
            throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.');
        }

        return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10);
    };

    /**
     * Converts to a checksum address
     *
     * @method toChecksumAddress
     * @param {String} address the given HEX address
     * @return {String}
     */
    var toChecksumAddress = function (address) {
        if (typeof address === 'undefined') return '';

        Iif(!/^(0x)?[0-9a-f]{40}$/i.test(address))
            throw new Error('Given address "'+ address +'" is not a valid Ethereum address.');

        address = address.toLowerCase().replace(/^0x/i,'');
        var addressHash = utils.sha3(address).replace(/^0x/i,'');
        var checksumAddress = '0x';

        for (var i = 0; i < address.length; i++ ) {
            // If ith character is 9 to f then make it uppercase
            if (parseInt(addressHash[i], 16) > 7) {
                checksumAddress += address[i].toUpperCase();
            } else {
                checksumAddress += address[i];
            }
        }
        return checksumAddress;
    };

    module.exports = {
        _fireError: _fireError,
        _jsonInterfaceMethodToString: _jsonInterfaceMethodToString,
        // extractDisplayName: extractDisplayName,
        // extractTypeName: extractTypeName,
        randomHex: randomHex,
        _: _,
        BN: utils.BN,
        isBN: utils.isBN,
        isBigNumber: utils.isBigNumber,
        isHex: utils.isHex,
        isHexStrict: utils.isHexStrict,
        sha3: utils.sha3,
        keccak256: utils.sha3,
        soliditySha3: soliditySha3,
        isAddress: utils.isAddress,
        checkAddressChecksum: utils.checkAddressChecksum,
        toChecksumAddress: toChecksumAddress,
        toHex: utils.toHex,
        toBN: utils.toBN,

        bytesToHex: utils.bytesToHex,
        hexToBytes: utils.hexToBytes,

        hexToNumberString: utils.hexToNumberString,

        hexToNumber: utils.hexToNumber,
        toDecimal: utils.hexToNumber, // alias

        numberToHex: utils.numberToHex,
        fromDecimal: utils.numberToHex, // alias

        hexToUtf8: utils.hexToUtf8,
        hexToString: utils.hexToUtf8,
        toUtf8: utils.hexToUtf8,

        utf8ToHex: utils.utf8ToHex,
        stringToHex: utils.utf8ToHex,
        fromUtf8: utils.utf8ToHex,

        hexToAscii: hexToAscii,
        toAscii: hexToAscii,
        asciiToHex: asciiToHex,
        fromAscii: asciiToHex,

        unitMap: ethjsUnit.unitMap,
        toWei: toWei,
        fromWei: fromWei,

        padLeft: utils.leftPad,
        leftPad: utils.leftPad,
        padRight: utils.rightPad,
        rightPad: utils.rightPad,
        toTwosComplement: utils.toTwosComplement
    };