All files / susyweb-core-method/src index.js

92.31% Statements 216/234
86.81% Branches 158/182
93.94% Functions 31/33
92.7% Lines 216/233

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610                                                  1x 1x 1x 1x 1x 1x   1x 1x 1x   1x   32043x 2x     32041x 32041x 32041x 32041x 32041x 32041x 32041x   32041x     32041x   32041x 32041x     1x 31894x     31894x 13312x         1x 84x 84x   84x   84x     1x 31926x 31926x 31926x 31926x 1206x 1206x   30720x                     1x 647x                   1x 646x 139x                     1x 641x 2x                     1x 645x   645x 103x     542x   729x                     1x 636x   636x 18x 28x     618x                     1x 643x 643x 643x 637x   637x           637x 8x     637x       1x 67x 67x 67x 67x 67x 67x 67x 67x             67x                                                     67x 67x 201x 201x         67x 195x   195x 14x   12x         195x                 195x 128x       67x 19x       67x         31x 29x     29x 29x   29x 1x 1x       65x         65x   9x   2x 2x 2x     2x 2x     7x   7x         7x 5x     5x 3x   2x       5x 5x       2x     7x 7x   7x       63x         65x   30x     30x 30x     30x 27x                                 30x 27x   30x           130x     130x               130x 2x 2x 2x                           67x   65x 55x   10x           67x   67x 4x   2x   4x   63x 63x                   1x 11x     11x 2x     9x 2x       7x     11x     1x 32028x 32028x     32028x 635x 635x       629x 625x 625x   3x     625x 1x     625x 618x 122x     7x 3x     7x       618x   551x 551x           67x   67x           629x   7x         7x       629x   629x       11x 7x 7x       7x 7x       4x 4x 4x     4x 4x   4x 2x     4x 4x             618x       629x   7x           7x   7x 7x   7x       622x       629x       32028x   32028x 32028x                 1x 8x 8x 8x     1x  
/*
    This file is part of susyweb.js.
 
    susyweb.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.
 
    susyweb.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MSRCHANTABILITY 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 susyweb.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @file index.js
 * @author Fabian Vogelsteller <fabian@ethereum.org>
 * @author Marek Kotewicz <marek@superstring.io>
 * @date 2017
 */
 
"use strict";
 
var _ = require('underscore');
var errors = require('susyweb-core-helpers').errors;
var formatters = require('susyweb-core-helpers').formatters;
var utils = require('susyweb-utils');
var promiEvent = require('susyweb-core-promievent');
var Subscriptions = require('susyweb-core-subscriptions').subscriptions;
 
var TIMEOUTBLOCK = 50;
var POLLINGTIMEOUT = 15 * TIMEOUTBLOCK; // ~average block time (seconds) * TIMEOUTBLOCK
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 sof.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 sof.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 _sophonCalls = [
        new Method({
            name: 'getTransactionReceipt',
            call: 'sof_getTransactionReceipt',
            params: 1,
            inputFormatter: [null],
            outputFormatter: formatters.outputTransactionReceiptFormatter
        }),
        new Method({
            name: 'getCode',
            call: 'sof_getCode',
            params: 2,
            inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
        }),
        new Subscriptions({
            name: 'subscribe',
            type: 'sof',
            subscriptions: {
                'newBlockHeaders': {
                    subscriptionName: 'newHeads', // replace subscription with this name
                    params: 0,
                    outputFormatter: formatters.outputBlockFormatter
                }
            }
        })
    ];
    // attach methods to this._sophonCall
    var _sophonCall = {};
    _.each(_sophonCalls, function (mthd) {
        mthd.attachToObject(_sophonCall);
        mthd.requestManager = method.requestManager; // assign rather than call setRequestManager()
    });
 
 
    // fire "receipt" and confirmation events and resolve after
    var checkConfirmation = function (existingReceipt, isPolling, err, blockHeader, sub) {
        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) : _sophonCall.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) {
 
                    // If there was an immediately retrieved receipt, it's already
                    // been confirmed by the direct call to checkConfirmation needed
                    // for susy instant-seal
                    if (existingReceipt === undefined || confirmationCount !== 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;
                        }
 
                        utils._fireError(new Error('The transaction receipt didn\'t contain a contract address.'), defer.eventEmitter, defer.reject);
                        return;
                    }
 
                    _sophonCall.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) &&
                        (receipt.status === true || receipt.status === '0x1' || typeof receipt.status === 'undefined')) {
                        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);
                        }
                        if (receipt.status === false || receipt.status === '0x0') {
                            utils._fireError(new Error("Transaction has been reverted by the SVM:\n" + receipt),
                                defer.eventEmitter, defer.reject);
                        } else {
                            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++;
 
                // check to see if we are http polling
                Iif(!!isPolling) {
                    // polling timeout is different than TIMEOUTBLOCK blocks since we are triggering every second
                    if (timeoutCount - 1 >= POLLINGTIMEOUT) {
                        sub.unsubscribe();
                        promiseResolved = true;
                        utils._fireError(new Error('Transaction was not mined within' + POLLINGTIMEOUT + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
                    }
                } else {
                    if (timeoutCount - 1 >= TIMEOUTBLOCK) {
                        sub.unsubscribe();
                        promiseResolved = true;
                        utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject);
                    }
                }
            });
 
 
        } else {
            sub.unsubscribe();
            promiseResolved = true;
            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(existingReceipt) {
        // if provider allows PUB/SUB
        if (_.isFunction(this.requestManager.provider.on)) {
            _sophonCall.subscribe('newBlockHeaders', checkConfirmation.bind(null, existingReceipt, false));
        } else {
            intervalId = setInterval(checkConfirmation.bind(null, existingReceipt, true), 1000);
        }
    }.bind(this);
 
 
    // first check if we already have a confirmed transaction
    _sophonCall.getTransactionReceipt(result)
    .then(function(receipt) {
        if (receipt && receipt.blockHash) {
            if (defer.eventEmitter.listeners('confirmation').length > 0) {
                // We must keep on watching for new Blocks, if a confirmation listener is present
                startWatching(receipt);
            }
            checkConfirmation(receipt, false);
 
        } 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 === 'sof_sendTransaction' || method.call === 'sof_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){
 
            var signedPayload = _.extend({}, payload, {
                method: 'sof_sendRawTransaction',
                params: [sign.rawTransaction]
            });
 
            method.requestManager.send(signedPayload, sendTxCallback);
        };
 
 
        var sendRequest = function(payload, method) {
 
            if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) {
                var wallet;
 
                // SOF_SENDTRANSACTION
                if (payload.method === 'sof_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) {
                        return method.accounts.signTransaction(_.omit(tx, 'from'), wallet.privateKey).then(sendSignedTx);
                    }
 
                    // SOF_SIGN
                } else Eif (payload.method === 'sof_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: 'sof_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;