# all files / packages/web3-core-helpers/src/ formatters.js

96.25% Statements 154/160
82.5% Branches 99/120
100% Functions 25/25
96.25% Lines 154/160

    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
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408

    3×
    3×
    3×

    3×

    3×
    93×

    3×
    82×

    3×
    90×
    49×

    41×
    2×

    39×

    3×
    82×

    82×
    14×

    68×

    3×

    30×

    30×
    16×

    30×
    29×

    30×
    150×

    18×

    30×

    3×

    60×
    56×

    56×

    56×

    54×
    43×

    54×
    15×

    54×
    216×

    95×

    54×

    3×
    8×

    3×
    12×
    11×
    12×
    11×
    12×
    12×
    12×
    12×

    12×
    11×

    12×
    12×

    12×

    3×
    48×

    48×
    48×
    48×
    48×
    48×
    48×

    48×
    4×

    48×
    19×

    48×

    3×

    165×
    165×
    165×
    165×
    165×
    164×

    165×
    15×
    165×
    15×

    165×
    12×
    20×
    4×

    165×
    14×

    165×

    3×
    12×

    26×
    9×

    17×

    17×
    17×

    12×
    12×
    26×

    12×

    12×
    11×

    12×

    3×

    37×

    30×
    30×
    7×
    3×

    37×
    34×
    37×
    34×
    37×
    34×

    37×
    32×

    37×

    3×

    1×
    1×
    1×
    1×
    1×
    1×

    1×

    1×

    2×

    1×

    3×

    1×
    1×
    1×
    1×

    1×

    1×
    2×

    1×

    3×
    407×
    407×
    17×
    390×
    373×

    17×

    3×

    2×
    2×
    2×
    2×
    2×
    2×

    2×

    3×

     /*
        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 formatters.js
     * @author Fabian Vogelsteller <fabian@ethereum.org>
     * @author Marek Kotewicz <marek@ethcore.io>
     * @date 2017
     */

    "use strict";

    var _ = require('underscore');
    var utils = require('web3-utils');
    var Iban = require('web3-eth-iban');

    var config = require('./config');

    /**
     * Should the format output to a big number
     *
     * @method outputBigNumberFormatter
     * @param {String|Number|BigNumber} number
     * @returns {BigNumber} object
     */
    var outputBigNumberFormatter = function (number) {
        return utils.toBN(number).toString(10);
    };

    var isPredefinedBlockNumber = function (blockNumber) {
        return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
    };

    var inputDefaultBlockNumberFormatter = function (blockNumber) {
        if (blockNumber === undefined || blockNumber === null) {
            return config.defaultBlock;
        }
        if (blockNumber === 'genesis' || blockNumber === 'earliest') {
            return '0x0';
        }
        return inputBlockNumberFormatter(blockNumber);
    };

    var inputBlockNumberFormatter = function (blockNumber) {
        Iif (blockNumber === undefined) {
            return undefined;
        } else if (isPredefinedBlockNumber(blockNumber)) {
            return blockNumber;
        }
        return utils.numberToHex(blockNumber);
    };

    /**
     * Formats the input of a transaction and converts all values to HEX
     *
     * @method inputCallFormatter
     * @param {Object} transaction options
     * @returns object
    */
    var inputCallFormatter = function (options){

        var from = options.from || config.defaultAccount;

        if (from) {
            options.from = inputAddressFormatter(from);
        }

        if (options.to) { // it might be contract creation
            options.to = inputAddressFormatter(options.to);
        }

        ['gasPrice', 'gas', 'gasLimit', 'value', 'nonce'].filter(function (key) {
            return options[key] !== undefined;
        }).forEach(function(key){
            options[key] = utils.numberToHex(options[key]);
        });

        return options;
    };

    /**
     * Formats the input of a transaction and converts all values to HEX
     *
     * @method inputTransactionFormatter
     * @param {Object} options
     * @returns object
    */
    var inputTransactionFormatter = function (options) {

        // check from, only if not number, or object
        if (!_.isNumber(options.from) && !_.isObject(options.from)) {
            options.from = options.from || config.defaultAccount;

            Iif (!options.from && !_.isNumber(options.from)) {
                throw new Error('The send transactions "from" field must be defined!');
            }

            options.from = inputAddressFormatter(options.from);
        }

        if (options.to) { // it might be contract creation
            options.to = inputAddressFormatter(options.to);
        }

        // allow both
        if (options.gas || options.gasLimit) {
            options.gas = options.gas || options.gasLimit;
        }

        ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
            return options[key] !== undefined;
        }).forEach(function(key){
            options[key] = utils.numberToHex(options[key]);
        });

        return options;
    };

    /**
     * Hex encodes the data passed to eth_sign and personal_sign
     *
     * @method inputSignFormatter
     * @param {String} data
     * @returns {String}
     */
    var inputSignFormatter = function (data) {
        return (utils.isHex(data)) ? data : utils.utf8ToHex(data);
    };

    /**
     * Formats the output of a transaction to its proper values
     *
     * @method outputTransactionFormatter
     * @param {Object} tx
     * @returns {Object}
    */
    var outputTransactionFormatter = function (tx){
        if(tx.blockNumber !== null)
            tx.blockNumber = utils.hexToNumber(tx.blockNumber);
        if(tx.transactionIndex !== null)
            tx.transactionIndex = utils.hexToNumber(tx.transactionIndex);
        tx.nonce = utils.hexToNumber(tx.nonce);
        tx.gas = utils.hexToNumber(tx.gas);
        tx.gasPrice = outputBigNumberFormatter(tx.gasPrice);
        tx.value = outputBigNumberFormatter(tx.value);

        if(tx.to) {
            tx.to = utils.toChecksumAddress(tx.to);
        }
        Eif(tx.from) {
            tx.from = utils.toChecksumAddress(tx.from);
        }

        return tx;
    };

    /**
     * Formats the output of a transaction receipt to its proper values
     *
     * @method outputTransactionReceiptFormatter
     * @param {Object} receipt
     * @returns {Object}
    */
    var outputTransactionReceiptFormatter = function (receipt){
        Iif(typeof receipt !== 'object') {
            throw new Error('Received receipt is invalid: '+ receipt);
        }

        Eif(receipt.blockNumber !== null)
            receipt.blockNumber = utils.hexToNumber(receipt.blockNumber);
        Eif(receipt.transactionIndex !== null)
            receipt.transactionIndex = utils.hexToNumber(receipt.transactionIndex);
        receipt.cumulativeGasUsed = utils.hexToNumber(receipt.cumulativeGasUsed);
        receipt.gasUsed = utils.hexToNumber(receipt.gasUsed);

        if(_.isArray(receipt.logs)) {
            receipt.logs = receipt.logs.map(outputLogFormatter);
        }

        if(receipt.contractAddress) {
            receipt.contractAddress = utils.toChecksumAddress(receipt.contractAddress);
        }

        return receipt;
    };

    /**
     * Formats the output of a block to its proper values
     *
     * @method outputBlockFormatter
     * @param {Object} block
     * @returns {Object}
    */
    var outputBlockFormatter = function(block) {

        // transform to number
        block.gasLimit = utils.hexToNumber(block.gasLimit);
        block.gasUsed = utils.hexToNumber(block.gasUsed);
        block.size = utils.hexToNumber(block.size);
        block.timestamp = utils.hexToNumber(block.timestamp);
        if (block.number !== null)
            block.number = utils.hexToNumber(block.number);

        if(block.difficulty)
            block.difficulty = outputBigNumberFormatter(block.difficulty);
        if(block.totalDifficulty)
            block.totalDifficulty = outputBigNumberFormatter(block.totalDifficulty);

        if (_.isArray(block.transactions)) {
            block.transactions.forEach(function(item){
                if(!_.isString(item))
                    return outputTransactionFormatter(item);
            });
        }

        if (block.miner)
            block.miner = utils.toChecksumAddress(block.miner);

        return block;
    };

    /**
     * Formats the input of a log
     *
     * @method inputLogFormatter
     * @param {Object} log object
     * @returns {Object} log
    */
    var inputLogFormatter = function(options) {
        var toTopic = function(value){

            if(value === null || typeof value === 'undefined')
                return null;

            value = String(value);

            Eif(value.indexOf('0x') === 0)
                return value;
            else
                return utils.fromUtf8(value);
        };

        // make sure topics, get converted to hex
        options.topics = options.topics || [];
        options.topics = options.topics.map(function(topic){
            return (_.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
        });

        toTopic = null;

        if(options.address)
            options.address = inputAddressFormatter(options.address);

        return options;
    };

    /**
     * Formats the output of a log
     *
     * @method outputLogFormatter
     * @param {Object} log object
     * @returns {Object} log
    */
    var outputLogFormatter = function(log) {

        // generate a custom log id
        if(typeof log.blockHash === 'string' &&
           typeof log.transactionHash === 'string' &&
           typeof log.logIndex === 'string') {
            var shaId = utils.sha3(log.blockHash.replace('0x','') + log.transactionHash.replace('0x','') + log.logIndex.replace('0x',''));
            log.id = 'log_'+ shaId.replace('0x','').substr(0,8);
        } else if(!log.id) {
            log.id = null;
        }

        if (log.blockNumber !== null)
            log.blockNumber = utils.hexToNumber(log.blockNumber);
        if (log.transactionIndex !== null)
            log.transactionIndex = utils.hexToNumber(log.transactionIndex);
        if (log.logIndex !== null)
            log.logIndex = utils.hexToNumber(log.logIndex);

        if (log.address)
            log.address = utils.toChecksumAddress(log.address);

        return log;
    };

    /**
     * Formats the input of a whisper post and converts all values to HEX
     *
     * @method inputPostFormatter
     * @param {Object} transaction object
     * @returns {Object}
    */
    var inputPostFormatter = function(post) {

        // post.payload = utils.toHex(post.payload);

        Eif (post.ttl)
            post.ttl = utils.numberToHex(post.ttl);
        Eif (post.workToProve)
            post.workToProve = utils.numberToHex(post.workToProve);
        Eif (post.priority)
            post.priority = utils.numberToHex(post.priority);

        // fallback
        Iif (!_.isArray(post.topics)) {
            post.topics = post.topics ? [post.topics] : [];
        }

        // format the following options
        post.topics = post.topics.map(function(topic){
            // convert only if not hex
            return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic);
        });

        return post;
    };

    /**
     * Formats the output of a received post message
     *
     * @method outputPostFormatter
     * @param {Object}
     * @returns {Object}
     */
    var outputPostFormatter = function(post){

        post.expiry = utils.hexToNumber(post.expiry);
        post.sent = utils.hexToNumber(post.sent);
        post.ttl = utils.hexToNumber(post.ttl);
        post.workProved = utils.hexToNumber(post.workProved);
        // post.payloadRaw = post.payload;
        // post.payload = utils.hexToAscii(post.payload);

        // if (utils.isJson(post.payload)) {
        //     post.payload = JSON.parse(post.payload);
        // }

        // format the following options
        Iif (!post.topics) {
            post.topics = [];
        }
        post.topics = post.topics.map(function(topic){
            return utils.toUtf8(topic);
        });

        return post;
    };

    var inputAddressFormatter = function (address) {
        var iban = new Iban(address);
        if (iban.isValid() && iban.isDirect()) {
            return iban.toAddress().toLowerCase();
        } else if (utils.isAddress(address)) {
            return '0x' + address.toLowerCase().replace('0x','');
        }
        throw new Error('Provided address "'+ address +'" is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can\'t be converted.');
    };

    var outputSyncingFormatter = function(result) {

        result.startingBlock = utils.hexToNumber(result.startingBlock);
        result.currentBlock = utils.hexToNumber(result.currentBlock);
        result.highestBlock = utils.hexToNumber(result.highestBlock);
        Eif (result.knownStates) {
            result.knownStates = utils.hexToNumber(result.knownStates);
            result.pulledStates = utils.hexToNumber(result.pulledStates);
        }

        return result;
    };

    module.exports = {
        inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter,
        inputBlockNumberFormatter: inputBlockNumberFormatter,
        inputCallFormatter: inputCallFormatter,
        inputTransactionFormatter: inputTransactionFormatter,
        inputAddressFormatter: inputAddressFormatter,
        inputPostFormatter: inputPostFormatter,
        inputLogFormatter: inputLogFormatter,
        inputSignFormatter: inputSignFormatter,
        outputBigNumberFormatter: outputBigNumberFormatter,
        outputTransactionFormatter: outputTransactionFormatter,
        outputTransactionReceiptFormatter: outputTransactionReceiptFormatter,
        outputBlockFormatter: outputBlockFormatter,
        outputLogFormatter: outputLogFormatter,
        outputPostFormatter: outputPostFormatter,
        outputSyncingFormatter: outputSyncingFormatter
    };