# All files / web3-core-method/src index.js

93.45% Statements 214/229
87.13% Branches 149/171
91.18% Functions 31/34
94.27% Lines 214/227

    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
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590

    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    26349x
    2x

    26347x
    26347x
    26347x
    26347x
    26347x
    26347x
    26347x

    26347x

    26347x

    26347x
    26347x

    1x
    26236x

    26236x
    10893x

    1x
    41x
    41x

    41x

    41x

    1x
    26276x
    26276x
    26276x
    26276x
    1017x
    1017x

    25259x

    1x
    500x

    1x
    499x
    114x

    1x
    494x
    2x

    1x
    498x

    498x
    60x

    438x

    580x

    1x
    489x

    489x
    17x
    26x

    472x

    1x
    496x
    496x
    496x
    490x

    490x

    490x
    8x

    490x

    1x
    49x
    49x
    49x
    49x
    49x
    49x
    49x
    49x

    49x

    49x
    49x
    147x
    147x

    49x
    173x

    173x
    10x

    10x

    173x

    173x
    119x

    54x
    6x

    54x

    25x

    25x
    25x

    25x
    1x
    1x

    54x

    54x

    7x

    2x
    2x
    2x

    2x

    5x

    5x

    5x
    3x

    3x
    1x

    2x

    3x
    3x

    2x

    5x
    5x

    5x

    52x

    52x

    23x

    23x
    23x

    23x
    22x

    23x
    22x

    23x

    121x

    121x
    2x
    2x
    2x

    49x

    48x
    39x

    9x

    49x

    49x
    1x

    1x
    48x
    48x

    1x
    10x

    10x
    2x

    8x
    2x

    6x

    10x

    1x
    26334x
    26334x

    26334x
    490x
    490x

    484x
    480x
    480x

    2x

    480x
    1x

    480x
    474x
    100x

    6x
    3x

    6x

    474x

    425x
    425x

    49x

    49x

    484x

    6x
    6x

    6x

    484x

    484x

    10x
    6x
    6x

    6x
    6x

    6x

    6x

    4x
    4x
    4x

    4x
    4x

    4x
    2x

    4x
    4x

    474x

    484x

    6x

    6x

    6x
    6x

    6x

    478x

    484x

    26334x

    26334x
    26334x

    1x
    6x
    6x
    6x

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

    "use strict";

    var _ = require('underscore');
    var errors = require('web3-core-helpers').errors;
    var formatters = require('web3-core-helpers').formatters;
    var utils = require('web3-utils');
    var promiEvent = require('web3-core-promievent');
    var Subscriptions = require('web3-core-subscriptions').subscriptions;

    var TIMEOUTBLOCK = 50;
    var CONFIRMATIONBLOCKS = 24;

    var Method = function Method(options) {

        if(!options.call || !options.name) {
            throw new Error('When creating a method you need to provide at least the "name" and "call" property.');
        }

        this.name = options.name;
        this.call = options.call;
        this.params = options.params || 0;
        this.inputFormatter = options.inputFormatter;
        this.outputFormatter = options.outputFormatter;
        this.transformPayload = options.transformPayload;
        this.extraFormatters = options.extraFormatters;

        this.requestManager = options.requestManager;

        // reference to eth.accounts
        this.accounts = options.accounts;

        this.defaultBlock = options.defaultBlock || 'latest';
        this.defaultAccount = options.defaultAccount || null;
    };

    Method.prototype.setRequestManager = function (requestManager, accounts) {
        this.requestManager = requestManager;

        // reference to eth.accounts
        if (accounts) {
            this.accounts = accounts;
        }

    };

    Method.prototype.createFunction = function (requestManager, accounts) {
        var func = this.buildCall();
        func.call = this.call;

        this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts);

        return func;
    };

    Method.prototype.attachToObject = function (obj) {
        var func = this.buildCall();
        func.call = this.call;
        var name = this.name.split('.');
        if (name.length > 1) {
            obj[name[0]] = obj[name[0]] || {};
            obj[name[0]][name[1]] = func;
        } else {
            obj[name[0]] = func;
        }
    };

    /**
     * Should be used to determine name of the jsonrpc method based on arguments
     *
     * @method getCall
     * @param {Array} arguments
     * @return {String} name of jsonrpc method
     */
    Method.prototype.getCall = function (args) {
        return _.isFunction(this.call) ? this.call(args) : this.call;
    };

    /**
     * Should be used to extract callback from array of arguments. Modifies input param
     *
     * @method extractCallback
     * @param {Array} arguments
     * @return {Function|Null} callback, if exists
     */
    Method.prototype.extractCallback = function (args) {
        if (_.isFunction(args[args.length - 1])) {
            return args.pop(); // modify the args array!
        }
    };

    /**
     * Should be called to check if the number of arguments is correct
     *
     * @method validateArgs
     * @param {Array} arguments
     * @throws {Error} if it is not
     */
    Method.prototype.validateArgs = function (args) {
        if (args.length !== this.params) {
            throw errors.InvalidNumberOfParams(args.length, this.params, this.name);
        }
    };

    /**
     * Should be called to format input args of method
     *
     * @method formatInput
     * @param {Array}
     * @return {Array}
     */
    Method.prototype.formatInput = function (args) {
        var _this = this;

        if (!this.inputFormatter) {
            return args;
        }

        return this.inputFormatter.map(function (formatter, index) {
            // bind this for defaultBlock, and defaultAccount
            return formatter ? formatter.call(_this, args[index]) : args[index];
        });
    };

    /**
     * Should be called to format output(result) of method
     *
     * @method formatOutput
     * @param {Object}
     * @return {Object}
     */
    Method.prototype.formatOutput = function (result) {
        var _this = this;

        if(_.isArray(result)) {
            return result.map(function(res){
                return _this.outputFormatter && res ? _this.outputFormatter(res) : res;
            });
        } else {
            return this.outputFormatter && result ? this.outputFormatter(result) : result;
        }
    };

    /**
     * Should create payload from given input args
     *
     * @method toPayload
     * @param {Array} args
     * @return {Object}
     */
    Method.prototype.toPayload = function (args) {
        var call = this.getCall(args);
        var callback = this.extractCallback(args);
        var params = this.formatInput(args);
        this.validateArgs(params);

        var payload = {
            method: call,
            params: params,
            callback: callback
        };

        if (this.transformPayload) {
            payload = this.transformPayload(payload);
        }

        return payload;
    };

    Method.prototype._confirmTransaction = function (defer, result, payload) {
        var method = this,
            promiseResolved = false,
            canUnsubscribe = true,
            timeoutCount = 0,
            confirmationCount = 0,
            intervalId = null,
            gasProvided = (_.isObject(payload.params[0]) && payload.params[0].gas) ? payload.params[0].gas : null,
            isContractDeployment = _.isObject(payload.params[0]) &&
                payload.params[0].data &&
                payload.params[0].from &&
                !payload.params[0].to;

        // add custom send Methods
        var _ethereumCalls = [
            new Method({
                name: 'getTransactionReceipt',
                call: 'eth_getTransactionReceipt',
                params: 1,
                inputFormatter: [null],
                outputFormatter: formatters.outputTransactionReceiptFormatter
            }),
            new Method({
                name: 'getCode',
                call: 'eth_getCode',
                params: 2,
                inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
            }),
            new Subscriptions({
                name: 'subscribe',
                type: 'eth',
                subscriptions: {
                    'newBlockHeaders': {
                        subscriptionName: 'newHeads', // replace subscription with this name
                        params: 0,
                        outputFormatter: formatters.outputBlockFormatter
                    }
                }
            })
        ];
        // attach methods to this._ethereumCall
        var _ethereumCall = {};
        _.each(_ethereumCalls, function (mthd) {
            mthd.attachToObject(_ethereumCall);
            mthd.requestManager = method.requestManager; // assign rather than call setRequestManager()
        });

        // fire "receipt" and confirmation events and resolve after
        var checkConfirmation = function (err, blockHeader, sub, existingReceipt) {
            Eif (!err) {
                // create fake unsubscribe
                if (!sub) {
                    sub = {
                        unsubscribe: function () {
                            clearInterval(intervalId);
                        }
                    };
                }
                // if we have a valid receipt we don't need to send a request
                return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result))
                // catch error from requesting receipt
                .catch(function (err) {
                    sub.unsubscribe();
                    promiseResolved = true;
                    utils._fireError({message: 'Failed to check for transaction receipt:', data: err}, defer.eventEmitter, defer.reject);
                })
                // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false
                .then(function(receipt) {

                    if (!receipt || !receipt.blockHash) {
                        throw new Error('Receipt missing or blockHash null');
                    }

                    // apply extra formatters
                    if (method.extraFormatters && method.extraFormatters.receiptFormatter) {
                        receipt = method.extraFormatters.receiptFormatter(receipt);
                    }

                    // check if confirmation listener exists
                    if (defer.eventEmitter.listeners('confirmation').length > 0) {

                        defer.eventEmitter.emit('confirmation', confirmationCount, receipt);

                        canUnsubscribe = false;
                        confirmationCount++;

                        if (confirmationCount === CONFIRMATIONBLOCKS + 1) { // add 1 so we account for conf 0
                            sub.unsubscribe();
                            defer.eventEmitter.removeAllListeners();
                        }
                    }

                    return receipt;
                })
                // CHECK for CONTRACT DEPLOYMENT
                .then(function(receipt) {

                    if (isContractDeployment && !promiseResolved) {

                        if (!receipt.contractAddress) {

                            Eif (canUnsubscribe) {
                                sub.unsubscribe();
                                promiseResolved = true;
                            }

                            return utils._fireError(new Error('The transaction receipt didn\'t contain a contract address.'), defer.eventEmitter, defer.reject);
                        }

                        _ethereumCall.getCode(receipt.contractAddress, function (e, code) {

                            Iif (!code) {
                                return;
                            }

                            if (code.length > 2) {
                                defer.eventEmitter.emit('receipt', receipt);

                                // if contract, return instance instead of receipt
                                if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) {
                                    defer.resolve(method.extraFormatters.contractDeployFormatter(receipt));
                                } else {
                                    defer.resolve(receipt);
                                }

                                // need to remove listeners, as they aren't removed automatically when succesfull
                                Eif (canUnsubscribe) {
                                    defer.eventEmitter.removeAllListeners();
                                }

                            } else {
                                utils._fireError(new Error('The contract code couldn\'t be stored, please check your gas limit.'), defer.eventEmitter, defer.reject);
                            }

                            Eif (canUnsubscribe) {
                                sub.unsubscribe();
                            }
                            promiseResolved = true;
                        });
                    }

                    return receipt;
                })
                // CHECK for normal tx check for receipt only
                .then(function(receipt) {

                    if (!isContractDeployment && !promiseResolved) {

                        Eif(!receipt.outOfGas &&
                           (!gasProvided || gasProvided !== receipt.gasUsed)) {
                            defer.eventEmitter.emit('receipt', receipt);
                            defer.resolve(receipt);

                            // need to remove listeners, as they aren't removed automatically when succesfull
                            if (canUnsubscribe) {
                                defer.eventEmitter.removeAllListeners();
                            }

                        } else {
                            if(receipt) {
                                receipt = JSON.stringify(receipt, null, 2);
                            }
                            utils._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+ receipt), defer.eventEmitter, defer.reject);
                        }

                        if (canUnsubscribe) {
                            sub.unsubscribe();
                        }
                        promiseResolved = true;
                    }

                })
                // time out the transaction if not mined after 50 blocks
                .catch(function () {
                    timeoutCount++;

                    if (timeoutCount - 1 >= TIMEOUTBLOCK) {
                        sub.unsubscribe();
                        promiseResolved = true;
                        return utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
                    }
                });

            } else {
                sub.unsubscribe();
                promiseResolved = true;
                return utils._fireError({message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.', data: err}, defer.eventEmitter, defer.reject);
            }
        };

      // start watching for confirmation depending on the support features of the provider
      var startWatching = function() {
          // if provider allows PUB/SUB
          if (_.isFunction(this.requestManager.provider.on)) {
              _ethereumCall.subscribe('newBlockHeaders', checkConfirmation);
          } else {
              intervalId = setInterval(checkConfirmation, 1000);
          }
      }.bind(this);

      // first check if we already have a confirmed transaction
      _ethereumCall.getTransactionReceipt(result)
      .then(function(receipt) {
          if (receipt && receipt.blockHash) {
              Iif (defer.eventEmitter.listeners('confirmation').length > 0) {
                  // if the promise has not been resolved we must keep on watching for new Blocks, if a confrimation listener is present
                  setTimeout(function(){
                      if (!promiseResolved) startWatching();
                  }, 1000);
              }

              return checkConfirmation(null, null, null, receipt);
          } else Eif (!promiseResolved) {
              startWatching();
          }
      })
      .catch(function(){
          if (!promiseResolved) startWatching();
      });

    };

    var getWallet = function(from, accounts) {
        var wallet = null;

        // is index given
        if (_.isNumber(from)) {
            wallet = accounts.wallet[from];

            // is account given
        } else if (_.isObject(from) && from.address && from.privateKey) {
            wallet = from;

            // search in wallet for address
        } else {
            wallet = accounts.wallet[from.toLowerCase()];
        }

        return wallet;
    };

    Method.prototype.buildCall = function() {
        var method = this,
            isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'); // || method.call === 'personal_sendTransaction'

        // actual send function
        var send = function () {
            var defer = promiEvent(!isSendTx),
                payload = method.toPayload(Array.prototype.slice.call(arguments));

            // CALLBACK function
            var sendTxCallback = function (err, result) {
                try {
                    result = method.formatOutput(result);
                } catch(e) {
                    err = e;
                }

                if (result instanceof Error) {
                    err = result;
                }

                if (!err) {
                    if (payload.callback) {
                        payload.callback(null, result);
                    }
                } else {
                    if(err.error) {
                        err = err.error;
                    }

                    return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback);
                }

                // return PROMISE
                if (!isSendTx) {

                    Eif (!err) {
                        defer.resolve(result);

                    }

                // return PROMIEVENT
                } else {
                    defer.eventEmitter.emit('transactionHash', result);

                    method._confirmTransaction(defer, result, payload);
                }

            };

            // SENDS the SIGNED SIGNATURE
            var sendSignedTx = function(sign){

                payload.method = 'eth_sendRawTransaction';
                payload.params = [sign.rawTransaction];

                method.requestManager.send(payload, sendTxCallback);
            };

            var sendRequest = function(payload, method) {

                if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) {
                    var wallet;

                    // ETH_SENDTRANSACTION
                    if (payload.method === 'eth_sendTransaction') {
                        var tx = payload.params[0];
                        wallet = getWallet((_.isObject(tx)) ? tx.from : null, method.accounts);

                        // If wallet was found, sign tx, and send using sendRawTransaction
                        Eif (wallet && wallet.privateKey) {
                            delete tx.from;

                            var signature = method.accounts.signTransaction(tx, wallet.privateKey);

                            return (_.isFunction(signature.then)) ? signature.then(sendSignedTx) : sendSignedTx(signature);
                        }

                    // ETH_SIGN
                    } else Eif (payload.method === 'eth_sign') {
                        var data = payload.params[1];
                        wallet = getWallet(payload.params[0], method.accounts);

                        // If wallet was found, sign tx, and send using sendRawTransaction
                        Eif (wallet && wallet.privateKey) {
                            var sign = method.accounts.sign(data, wallet.privateKey);

                            if (payload.callback) {
                                payload.callback(null, sign.signature);
                            }

                            defer.resolve(sign.signature);
                            return;
                        }

                    }
                }

                return method.requestManager.send(payload, sendTxCallback);
            };

            // Send the actual transaction
            if(isSendTx && _.isObject(payload.params[0]) && !payload.params[0].gasPrice) {

                var getGasPrice = (new Method({
                    name: 'getGasPrice',
                    call: 'eth_gasPrice',
                    params: 0
                })).createFunction(method.requestManager);

                getGasPrice(function (err, gasPrice) {

                    Eif (gasPrice) {
                        payload.params[0].gasPrice = gasPrice;
                    }
                    sendRequest(payload, method);
                });

            } else {
                sendRequest(payload, method);
            }

            return defer.eventEmitter;
        };

        // necessary to attach things to the method
        send.method = method;
        // necessary for batch requests
        send.request = this.request.bind(this);
        return send;
    };

    /**
     * Should be called to create the pure JSONRPC request which can be used in a batch request
     *
     * @method request
     * @return {Object} jsonrpc request
     */
    Method.prototype.request = function () {
        var payload = this.toPayload(Array.prototype.slice.call(arguments));
        payload.format = this.formatOutput.bind(this);
        return payload;
    };

    module.exports = Method;