all files / dist/ ethereumContracts.js

93.69% Statements 193/206
80.61% Branches 79/98
96.23% Functions 51/53
94.09% Lines 191/203
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                       70×         16×         16× 16× 16× 16× 16×                                                                                                                                                     11×   11×         11×   11× 10×   10×   10× 10×         18×       16×                           17×   17× 17× 17×       14×   14×             45×   45×   45×   45×   45×             36× 47×       47× 47×               23×   23×   23×   23×   23×       23× 23× 23×           23×         68×   68× 234×     68×         23×   23×     23×     23×         47×   47×     47× 15×   15× 15×         15×     15×   11× 11×     15×   15×     12×       32× 11× 11×     21×     14×                 39×         372×       12×                                       32× 32× 51×                           31×   31×   31×   23×                                                               52×         147×                                                           11×   11×   11× 11×           11×   10× 10×               22×              
(function (global, factory) {
  Iif (typeof define === "function" && define.amd) {
    define(['module'], factory);
  } else Eif (typeof exports !== "undefined") {
    factory(module);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod);
    global.EthereumContracts = mod.exports;
  }
})(this, function (module) {
  "use strict";
 
  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
  };
 
  function _classCallCheck(instance, Constructor) {
    Iif (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
 
  var _createClass = function () {
    function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }
 
    return function (Constructor, protoProps, staticProps) {
      Eif (protoProps) defineProperties(Constructor.prototype, protoProps);
      Iif (staticProps) defineProperties(Constructor, staticProps);
      return Constructor;
    };
  }();
 
  var DUMMY_LOGGER = {
    debug: function debug() {},
    info: function info() {},
    warn: function warn() {},
    error: function error() {}
  };
 
  /**
   * Factory for creating new contracts.
   */
 
  var ContractFactory = function () {
    /**
     * Constuct a new instance.
     * 
     * @param {Object} config Configuration.
     * @param {Object} config.web3 A `Web3` instance.
     * @param {Object} config.account Account to send transactions from.
     * @param {String} config.account.address Address of account.
     * @param {String} config.account.password Password for account.
     * @param {Number} config.gas Gas amount to use for calls.
     */
    function ContractFactory(config) {
      _classCallCheck(this, ContractFactory);
 
      this._config = config;
      this._web3 = config.web3;
      this._account = config.account;
      this._gas = config.gas;
    }
 
    /**
     * Make a wrapper for the given contract.
     *
     * @param {Object} config Configuration.
     * @param {Object} config.contract Contract data, usually the output of `solc` compiler.
     * @param {String} config.contract.interface Contract ABI interface JSON.
     * @param {String} config.contract.bytecode Contract bytecode string.
     */
 
 
    _createClass(ContractFactory, [{
      key: 'make',
      value: function make(config) {
        return new Contract(Object.assign({}, config, {
          gas: this._gas,
          web3: this._web3,
          account: this._account
        }));
      }
    }]);
 
    return ContractFactory;
  }();
 
  var Contract = function () {
    /**
     * Constuct a new instance.
     * 
     * @param {Object} config Configuration.
     * @param {Object} config.web3 A `Web3` instance.
     * @param {Object} contract.contract Contract data, usually the output of `solc` compiler.
     * @param {String} config.contract.interface Contract ABI interface JSON.
     * @param {String} config.contract.bytecode Contract bytecode string.
     * @param {Object} config.account Account to send transactions from.
     * @param {String} config.account.address Address of account.
     * @param {String} config.account.password Password for account.
     * @param {Number} config.gas Gas amount to use for calls.
     */
    function Contract(config) {
      _classCallCheck(this, Contract);
 
      this._config = config;
      this._web3 = config.web3;
      this._bytecode = config.contract.bytecode;
      this._interface = JSON.parse(config.contract.interface);
      this._contract = this._web3.eth.contract(this._interface);
      this._account = config.account;
      this._gas = config.gas;
      this._logger = DUMMY_LOGGER;
    }
 
    /**
     * Get the logger.
     * @return {Object}
     */
 
 
    _createClass(Contract, [{
      key: 'deploy',
      value: function deploy(args, options) {
        var _this = this;
 
        options = Object.assign({
          account: this._account,
          gas: this._gas
        }, options);
 
        this.logger.info('Deploy contract from account ' + options.account.address + '...');
 
        return this._unlockAccount(options.account).then(function () {
          var sortedArgs = _this._sanitizeMethodArgs('constructor', args);
 
          _this.logger.debug('Deploy contract ...');
 
          return new Promise(function (resolve, reject) {
            _this._contract.new.apply(_this._contract, sortedArgs.concat([{
              data: _this._bytecode,
              gas: options.gas,
              from: options.account.address
            }, function (err, newContract) {
              if (err) {
                _this.logger.error('Contract creation error', err);
 
                return reject(err);
              }
 
              if (!newContract.address) {
                _this.logger.debug('New contract transaction: ' + newContract.transactionHash);
              } else {
                _this.logger.info('New contract address: ' + newContract.address);
 
                resolve(new ContractInstance({
                  contract: _this,
                  address: newContract.address
                }));
              }
            }]));
          });
        });
      }
    }, {
      key: '_unlockAccount',
      value: function _unlockAccount(account) {
        var _this2 = this;
 
        return new Promise(function (resolve, reject) {
          _this2._web3.personal.unlockAccount(account.address, account.password, 2000, function (err) {
            if (err) {
              _this2.logger.info('Error unlocking account ' + account.address + ': ' + err.message);
 
              return reject(err);
            }
 
            _this2.logger.info('Unlocked account ' + account.address + ' for 2 seconds.');
 
            resolve();
          });
        });
      }
    }, {
      key: '_sanitizeMethodArgs',
      value: function _sanitizeMethodArgs(method, args) {
        var _this3 = this;
 
        args = args || {};
 
        this.logger.debug('Sanitize ' + Object.keys(args).length + ' arguments for method: ' + method + ' ...');
 
        var methodAbi = this._getMethodDescriptor(method);
 
        if (!methodAbi) {
          // if not constructor found then it's a built-in constructor
          if ('constructor' === method) {
            this.logger.debug('Built-in constructor, so no default arguments.');
 
            return [];
          } else {
            throw new Error('Method not found: ' + method);
          }
        }
 
        return methodAbi.inputs.map(function (input) {
          Iif (!args.hasOwnProperty(input.name)) {
            throw new Error('Missing argument ' + input.name + ' for method ' + method);
          }
 
          try {
            return _this3._convertInputArg(args[input.name], input.type);
          } catch (err) {
            throw new Error('Error converting value for argument ' + input.name + ' of method ' + method + ': ' + err.message);
          }
        });
      }
    }, {
      key: '_sanitizeMethodReturnValues',
      value: function _sanitizeMethodReturnValues(method, value) {
        var _this4 = this;
 
        var values = Array.isArray(value) ? value : [value];
 
        this.logger.debug('Sanitize ' + values.length + ' return values from method: ' + method + ' ...');
 
        var methodAbi = this._getMethodDescriptor(method);
 
        Iif (!methodAbi) {
          throw new Error('Method not found: ' + method);
        }
 
        var ret = methodAbi.outputs.map(function (output) {
          try {
            return _this4._convertReturnValue(values.shift(), output.type);
          } catch (err) {
            throw new Error('Error converting return value to type ' + output.name + ' for method ' + method + ': ' + err.message);
          }
        });
 
        return Array.isArray(value) ? ret : ret[0];
      }
    }, {
      key: '_getMethodDescriptor',
      value: function _getMethodDescriptor(method) {
        this.logger.debug('Get descriptor for method: ' + method + ' ...');
 
        var interfaceMethod = this._interface.find(function (item) {
          return item.name === method || item.type === method;
        });
 
        return interfaceMethod || null;
      }
    }, {
      key: '_convertReturnValue',
      value: function _convertReturnValue(value, targetType) {
        var originalType = typeof value === 'undefined' ? 'undefined' : _typeof(value);
 
        this.logger.debug('Convert return value of type ' + originalType + ' to type ' + targetType + ' ...');
 
        // numbers
        if (0 === targetType.indexOf('int') || 0 === targetType.indexOf('uint')) {
          value = parseInt(this._web3.fromWei(value, 'wei'), 10);
        }
 
        return value;
      }
    }, {
      key: '_convertInputArg',
      value: function _convertInputArg(value, targetType) {
        var originalType = typeof value === 'undefined' ? 'undefined' : _typeof(value);
 
        this.logger.debug('Convert input value of type ' + originalType + ' to type ' + targetType + ' ...');
 
        // numbers
        if (0 === targetType.indexOf('int') || 0 === targetType.indexOf('uint')) {
          var suffix = targetType.substr(targetType.indexOf('int') + 3);
 
          Eif (suffix.length) {
            suffix = parseInt(suffix, 10);
          } else {
            suffix = 256; // since int=int256 and uint=uint256
          }
 
          var maxValue = void 0,
              minValue = void 0;
 
          if (0 === targetType.indexOf('int')) {
            minValue = -(Math.pow(2, suffix - 1) - 1);
            maxValue = Math.pow(2, suffix - 1) - 1;
          } else {
            minValue = 0;
            maxValue = Math.pow(2, suffix) - 1;
          }
 
          value = Number(value);
 
          if (isNaN(value)) {
            throw new Error('Value is not a number');
          }
 
          if (value < minValue || value > maxValue) {
            throw new Error('Value out of bounds (min=' + minValue + ', max=' + maxValue + ')');
          }
        }
        // bool
        else if ('bool' === targetType) {
            value += '';
            value = '' === value || '0' === value || 'false' === value ? false : true;
          }
          // string
          else if ('string' === targetType) {
              value = '' + value;
            }
            // address
            else if ('address' === targetType) {
                if ('number' === originalType) {
                  value = ('0000000000000000000000000000000000000000' + value.toString(16)).slice(-40);
                  value = '0x' + value;
                } else {
                  value = value + '';
                }
 
                if (!this._web3.isAddress(value)) {
                  throw new Error('Value is not a valid address');
                }
              }
              // bytes
              else Eif (0 === targetType.indexOf('byte')) {
                  value = this._web3.toHex(value);
                }
 
        return value;
      }
    }, {
      key: 'logger',
      get: function get() {
        return this._logger;
      },
      set: function set(val) {
        this._logger = {};
 
        for (var key in DUMMY_LOGGER) {
          this._logger[key] = val && typeof val[key] === 'function' ? val[key].bind(val) : DUMMY_LOGGER[key];
        }
      }
    }]);
 
    return Contract;
  }();
 
  var ContractInstance = function () {
    /**
     * Construct a new instance.
     *
     * @param {Object} config Configuration.
     * @param {Contract} config.contract The contract instance.
     * @param {String} config.address Address on blockchain.
     */
    function ContractInstance(config) {
      _classCallCheck(this, ContractInstance);
 
      this._config = config;
      this._contract = config.contract;
      this._web3 = this._contract._web3;
      this._address = config.address;
      this._inst = this.contract._contract.at(this._address);
 
      /*
      Logger is same as parent contract one, except that address is prepended 
      to all log output.
       */
      this._logger = {};
      for (var logMethod in DUMMY_LOGGER) {
        this._logger[logMethod] = function (logMethod, self) {
          return function () {
            self.contract.logger[logMethod].apply(self.contract.logger, ['[' + self.address + ']: '].concat(Array.from(arguments)));
          };
        }(logMethod, this);
      }
    }
 
    /**
     * Get address of this instance.
     * @return {String}
     */
 
 
    _createClass(ContractInstance, [{
      key: 'localCall',
      value: function localCall(method, args) {
        var parentContract = this.contract;
 
        this._logger.info('Local call ' + method + ' ...');
 
        var sortedArgs = parentContract._sanitizeMethodArgs(method, args);
 
        return parentContract._sanitizeMethodReturnValues(method, this._inst[method].call.apply(this._inst[method], sortedArgs));
      }
    }, {
      key: 'sendCall',
      value: function sendCall(method, args, options) {
        var _this5 = this;
 
        var parentContract = this.contract;
 
        options = Object.assign({
          account: parentContract._account,
          gas: parentContract._gas
        }, options);
 
        this._logger.info('Call method ' + method + ' from account ' + options.account.address + '...');
 
        return parentContract._unlockAccount(options.account).then(function () {
          var sortedArgs = parentContract._sanitizeMethodArgs(method, args);
 
          _this5._logger.debug('Execute method ' + method + ' ...');
 
          return new Promise(function (resolve, reject) {
            _this5._inst[method].sendTransaction.apply(_this5._inst, sortedArgs.concat([{
              data: _this5._bytecode,
              gas: options.gas,
              from: options.account.address
            }, function (err, txHash) {
              if (err) {
                _this5._logger.error('Method call error', err);
 
                return reject(err);
              }
 
              var tx = new Transaction({
                parent: _this5,
                hash: txHash
              });
 
              tx.getReceipt().then(resolve).catch(reject);
            }]));
          });
        });
      }
    }, {
      key: 'address',
      get: function get() {
        return this._address;
      }
    }, {
      key: 'contract',
      get: function get() {
        return this._contract;
      }
    }]);
 
    return ContractInstance;
  }();
 
  var Transaction = function () {
    /**
     * Constructor a transaction object.
     *
     * @param {Object} config Configuration options.
     * @param {ContractInstance} config.parent The parent `ContratInstance`.
     * @param {String} config.hash Transaction hash.
     */
    function Transaction(config) {
      _classCallCheck(this, Transaction);
 
      this._web3 = config.parent._web3;
      this._logger = config.parent._logger;
      this._hash = config.hash;
    }
 
    /**
     * Get transaction hash.
     * @return {String}
     */
 
 
    _createClass(Transaction, [{
      key: 'getReceipt',
      value: function getReceipt() {
        var _this6 = this;
 
        return new Promise(function (resolve, reject) {
          _this6._fetchReceiptLoop(resolve, reject);
        });
      }
    }, {
      key: '_fetchReceiptLoop',
      value: function _fetchReceiptLoop(onSuccess, onError) {
        var _this7 = this;
 
        this._logger.debug('Fetch receipt for tx ' + this.hash + ' ...');
 
        this._web3.eth.getTransactionReceipt(this.hash, function (err, receipt) {
          Iif (err) {
            _this7._logger.error('Transaction receipt error', err);
 
            return onError(err);
          }
 
          if (receipt) {
            onSuccess(receipt);
          } else {
            _this7._fetchReceiptLoopTimer = setTimeout(function () {
              _this7._fetchReceiptLoop(onSuccess, onError);
            }, 1000);
          }
        });
      }
    }, {
      key: 'hash',
      get: function get() {
        return this._hash;
      }
    }]);
 
    return Transaction;
  }();
 
  module.exports = { ContractFactory: ContractFactory, Contract: Contract, ContractInstance: ContractInstance };
});