Fix tslint issues

This commit is contained in:
Leonid Logvinov 2018-07-17 12:59:02 +02:00
parent edcdc9b1b9
commit bf8ac3b9e6
No known key found for this signature in database
GPG Key ID: 0DD294BFDE8C95D4
113 changed files with 354 additions and 323 deletions

View File

@ -61,7 +61,7 @@ export class ZeroEx {
* ERC721 proxy smart contract. * ERC721 proxy smart contract.
*/ */
public erc721Proxy: ERC721ProxyWrapper; public erc721Proxy: ERC721ProxyWrapper;
private _contractWrappers: ContractWrappers; private readonly _contractWrappers: ContractWrappers;
/** /**
* Generates a pseudo-random 256-bit salt. * Generates a pseudo-random 256-bit salt.
* The salt can be included in a 0x order, ensuring that the order generates a unique orderHash * The salt can be included in a 0x order, ensuring that the order generates a unique orderHash

View File

@ -7,7 +7,7 @@ before('migrate contracts', async function(): Promise<void> {
// HACK: Since the migrations take longer then our global mocha timeout limit // HACK: Since the migrations take longer then our global mocha timeout limit
// we manually increase it for this before hook. // we manually increase it for this before hook.
const mochaTestTimeoutMs = 20000; const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs); this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = { const txDefaults = {
gas: devConstants.GAS_LIMIT, gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS, from: devConstants.TESTRPC_FIRST_ADDRESS,

View File

@ -8,33 +8,33 @@ const HEX_REGEX = /^0x[0-9A-F]*$/i;
export const assert = { export const assert = {
isBigNumber(variableName: string, value: BigNumber): void { isBigNumber(variableName: string, value: BigNumber): void {
const isBigNumber = _.isObject(value) && (value as any).isBigNumber; const isBigNumber = _.isObject(value) && (value as any).isBigNumber;
this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value)); assert.assert(isBigNumber, assert.typeAssertionMessage(variableName, 'BigNumber', value));
}, },
isValidBaseUnitAmount(variableName: string, value: BigNumber): void { isValidBaseUnitAmount(variableName: string, value: BigNumber): void {
assert.isBigNumber(variableName, value); assert.isBigNumber(variableName, value);
const isNegative = value.lessThan(0); const isNegative = value.lessThan(0);
this.assert(!isNegative, `${variableName} cannot be a negative number, found value: ${value.toNumber()}`); assert.assert(!isNegative, `${variableName} cannot be a negative number, found value: ${value.toNumber()}`);
const hasDecimals = value.decimalPlaces() !== 0; const hasDecimals = value.decimalPlaces() !== 0;
this.assert( assert.assert(
!hasDecimals, !hasDecimals,
`${variableName} should be in baseUnits (no decimals), found value: ${value.toNumber()}`, `${variableName} should be in baseUnits (no decimals), found value: ${value.toNumber()}`,
); );
}, },
isString(variableName: string, value: string): void { isString(variableName: string, value: string): void {
this.assert(_.isString(value), this.typeAssertionMessage(variableName, 'string', value)); assert.assert(_.isString(value), assert.typeAssertionMessage(variableName, 'string', value));
}, },
isFunction(variableName: string, value: any): void { isFunction(variableName: string, value: any): void {
this.assert(_.isFunction(value), this.typeAssertionMessage(variableName, 'function', value)); assert.assert(_.isFunction(value), assert.typeAssertionMessage(variableName, 'function', value));
}, },
isHexString(variableName: string, value: string): void { isHexString(variableName: string, value: string): void {
this.assert( assert.assert(
_.isString(value) && HEX_REGEX.test(value), _.isString(value) && HEX_REGEX.test(value),
this.typeAssertionMessage(variableName, 'HexString', value), assert.typeAssertionMessage(variableName, 'HexString', value),
); );
}, },
isETHAddressHex(variableName: string, value: string): void { isETHAddressHex(variableName: string, value: string): void {
this.assert(_.isString(value), this.typeAssertionMessage(variableName, 'string', value)); assert.assert(_.isString(value), assert.typeAssertionMessage(variableName, 'string', value));
this.assert(addressUtils.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value)); assert.assert(addressUtils.isAddress(value), assert.typeAssertionMessage(variableName, 'ETHAddressHex', value));
}, },
doesBelongToStringEnum( doesBelongToStringEnum(
variableName: string, variableName: string,
@ -51,17 +51,17 @@ export const assert = {
); );
}, },
hasAtMostOneUniqueValue(value: any[], errMsg: string): void { hasAtMostOneUniqueValue(value: any[], errMsg: string): void {
this.assert(_.uniq(value).length <= 1, errMsg); assert.assert(_.uniq(value).length <= 1, errMsg);
}, },
isNumber(variableName: string, value: number): void { isNumber(variableName: string, value: number): void {
this.assert(_.isFinite(value), this.typeAssertionMessage(variableName, 'number', value)); assert.assert(_.isFinite(value), assert.typeAssertionMessage(variableName, 'number', value));
}, },
isBoolean(variableName: string, value: boolean): void { isBoolean(variableName: string, value: boolean): void {
this.assert(_.isBoolean(value), this.typeAssertionMessage(variableName, 'boolean', value)); assert.assert(_.isBoolean(value), assert.typeAssertionMessage(variableName, 'boolean', value));
}, },
isWeb3Provider(variableName: string, value: any): void { isWeb3Provider(variableName: string, value: any): void {
const isWeb3Provider = _.isFunction(value.send) || _.isFunction(value.sendAsync); const isWeb3Provider = _.isFunction(value.send) || _.isFunction(value.sendAsync);
this.assert(isWeb3Provider, this.typeAssertionMessage(variableName, 'Provider', value)); assert.assert(isWeb3Provider, assert.typeAssertionMessage(variableName, 'Provider', value));
}, },
doesConformToSchema(variableName: string, value: any, schema: Schema, subSchemas?: Schema[]): void { doesConformToSchema(variableName: string, value: any, schema: Schema, subSchemas?: Schema[]): void {
if (_.isUndefined(value)) { if (_.isUndefined(value)) {
@ -76,15 +76,15 @@ export const assert = {
const msg = `Expected ${variableName} to conform to schema ${schema.id} const msg = `Expected ${variableName} to conform to schema ${schema.id}
Encountered: ${JSON.stringify(value, null, '\t')} Encountered: ${JSON.stringify(value, null, '\t')}
Validation errors: ${validationResult.errors.join(', ')}`; Validation errors: ${validationResult.errors.join(', ')}`;
this.assert(!hasValidationErrors, msg); assert.assert(!hasValidationErrors, msg);
}, },
isWebUri(variableName: string, value: any): void { isWebUri(variableName: string, value: any): void {
const isValidUrl = !_.isUndefined(validUrl.isWebUri(value)); const isValidUrl = !_.isUndefined(validUrl.isWebUri(value));
this.assert(isValidUrl, this.typeAssertionMessage(variableName, 'web uri', value)); assert.assert(isValidUrl, assert.typeAssertionMessage(variableName, 'web uri', value));
}, },
isUri(variableName: string, value: any): void { isUri(variableName: string, value: any): void {
const isValidUri = !_.isUndefined(validUrl.isUri(value)); const isValidUri = !_.isUndefined(validUrl.isUri(value));
this.assert(isValidUri, this.typeAssertionMessage(variableName, 'uri', value)); assert.assert(isValidUri, assert.typeAssertionMessage(variableName, 'uri', value));
}, },
assert(condition: boolean, message: string): void { assert(condition: boolean, message: string): void {
if (!condition) { if (!condition) {

View File

@ -49,7 +49,7 @@ describe('Assertions', () => {
}); });
describe('#isFunction', () => { describe('#isFunction', () => {
it('should not throw for valid input', () => { it('should not throw for valid input', () => {
const validInputs = [BigNumber, assert.isString]; const validInputs = [BigNumber, assert.isString.bind(assert)];
validInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.not.throw()); validInputs.forEach(input => expect(assert.isFunction.bind(assert, variableName, input)).to.not.throw());
}); });
it('should throw for invalid input', () => { it('should throw for invalid input', () => {

View File

@ -72,15 +72,13 @@ export class BaseContract {
// 1. Optional param passed in to public method call // 1. Optional param passed in to public method call
// 2. Global config passed in at library instantiation // 2. Global config passed in at library instantiation
// 3. Gas estimate calculation + safety margin // 3. Gas estimate calculation + safety margin
const removeUndefinedProperties = _.pickBy; const removeUndefinedProperties = _.pickBy.bind(_);
const txDataWithDefaults: TxData = { const txDataWithDefaults = {
...removeUndefinedProperties(txDefaults), ...removeUndefinedProperties(txDefaults),
...removeUndefinedProperties(txData as any), ...removeUndefinedProperties(txData),
// HACK: TS can't prove that T is spreadable. };
// Awaiting https://github.com/Microsoft/TypeScript/pull/13288 to be merged
} as any;
if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) { if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) {
txDataWithDefaults.gas = await estimateGasAsync(txDataWithDefaults as any); txDataWithDefaults.gas = await estimateGasAsync(txDataWithDefaults);
} }
return txDataWithDefaults; return txDataWithDefaults;
} }

View File

@ -38,7 +38,7 @@ const OPTS_TO_QUERY_FIELD_MAP = {
* that implement the standard relayer API v0 * that implement the standard relayer API v0
*/ */
export class HttpClient implements Client { export class HttpClient implements Client {
private _apiEndpointUrl: string; private readonly _apiEndpointUrl: string;
/** /**
* Format parameters to be appended to http requests into query string form * Format parameters to be appended to http requests into query string form
*/ */

View File

@ -6,12 +6,12 @@ export const typeConverters = {
const bids = _.get(orderbook, 'bids', []); const bids = _.get(orderbook, 'bids', []);
const asks = _.get(orderbook, 'asks', []); const asks = _.get(orderbook, 'asks', []);
return { return {
bids: bids.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)), bids: bids.map((order: any) => typeConverters.convertOrderStringFieldsToBigNumber(order)),
asks: asks.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)), asks: asks.map((order: any) => typeConverters.convertOrderStringFieldsToBigNumber(order)),
}; };
}, },
convertOrderStringFieldsToBigNumber(order: any): any { convertOrderStringFieldsToBigNumber(order: any): any {
return this.convertStringsFieldsToBigNumbers(order, [ return typeConverters.convertStringsFieldsToBigNumbers(order, [
'makerTokenAmount', 'makerTokenAmount',
'takerTokenAmount', 'takerTokenAmount',
'makerFee', 'makerFee',

View File

@ -15,9 +15,9 @@ import { orderbookChannelMessageParser } from './utils/orderbook_channel_message
* that implements the standard relayer API v0 * that implements the standard relayer API v0
*/ */
export class WebSocketOrderbookChannel implements OrderbookChannel { export class WebSocketOrderbookChannel implements OrderbookChannel {
private _client: WebSocket.w3cwebsocket; private readonly _client: WebSocket.w3cwebsocket;
private _handler: OrderbookChannelHandler; private readonly _handler: OrderbookChannelHandler;
private _subscriptionOptsList: OrderbookChannelSubscriptionOpts[] = []; private readonly _subscriptionOptsList: OrderbookChannelSubscriptionOpts[] = [];
/** /**
* Instantiates a new WebSocketOrderbookChannel instance * Instantiates a new WebSocketOrderbookChannel instance
* @param client A WebSocket client * @param client A WebSocket client

View File

@ -29,7 +29,7 @@ describe('WebSocketOrderbookChannel', () => {
const websocketUrl = 'ws://localhost:8080'; const websocketUrl = 'ws://localhost:8080';
const openClient = new WebSocket.w3cwebsocket(websocketUrl); const openClient = new WebSocket.w3cwebsocket(websocketUrl);
Sinon.stub(openClient, 'readyState').get(() => WebSocket.w3cwebsocket.OPEN); Sinon.stub(openClient, 'readyState').get(() => WebSocket.w3cwebsocket.OPEN);
Sinon.stub(openClient, 'send').callsFake(_.noop); Sinon.stub(openClient, 'send').callsFake(_.noop.bind(_));
const openOrderbookChannel = new WebSocketOrderbookChannel(openClient, emptyOrderbookChannelHandler); const openOrderbookChannel = new WebSocketOrderbookChannel(openClient, emptyOrderbookChannelHandler);
const subscriptionOpts = { const subscriptionOpts = {
baseTokenAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d', baseTokenAddress: '0x323b5d4c32345ced77393b3530b1eed0f346429d',

View File

@ -7,7 +7,7 @@ before('migrate contracts', async function(): Promise<void> {
// HACK: Since the migrations take longer then our global mocha timeout limit // HACK: Since the migrations take longer then our global mocha timeout limit
// we manually increase it for this before hook. // we manually increase it for this before hook.
const mochaTestTimeoutMs = 50000; const mochaTestTimeoutMs = 50000;
this.timeout(mochaTestTimeoutMs); this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = { const txDefaults = {
gas: devConstants.GAS_LIMIT, gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS, from: devConstants.TESTRPC_FIRST_ADDRESS,

View File

@ -17,7 +17,7 @@ interface ProxyIdToAssetWrappers {
* the logic that uses it does not need to care what standard a token belongs to. * the logic that uses it does not need to care what standard a token belongs to.
*/ */
export class AssetWrapper { export class AssetWrapper {
private _proxyIdToAssetWrappers: ProxyIdToAssetWrappers; private readonly _proxyIdToAssetWrappers: ProxyIdToAssetWrappers;
constructor(assetWrappers: AbstractAssetWrapper[]) { constructor(assetWrappers: AbstractAssetWrapper[]) {
this._proxyIdToAssetWrappers = {}; this._proxyIdToAssetWrappers = {};
_.each(assetWrappers, assetWrapper => { _.each(assetWrappers, assetWrapper => {

View File

@ -13,11 +13,11 @@ import { ERC20BalancesByOwner } from './types';
import { txDefaults } from './web3_wrapper'; import { txDefaults } from './web3_wrapper';
export class ERC20Wrapper { export class ERC20Wrapper {
private _tokenOwnerAddresses: string[]; private readonly _tokenOwnerAddresses: string[];
private _contractOwnerAddress: string; private readonly _contractOwnerAddress: string;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _provider: Provider; private readonly _provider: Provider;
private _dummyTokenContracts: DummyERC20TokenContract[]; private readonly _dummyTokenContracts: DummyERC20TokenContract[];
private _proxyContract?: ERC20ProxyContract; private _proxyContract?: ERC20ProxyContract;
private _proxyIdIfExists?: string; private _proxyIdIfExists?: string;
constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) { constructor(provider: Provider, tokenOwnerAddresses: string[], contractOwnerAddress: string) {

View File

@ -13,11 +13,11 @@ import { ERC721TokenIdsByOwner } from './types';
import { txDefaults } from './web3_wrapper'; import { txDefaults } from './web3_wrapper';
export class ERC721Wrapper { export class ERC721Wrapper {
private _tokenOwnerAddresses: string[]; private readonly _tokenOwnerAddresses: string[];
private _contractOwnerAddress: string; private readonly _contractOwnerAddress: string;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _provider: Provider; private readonly _provider: Provider;
private _dummyTokenContracts: DummyERC721TokenContract[]; private readonly _dummyTokenContracts: DummyERC721TokenContract[];
private _proxyContract?: ERC721ProxyContract; private _proxyContract?: ERC721ProxyContract;
private _proxyIdIfExists?: string; private _proxyIdIfExists?: string;
private _initialTokenIdsByOwner: ERC721TokenIdsByOwner = {}; private _initialTokenIdsByOwner: ERC721TokenIdsByOwner = {};

View File

@ -11,9 +11,9 @@ import { orderUtils } from './order_utils';
import { OrderInfo, SignedTransaction } from './types'; import { OrderInfo, SignedTransaction } from './types';
export class ExchangeWrapper { export class ExchangeWrapper {
private _exchange: ExchangeContract; private readonly _exchange: ExchangeContract;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _logDecoder: LogDecoder; private readonly _logDecoder: LogDecoder;
constructor(exchangeContract: ExchangeContract, provider: Provider) { constructor(exchangeContract: ExchangeContract, provider: Provider) {
this._exchange = exchangeContract; this._exchange = exchangeContract;
this._web3Wrapper = new Web3Wrapper(provider); this._web3Wrapper = new Web3Wrapper(provider);

View File

@ -18,10 +18,10 @@ const ZERO_AMOUNT = new BigNumber(0);
const INSUFFICENT_ORDERS_FOR_MAKER_AMOUNT = 'Unable to satisfy makerAssetFillAmount with provided orders'; const INSUFFICENT_ORDERS_FOR_MAKER_AMOUNT = 'Unable to satisfy makerAssetFillAmount with provided orders';
export class ForwarderWrapper { export class ForwarderWrapper {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _forwarderContract: ForwarderContract; private readonly _forwarderContract: ForwarderContract;
private _logDecoder: LogDecoder; private readonly _logDecoder: LogDecoder;
private _zrxAddress: string; private readonly _zrxAddress: string;
private static _createOptimizedSellOrders(signedOrders: SignedOrder[]): MarketSellOrders { private static _createOptimizedSellOrders(signedOrders: SignedOrder[]): MarketSellOrders {
const marketSellOrders = formatters.createMarketSellOrders(signedOrders, ZERO_AMOUNT); const marketSellOrders = formatters.createMarketSellOrders(signedOrders, ZERO_AMOUNT);
const assetDataId = assetProxyUtils.decodeAssetDataId(signedOrders[0].makerAssetData); const assetDataId = assetProxyUtils.decodeAssetDataId(signedOrders[0].makerAssetData);

View File

@ -15,9 +15,9 @@ import { artifacts } from './artifacts';
import { constants } from './constants'; import { constants } from './constants';
export class LogDecoder { export class LogDecoder {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _contractAddress: string; private readonly _contractAddress: string;
private _abiDecoder: AbiDecoder; private readonly _abiDecoder: AbiDecoder;
public static wrapLogBigNumbers(log: any): any { public static wrapLogBigNumbers(log: any): any {
const argNames = _.keys(log.args); const argNames = _.keys(log.args);
for (const argName of argNames) { for (const argName of argNames) {

View File

@ -14,10 +14,10 @@ chaiSetup.configure();
const expect = chai.expect; const expect = chai.expect;
export class MatchOrderTester { export class MatchOrderTester {
private _exchangeWrapper: ExchangeWrapper; private readonly _exchangeWrapper: ExchangeWrapper;
private _erc20Wrapper: ERC20Wrapper; private readonly _erc20Wrapper: ERC20Wrapper;
private _erc721Wrapper: ERC721Wrapper; private readonly _erc721Wrapper: ERC721Wrapper;
private _feeTokenAddress: string; private readonly _feeTokenAddress: string;
/// @dev Compares a pair of ERC20 balances and a pair of ERC721 token owners. /// @dev Compares a pair of ERC20 balances and a pair of ERC721 token owners.
/// @param expectedNewERC20BalancesByOwner Expected ERC20 balances. /// @param expectedNewERC20BalancesByOwner Expected ERC20 balances.

View File

@ -10,9 +10,9 @@ import { constants } from './constants';
import { LogDecoder } from './log_decoder'; import { LogDecoder } from './log_decoder';
export class MultiSigWrapper { export class MultiSigWrapper {
private _multiSig: MultiSigWalletContract; private readonly _multiSig: MultiSigWalletContract;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _logDecoder: LogDecoder; private readonly _logDecoder: LogDecoder;
constructor(multiSigContract: MultiSigWalletContract, provider: Provider) { constructor(multiSigContract: MultiSigWalletContract, provider: Provider) {
this._multiSig = multiSigContract; this._multiSig = multiSigContract;
this._web3Wrapper = new Web3Wrapper(provider); this._web3Wrapper = new Web3Wrapper(provider);

View File

@ -6,8 +6,8 @@ import { constants } from './constants';
import { signingUtils } from './signing_utils'; import { signingUtils } from './signing_utils';
export class OrderFactory { export class OrderFactory {
private _defaultOrderParams: Partial<Order>; private readonly _defaultOrderParams: Partial<Order>;
private _privateKey: Buffer; private readonly _privateKey: Buffer;
constructor(privateKey: Buffer, defaultOrderParams: Partial<Order>) { constructor(privateKey: Buffer, defaultOrderParams: Partial<Order>) {
this._defaultOrderParams = defaultOrderParams; this._defaultOrderParams = defaultOrderParams;
this._privateKey = privateKey; this._privateKey = privateKey;

View File

@ -24,13 +24,13 @@ const FIVE_UNITS_FIVE_DECIMALS = new BigNumber(500_000);
const ONE_NFT_UNIT = new BigNumber(1); const ONE_NFT_UNIT = new BigNumber(1);
export class OrderFactoryFromScenario { export class OrderFactoryFromScenario {
private _userAddresses: string[]; private readonly _userAddresses: string[];
private _zrxAddress: string; private readonly _zrxAddress: string;
private _nonZrxERC20EighteenDecimalTokenAddresses: string[]; private readonly _nonZrxERC20EighteenDecimalTokenAddresses: string[];
private _erc20FiveDecimalTokenAddresses: string[]; private readonly _erc20FiveDecimalTokenAddresses: string[];
private _erc721Token: DummyERC721TokenContract; private readonly _erc721Token: DummyERC721TokenContract;
private _erc721Balances: ERC721TokenIdsByOwner; private readonly _erc721Balances: ERC721TokenIdsByOwner;
private _exchangeAddress: string; private readonly _exchangeAddress: string;
constructor( constructor(
userAddresses: string[], userAddresses: string[],
zrxAddress: string, zrxAddress: string,

View File

@ -4,7 +4,7 @@ import { BigNumber } from '@0xproject/utils';
import { AssetWrapper } from './asset_wrapper'; import { AssetWrapper } from './asset_wrapper';
export class SimpleAssetBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher { export class SimpleAssetBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher {
private _assetWrapper: AssetWrapper; private readonly _assetWrapper: AssetWrapper;
constructor(assetWrapper: AssetWrapper) { constructor(assetWrapper: AssetWrapper) {
this._assetWrapper = assetWrapper; this._assetWrapper = assetWrapper;
} }

View File

@ -4,8 +4,8 @@ import { BigNumber } from '@0xproject/utils';
import { ExchangeWrapper } from './exchange_wrapper'; import { ExchangeWrapper } from './exchange_wrapper';
export class SimpleOrderFilledCancelledFetcher implements AbstractOrderFilledCancelledFetcher { export class SimpleOrderFilledCancelledFetcher implements AbstractOrderFilledCancelledFetcher {
private _exchangeWrapper: ExchangeWrapper; private readonly _exchangeWrapper: ExchangeWrapper;
private _zrxAssetData: string; private readonly _zrxAssetData: string;
constructor(exchange: ExchangeWrapper, zrxAssetData: string) { constructor(exchange: ExchangeWrapper, zrxAssetData: string) {
this._exchangeWrapper = exchange; this._exchangeWrapper = exchange;
this._zrxAssetData = zrxAssetData; this._zrxAssetData = zrxAssetData;

View File

@ -8,8 +8,8 @@ import { Token } from './types';
import { constants } from './constants'; import { constants } from './constants';
export class TokenRegWrapper { export class TokenRegWrapper {
private _tokenReg: TokenRegistryContract; private readonly _tokenReg: TokenRegistryContract;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
constructor(tokenRegContract: TokenRegistryContract, provider: Provider) { constructor(tokenRegContract: TokenRegistryContract, provider: Provider) {
this._tokenReg = tokenRegContract; this._tokenReg = tokenRegContract;
this._web3Wrapper = new Web3Wrapper(provider); this._web3Wrapper = new Web3Wrapper(provider);

View File

@ -15,9 +15,9 @@ const EIP712_ZEROEX_TRANSACTION_SCHEMA: EIP712Schema = {
}; };
export class TransactionFactory { export class TransactionFactory {
private _signerBuff: Buffer; private readonly _signerBuff: Buffer;
private _exchangeAddress: string; private readonly _exchangeAddress: string;
private _privateKey: Buffer; private readonly _privateKey: Buffer;
constructor(privateKey: Buffer, exchangeAddress: string) { constructor(privateKey: Buffer, exchangeAddress: string) {
this._privateKey = privateKey; this._privateKey = privateKey;
this._exchangeAddress = exchangeAddress; this._exchangeAddress = exchangeAddress;

View File

@ -51,8 +51,10 @@ export const provider = web3Factory.getRpcProvider(providerConfigs);
const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage); const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage);
const isProfilerEnabled = env.parseBoolean(EnvVars.SolidityProfiler); const isProfilerEnabled = env.parseBoolean(EnvVars.SolidityProfiler);
const isRevertTraceEnabled = env.parseBoolean(EnvVars.SolidityRevertTrace); const isRevertTraceEnabled = env.parseBoolean(EnvVars.SolidityRevertTrace);
const enabledSubproviderCount = _.filter([isCoverageEnabled, isProfilerEnabled, isRevertTraceEnabled], _.identity) const enabledSubproviderCount = _.filter(
.length; [isCoverageEnabled, isProfilerEnabled, isRevertTraceEnabled],
_.identity.bind(_),
).length;
if (enabledSubproviderCount > 1) { if (enabledSubproviderCount > 1) {
throw new Error(`Only one of coverage, profiler, or revert trace subproviders can be enabled at a time`); throw new Error(`Only one of coverage, profiler, or revert trace subproviders can be enabled at a time`);
} }

View File

@ -10,8 +10,8 @@ import * as _ from 'lodash';
const MINIMUM_BLOCKS = 3; const MINIMUM_BLOCKS = 3;
export class BlockchainLifecycle { export class BlockchainLifecycle {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _snapshotIdsStack: number[]; private readonly _snapshotIdsStack: number[];
private _addresses: string[] = []; private _addresses: string[] = [];
private _nodeType: NodeType | undefined; private _nodeType: NodeType | undefined;
constructor(web3Wrapper: Web3Wrapper) { constructor(web3Wrapper: Web3Wrapper) {

View File

@ -11,12 +11,12 @@ import { ERC20TokenContract } from './generated_contract_wrappers/erc20_token';
import { ExchangeContract } from './generated_contract_wrappers/exchange'; import { ExchangeContract } from './generated_contract_wrappers/exchange';
export class FillScenarios { export class FillScenarios {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _userAddresses: string[]; private readonly _userAddresses: string[];
private _coinbase: string; private readonly _coinbase: string;
private _zrxTokenAddress: string; private readonly _zrxTokenAddress: string;
private _exchangeAddress: string; private readonly _exchangeAddress: string;
private _erc20ProxyAddress: string; private readonly _erc20ProxyAddress: string;
constructor( constructor(
provider: Provider, provider: Provider,
userAddresses: string[], userAddresses: string[],

View File

@ -7,7 +7,7 @@ import { schemas } from './schemas';
* A validator for [JSON-schemas](http://json-schema.org/) * A validator for [JSON-schemas](http://json-schema.org/)
*/ */
export class SchemaValidator { export class SchemaValidator {
private _validator: Validator; private readonly _validator: Validator;
/** /**
* Instantiates a SchemaValidator instance * Instantiates a SchemaValidator instance
*/ */

File diff suppressed because one or more lines are too long

View File

@ -4,8 +4,8 @@ import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
export class ArtifactWriter { export class ArtifactWriter {
private _artifactsDir: string; private readonly _artifactsDir: string;
private _networkId: number; private readonly _networkId: number;
constructor(artifactsDir: string, networkId: number) { constructor(artifactsDir: string, networkId: number) {
this._artifactsDir = artifactsDir; this._artifactsDir = artifactsDir;
this._networkId = networkId; this._networkId = networkId;

View File

@ -51,8 +51,13 @@ export const postpublishUtils = {
return configs; return configs;
}, },
async runAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> { async runAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> {
const configs = this.generateConfig(packageJSON, tsConfigJSON, cwd); const configs = postpublishUtils.generateConfig(packageJSON, tsConfigJSON, cwd);
await this.publishReleaseNotesAsync(configs.cwd, configs.packageName, configs.version, configs.assets); await postpublishUtils.publishReleaseNotesAsync(
configs.cwd,
configs.packageName,
configs.version,
configs.assets,
);
if ( if (
!_.isUndefined(configs.docPublishConfigs.s3BucketPath) || !_.isUndefined(configs.docPublishConfigs.s3BucketPath) ||
!_.isUndefined(configs.docPublishConfigs.s3StagingBucketPath) !_.isUndefined(configs.docPublishConfigs.s3StagingBucketPath)
@ -69,7 +74,7 @@ export const postpublishUtils = {
} }
}, },
async publishDocsToStagingAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> { async publishDocsToStagingAsync(packageJSON: any, tsConfigJSON: any, cwd: string): Promise<void> {
const configs = this.generateConfig(packageJSON, tsConfigJSON, cwd); const configs = postpublishUtils.generateConfig(packageJSON, tsConfigJSON, cwd);
if (_.isUndefined(configs.docPublishConfigs.s3StagingBucketPath)) { if (_.isUndefined(configs.docPublishConfigs.s3StagingBucketPath)) {
utils.log('config.postpublish.docPublishConfigs.s3StagingBucketPath entry in package.json not found!'); utils.log('config.postpublish.docPublishConfigs.s3StagingBucketPath entry in package.json not found!');
return; return;
@ -84,10 +89,10 @@ export const postpublishUtils = {
); );
}, },
async publishReleaseNotesAsync(cwd: string, packageName: string, version: string, assets: string[]): Promise<void> { async publishReleaseNotesAsync(cwd: string, packageName: string, version: string, assets: string[]): Promise<void> {
const notes = this.getReleaseNotes(packageName, version); const notes = postpublishUtils.getReleaseNotes(packageName, version);
const releaseName = this.getReleaseName(packageName, version); const releaseName = postpublishUtils.getReleaseName(packageName, version);
const tag = this.getTag(packageName, version); const tag = postpublishUtils.getTag(packageName, version);
this.adjustAssetPaths(cwd, assets); postpublishUtils.adjustAssetPaths(cwd, assets);
utils.log('POSTPUBLISH: Releasing ', releaseName, '...'); utils.log('POSTPUBLISH: Releasing ', releaseName, '...');
await publishReleaseAsync({ await publishReleaseAsync({
token: constants.githubPersonalAccessToken, token: constants.githubPersonalAccessToken,
@ -165,7 +170,7 @@ export const postpublishUtils = {
version: string, version: string,
S3BucketPath: string, S3BucketPath: string,
): Promise<void> { ): Promise<void> {
const fileIncludesAdjusted = this.adjustFileIncludePaths(fileIncludes, cwd); const fileIncludesAdjusted = postpublishUtils.adjustFileIncludePaths(fileIncludes, cwd);
const projectFiles = fileIncludesAdjusted.join(' '); const projectFiles = fileIncludesAdjusted.join(' ');
const jsonFilePath = `${cwd}/${generatedDocsDirectoryName}/index.json`; const jsonFilePath = `${cwd}/${generatedDocsDirectoryName}/index.json`;
const result = await execAsync( const result = await execAsync(

View File

@ -10,7 +10,7 @@ import { Change, Changelog, VersionChangelog } from '../types';
const CHANGELOG_MD_HEADER = ` const CHANGELOG_MD_HEADER = `
<!-- <!--
This file is auto-generated using the monorepo-scripts package. Don't edit directly. changelogUtils.file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only. Edit the package's CHANGELOG.json file only.
--> -->
@ -74,7 +74,7 @@ export const changelogUtils = {
}, },
getChangelogOrCreateIfMissing(packageName: string, packageLocation: string): Changelog { getChangelogOrCreateIfMissing(packageName: string, packageLocation: string): Changelog {
const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json'); const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json');
let changelogJsonIfExists = this.getChangelogJSONIfExists(changelogJSONPath); let changelogJsonIfExists = changelogUtils.getChangelogJSONIfExists(changelogJSONPath);
if (_.isUndefined(changelogJsonIfExists)) { if (_.isUndefined(changelogJsonIfExists)) {
// If none exists, create new, empty one. // If none exists, create new, empty one.
changelogJsonIfExists = '[]'; changelogJsonIfExists = '[]';
@ -91,12 +91,12 @@ export const changelogUtils = {
async writeChangelogJsonFileAsync(packageLocation: string, changelog: Changelog): Promise<void> { async writeChangelogJsonFileAsync(packageLocation: string, changelog: Changelog): Promise<void> {
const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json'); const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json');
fs.writeFileSync(changelogJSONPath, JSON.stringify(changelog, null, '\t')); fs.writeFileSync(changelogJSONPath, JSON.stringify(changelog, null, '\t'));
await this.prettifyAsync(changelogJSONPath, constants.monorepoRootPath); await changelogUtils.prettifyAsync(changelogJSONPath, constants.monorepoRootPath);
}, },
async writeChangelogMdFileAsync(packageLocation: string, changelogMdString: string): Promise<void> { async writeChangelogMdFileAsync(packageLocation: string, changelogMdString: string): Promise<void> {
const changelogMarkdownPath = path.join(packageLocation, 'CHANGELOG.md'); const changelogMarkdownPath = path.join(packageLocation, 'CHANGELOG.md');
fs.writeFileSync(changelogMarkdownPath, changelogMdString); fs.writeFileSync(changelogMarkdownPath, changelogMdString);
await this.prettifyAsync(changelogMarkdownPath, constants.monorepoRootPath); await changelogUtils.prettifyAsync(changelogMarkdownPath, constants.monorepoRootPath);
}, },
async prettifyAsync(filePath: string, cwd: string): Promise<void> { async prettifyAsync(filePath: string, cwd: string): Promise<void> {
await execAsync(`prettier --write ${filePath} --config .prettierrc`, { await execAsync(`prettier --write ${filePath} --config .prettierrc`, {

View File

@ -13,7 +13,7 @@ export const utils = {
console.log(...args); // tslint:disable-line:no-console console.log(...args); // tslint:disable-line:no-console
}, },
async getUpdatedLernaPackagesAsync(shouldIncludePrivate: boolean): Promise<LernaPackage[]> { async getUpdatedLernaPackagesAsync(shouldIncludePrivate: boolean): Promise<LernaPackage[]> {
const updatedPublicPackages = await this.getLernaUpdatedPackagesAsync(shouldIncludePrivate); const updatedPublicPackages = await utils.getLernaUpdatedPackagesAsync(shouldIncludePrivate);
const updatedPackageNames = _.map(updatedPublicPackages, pkg => pkg.name); const updatedPackageNames = _.map(updatedPublicPackages, pkg => pkg.name);
const allLernaPackages = lernaGetPackages(constants.monorepoRootPath); const allLernaPackages = lernaGetPackages(constants.monorepoRootPath);
@ -110,7 +110,7 @@ export const utils = {
} catch (err) { } catch (err) {
throw new Error(`Failed to delete local git tag. Got err: ${err}`); throw new Error(`Failed to delete local git tag. Got err: ${err}`);
} }
this.log(`Removed local tag: ${tagName}`); utils.log(`Removed local tag: ${tagName}`);
}, },
async removeRemoteTagAsync(tagName: string): Promise<void> { async removeRemoteTagAsync(tagName: string): Promise<void> {
try { try {
@ -120,6 +120,6 @@ export const utils = {
} catch (err) { } catch (err) {
throw new Error(`Failed to delete remote git tag. Got err: ${err}`); throw new Error(`Failed to delete remote git tag. Got err: ${err}`);
} }
this.log(`Removed remote tag: ${tagName}`); utils.log(`Removed remote tag: ${tagName}`);
}, },
}; };

View File

@ -34,7 +34,7 @@ const ERR_MSG_MAPPING = {
}; };
export class ExchangeTransferSimulator { export class ExchangeTransferSimulator {
private _store: AbstractBalanceAndProxyAllowanceLazyStore; private readonly _store: AbstractBalanceAndProxyAllowanceLazyStore;
private static _throwValidationError( private static _throwValidationError(
failureReason: FailureReason, failureReason: FailureReason,
tradeSide: TradeSide, tradeSide: TradeSide,

View File

@ -27,8 +27,8 @@ interface SidedOrderRelevantState {
const ACCEPTABLE_RELATIVE_ROUNDING_ERROR = 0.0001; const ACCEPTABLE_RELATIVE_ROUNDING_ERROR = 0.0001;
export class OrderStateUtils { export class OrderStateUtils {
private _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher; private readonly _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher;
private _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher; private readonly _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher;
private static _validateIfOrderIsValid( private static _validateIfOrderIsValid(
signedOrder: SignedOrder, signedOrder: SignedOrder,
sidedOrderRelevantState: SidedOrderRelevantState, sidedOrderRelevantState: SidedOrderRelevantState,

View File

@ -13,7 +13,7 @@ import { isValidSignatureAsync } from './signature_utils';
import { utils } from './utils'; import { utils } from './utils';
export class OrderValidationUtils { export class OrderValidationUtils {
private _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher; private readonly _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher;
public static isRoundingError(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean { public static isRoundingError(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean {
// Solidity's mulmod() in JS // Solidity's mulmod() in JS
// Source: https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#mathematical-and-cryptographic-functions // Source: https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#mathematical-and-cryptographic-functions

View File

@ -1,14 +1,14 @@
import { BigNumber } from '@0xproject/utils'; import { BigNumber } from '@0xproject/utils';
export class RemainingFillableCalculator { export class RemainingFillableCalculator {
private _isTraderAssetZRX: boolean; private readonly _isTraderAssetZRX: boolean;
// Transferrable Amount is the minimum of Approval and Balance // Transferrable Amount is the minimum of Approval and Balance
private _transferrableAssetAmount: BigNumber; private readonly _transferrableAssetAmount: BigNumber;
private _transferrableFeeAmount: BigNumber; private readonly _transferrableFeeAmount: BigNumber;
private _remainingOrderAssetAmount: BigNumber; private readonly _remainingOrderAssetAmount: BigNumber;
private _remainingOrderFeeAmount: BigNumber; private readonly _remainingOrderFeeAmount: BigNumber;
private _orderFee: BigNumber; private readonly _orderFee: BigNumber;
private _orderAssetAmount: BigNumber; private readonly _orderAssetAmount: BigNumber;
constructor( constructor(
orderFee: BigNumber, orderFee: BigNumber,
orderAssetAmount: BigNumber, orderAssetAmount: BigNumber,

View File

@ -8,7 +8,7 @@ import { AbstractBalanceAndProxyAllowanceLazyStore } from '../abstract/abstract_
* Copy on read store for balances/proxyAllowances of tokens/accounts * Copy on read store for balances/proxyAllowances of tokens/accounts
*/ */
export class BalanceAndProxyAllowanceLazyStore implements AbstractBalanceAndProxyAllowanceLazyStore { export class BalanceAndProxyAllowanceLazyStore implements AbstractBalanceAndProxyAllowanceLazyStore {
private _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher; private readonly _balanceAndProxyAllowanceFetcher: AbstractBalanceAndProxyAllowanceFetcher;
private _balance: { private _balance: {
[assetData: string]: { [assetData: string]: {
[userAddress: string]: BigNumber; [userAddress: string]: BigNumber;

View File

@ -34,7 +34,7 @@ describe('ExchangeTransferSimulator', async () => {
let erc20ProxyAddress: string; let erc20ProxyAddress: string;
before(async function(): Promise<void> { before(async function(): Promise<void> {
const mochaTestTimeoutMs = 20000; const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs); this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
userAddresses = await web3Wrapper.getAvailableAddressesAsync(); userAddresses = await web3Wrapper.getAvailableAddressesAsync();
[coinbase, sender, recipient] = userAddresses; [coinbase, sender, recipient] = userAddresses;
@ -77,8 +77,7 @@ describe('ExchangeTransferSimulator', async () => {
describe('#transferFromAsync', function(): void { describe('#transferFromAsync', function(): void {
// HACK: For some reason these tests need a slightly longer timeout // HACK: For some reason these tests need a slightly longer timeout
const mochaTestTimeoutMs = 3000; const mochaTestTimeoutMs = 3000;
this.timeout(mochaTestTimeoutMs); this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
beforeEach(() => { beforeEach(() => {
const simpleERC20BalanceAndProxyAllowanceFetcher = new SimpleERC20BalanceAndProxyAllowanceFetcher( const simpleERC20BalanceAndProxyAllowanceFetcher = new SimpleERC20BalanceAndProxyAllowanceFetcher(
(dummyERC20Token as any) as ERC20TokenContract, (dummyERC20Token as any) as ERC20TokenContract,

View File

@ -5,8 +5,8 @@ import { AbstractBalanceAndProxyAllowanceFetcher } from '../../src/abstract/abst
import { ERC20TokenContract } from '../../src/generated_contract_wrappers/erc20_token'; import { ERC20TokenContract } from '../../src/generated_contract_wrappers/erc20_token';
export class SimpleERC20BalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher { export class SimpleERC20BalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher {
private _erc20TokenContract: ERC20TokenContract; private readonly _erc20TokenContract: ERC20TokenContract;
private _erc20ProxyAddress: string; private readonly _erc20ProxyAddress: string;
constructor(erc20TokenWrapper: ERC20TokenContract, erc20ProxyAddress: string) { constructor(erc20TokenWrapper: ERC20TokenContract, erc20ProxyAddress: string) {
this._erc20TokenContract = erc20TokenWrapper; this._erc20TokenContract = erc20TokenWrapper;
this._erc20ProxyAddress = erc20ProxyAddress; this._erc20ProxyAddress = erc20ProxyAddress;

View File

@ -19,14 +19,14 @@ enum LogEventState {
* depth. * depth.
*/ */
export class EventWatcher { export class EventWatcher {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _blockAndLogStreamerIfExists: BlockAndLogStreamer<Block, Log> | undefined; private _blockAndLogStreamerIfExists: BlockAndLogStreamer<Block, Log> | undefined;
private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer; private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer;
private _onLogAddedSubscriptionToken: string | undefined; private _onLogAddedSubscriptionToken: string | undefined;
private _onLogRemovedSubscriptionToken: string | undefined; private _onLogRemovedSubscriptionToken: string | undefined;
private _pollingIntervalMs: number; private readonly _pollingIntervalMs: number;
private _stateLayer: BlockParamLiteral; private readonly _stateLayer: BlockParamLiteral;
private _isVerbose: boolean; private readonly _isVerbose: boolean;
constructor( constructor(
web3Wrapper: Web3Wrapper, web3Wrapper: Web3Wrapper,
pollingIntervalIfExistsMs: undefined | number, pollingIntervalIfExistsMs: undefined | number,

View File

@ -13,10 +13,10 @@ const DEFAULT_ORDER_EXPIRATION_CHECKING_INTERVAL_MS = 50;
* It stores them in a min heap by expiration time and checks for expired ones every `orderExpirationCheckingIntervalMs` * It stores them in a min heap by expiration time and checks for expired ones every `orderExpirationCheckingIntervalMs`
*/ */
export class ExpirationWatcher { export class ExpirationWatcher {
private _orderHashByExpirationRBTree: RBTree<string>; private readonly _orderHashByExpirationRBTree: RBTree<string>;
private _expiration: { [orderHash: string]: BigNumber } = {}; private readonly _expiration: { [orderHash: string]: BigNumber } = {};
private _orderExpirationCheckingIntervalMs: number; private readonly _orderExpirationCheckingIntervalMs: number;
private _expirationMarginMs: number; private readonly _expirationMarginMs: number;
private _orderExpirationCheckingIntervalIdIfExists?: NodeJS.Timer; private _orderExpirationCheckingIntervalIdIfExists?: NodeJS.Timer;
constructor(expirationMarginIfExistsMs?: number, orderExpirationCheckingIntervalIfExistsMs?: number) { constructor(expirationMarginIfExistsMs?: number, orderExpirationCheckingIntervalIfExistsMs?: number) {
this._orderExpirationCheckingIntervalMs = this._orderExpirationCheckingIntervalMs =
@ -44,7 +44,7 @@ export class ExpirationWatcher {
this._orderExpirationCheckingIntervalIdIfExists = intervalUtils.setInterval( this._orderExpirationCheckingIntervalIdIfExists = intervalUtils.setInterval(
this._pruneExpiredOrders.bind(this, callback), this._pruneExpiredOrders.bind(this, callback),
this._orderExpirationCheckingIntervalMs, this._orderExpirationCheckingIntervalMs,
_.noop, // _pruneExpiredOrders never throws _.noop.bind(_), // _pruneExpiredOrders never throws
); );
} }
public unsubscribe(): void { public unsubscribe(): void {

View File

@ -69,18 +69,18 @@ const DEFAULT_CLEANUP_JOB_INTERVAL_MS = 1000 * 60 * 60; // 1h
* the order should be deemed invalid. * the order should be deemed invalid.
*/ */
export class OrderWatcher { export class OrderWatcher {
private _contractWrappers: ContractWrappers; private readonly _contractWrappers: ContractWrappers;
private _orderStateByOrderHashCache: OrderStateByOrderHash = {}; private readonly _orderStateByOrderHashCache: OrderStateByOrderHash = {};
private _orderByOrderHash: OrderByOrderHash = {}; private readonly _orderByOrderHash: OrderByOrderHash = {};
private _dependentOrderHashes: DependentOrderHashes = {}; private readonly _dependentOrderHashes: DependentOrderHashes = {};
private _callbackIfExists?: OnOrderStateChangeCallback; private _callbackIfExists?: OnOrderStateChangeCallback;
private _eventWatcher: EventWatcher; private readonly _eventWatcher: EventWatcher;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _expirationWatcher: ExpirationWatcher; private readonly _expirationWatcher: ExpirationWatcher;
private _orderStateUtils: OrderStateUtils; private readonly _orderStateUtils: OrderStateUtils;
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore; private readonly _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
private _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore; private readonly _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
private _cleanupJobInterval: number; private readonly _cleanupJobInterval: number;
private _cleanupJobIntervalIdIfExists?: NodeJS.Timer; private _cleanupJobIntervalIdIfExists?: NodeJS.Timer;
constructor(provider: Provider, networkId: number, config?: OrderWatcherConfig) { constructor(provider: Provider, networkId: number, config?: OrderWatcherConfig) {
this._web3Wrapper = new Web3Wrapper(provider); this._web3Wrapper = new Web3Wrapper(provider);

View File

@ -12,6 +12,6 @@ export const assert = {
...sharedAssert, ...sharedAssert,
isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string): void { isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string): void {
const isValid = isValidSignature(orderHash, ecSignature, signerAddress); const isValid = isValidSignature(orderHash, ecSignature, signerAddress);
this.assert(isValid, `Expected order with hash '${orderHash}' to have a valid signature`); assert.assert(isValid, `Expected order with hash '${orderHash}' to have a valid signature`);
}, },
}; };

View File

@ -7,7 +7,7 @@ before('migrate contracts', async function(): Promise<void> {
// HACK: Since the migrations take longer then our global mocha timeout limit // HACK: Since the migrations take longer then our global mocha timeout limit
// we manually increase it for this before hook. // we manually increase it for this before hook.
const mochaTestTimeoutMs = 25000; const mochaTestTimeoutMs = 25000;
this.timeout(mochaTestTimeoutMs); this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = { const txDefaults = {
gas: devConstants.GAS_LIMIT, gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS, from: devConstants.TESTRPC_FIRST_ADDRESS,

View File

@ -116,8 +116,8 @@ describe('OrderWatcher', () => {
orderWatcher.unsubscribe(); orderWatcher.unsubscribe();
}); });
it('should fail when trying to subscribe twice', async () => { it('should fail when trying to subscribe twice', async () => {
orderWatcher.subscribe(_.noop); orderWatcher.subscribe(_.noop.bind(_));
expect(() => orderWatcher.subscribe(_.noop)).to.throw(OrderWatcherError.SubscriptionAlreadyPresent); expect(() => orderWatcher.subscribe(_.noop.bind(_))).to.throw(OrderWatcherError.SubscriptionAlreadyPresent);
}); });
}); });
describe('tests with cleanup', async () => { describe('tests with cleanup', async () => {

View File

@ -7,7 +7,7 @@ const PROTOCOL_TOKEN_SYMBOL = 'ZRX';
const WETH_TOKEN_SYMBOL = 'WETH'; const WETH_TOKEN_SYMBOL = 'WETH';
export class TokenUtils { export class TokenUtils {
private _tokens: Token[]; private readonly _tokens: Token[];
constructor(tokens: Token[]) { constructor(tokens: Token[]) {
this._tokens = tokens; this._tokens = tokens;
} }

View File

@ -27,7 +27,7 @@ export class DocsInfo {
public sectionNameToMarkdown: { [sectionName: string]: string }; public sectionNameToMarkdown: { [sectionName: string]: string };
public contractsByVersionByNetworkId?: ContractsByVersionByNetworkId; public contractsByVersionByNetworkId?: ContractsByVersionByNetworkId;
public typeConfigs: DocsInfoTypeConfigs; public typeConfigs: DocsInfoTypeConfigs;
private _docsInfo: DocsInfoConfig; private readonly _docsInfo: DocsInfoConfig;
constructor(config: DocsInfoConfig) { constructor(config: DocsInfoConfig) {
this.id = config.id; this.id = config.id;
this.type = config.type; this.type = config.type;

View File

@ -31,8 +31,8 @@ export const doxityUtils = {
comment: doxityConstructor.details, comment: doxityConstructor.details,
returnComment: doxityConstructor.return, returnComment: doxityConstructor.return,
callPath: '', callPath: '',
parameters: this._convertParameters(doxityConstructor.inputs), parameters: doxityUtils._convertParameters(doxityConstructor.inputs),
returnType: this._convertType(doxityContractObj.name), returnType: doxityUtils._convertType(doxityContractObj.name),
}; };
constructors.push(constructor); constructors.push(constructor);
} }
@ -40,7 +40,7 @@ export const doxityUtils = {
const doxityMethods: DoxityAbiDoc[] = _.filter<DoxityAbiDoc>( const doxityMethods: DoxityAbiDoc[] = _.filter<DoxityAbiDoc>(
doxityContractObj.abiDocs, doxityContractObj.abiDocs,
(abiDoc: DoxityAbiDoc) => { (abiDoc: DoxityAbiDoc) => {
return this._isMethod(abiDoc); return doxityUtils._isMethod(abiDoc);
}, },
); );
const methods: SolidityMethod[] = _.map<DoxityAbiDoc, SolidityMethod>( const methods: SolidityMethod[] = _.map<DoxityAbiDoc, SolidityMethod>(
@ -52,10 +52,10 @@ export const doxityUtils = {
// no-op. It's already undefined // no-op. It's already undefined
} else if (outputs.length === 1) { } else if (outputs.length === 1) {
const outputsType = outputs[0].type; const outputsType = outputs[0].type;
returnTypeIfExists = this._convertType(outputsType); returnTypeIfExists = doxityUtils._convertType(outputsType);
} else { } else {
const outputsType = `[${_.map(outputs, output => output.type).join(', ')}]`; const outputsType = `[${_.map(outputs, output => output.type).join(', ')}]`;
returnTypeIfExists = this._convertType(outputsType); returnTypeIfExists = doxityUtils._convertType(outputsType);
} }
// For ZRXToken, we want to convert it to zrxToken, rather then simply zRXToken // For ZRXToken, we want to convert it to zrxToken, rather then simply zRXToken
const callPath = const callPath =
@ -70,7 +70,7 @@ export const doxityUtils = {
comment: doxityMethod.details, comment: doxityMethod.details,
returnComment: doxityMethod.return, returnComment: doxityMethod.return,
callPath, callPath,
parameters: this._convertParameters(doxityMethod.inputs), parameters: doxityUtils._convertParameters(doxityMethod.inputs),
returnType: returnTypeIfExists, returnType: returnTypeIfExists,
}; };
return method; return method;
@ -80,7 +80,7 @@ export const doxityUtils = {
const doxityProperties: DoxityAbiDoc[] = _.filter<DoxityAbiDoc>( const doxityProperties: DoxityAbiDoc[] = _.filter<DoxityAbiDoc>(
doxityContractObj.abiDocs, doxityContractObj.abiDocs,
(abiDoc: DoxityAbiDoc) => { (abiDoc: DoxityAbiDoc) => {
return this._isProperty(abiDoc); return doxityUtils._isProperty(abiDoc);
}, },
); );
const properties = _.map<DoxityAbiDoc, Property>(doxityProperties, (doxityProperty: DoxityAbiDoc) => { const properties = _.map<DoxityAbiDoc, Property>(doxityProperties, (doxityProperty: DoxityAbiDoc) => {
@ -92,7 +92,7 @@ export const doxityUtils = {
} }
const property = { const property = {
name: doxityProperty.name, name: doxityProperty.name,
type: this._convertType(typeName), type: doxityUtils._convertType(typeName),
comment: doxityProperty.details, comment: doxityProperty.details,
}; };
return property; return property;
@ -105,7 +105,7 @@ export const doxityUtils = {
const events = _.map(doxityEvents, doxityEvent => { const events = _.map(doxityEvents, doxityEvent => {
const event = { const event = {
name: doxityEvent.name, name: doxityEvent.name,
eventArgs: this._convertEventArgs(doxityEvent.inputs), eventArgs: doxityUtils._convertEventArgs(doxityEvent.inputs),
}; };
return event; return event;
}); });
@ -129,7 +129,7 @@ export const doxityUtils = {
name: input.name, name: input.name,
comment: input.description, comment: input.description,
isOptional: false, isOptional: false,
type: this._convertType(input.type), type: doxityUtils._convertType(input.type),
}; };
return parameter; return parameter;
}); });
@ -167,7 +167,7 @@ export const doxityUtils = {
const eventArg = { const eventArg = {
isIndexed: input.indexed, isIndexed: input.indexed,
name: input.name, name: input.name,
type: this._convertType(input.type), type: doxityUtils._convertType(input.type),
}; };
return eventArg; return eventArg;
}); });

View File

@ -235,7 +235,7 @@ export const typeDocUtils = {
childTypeIfExists = { childTypeIfExists = {
name: child.name, name: child.name,
typeDocType: TypeDocTypes.Reflection, typeDocType: TypeDocTypes.Reflection,
method: this._convertMethod(child, isConstructor, sections, sectionName, docId), method: typeDocUtils._convertMethod(child, isConstructor, sections, sectionName, docId),
}; };
} }
const c: CustomTypeChild = { const c: CustomTypeChild = {

View File

@ -41,7 +41,7 @@ const styles: Styles = {
export class NestedSidebarMenu extends React.Component<NestedSidebarMenuProps, NestedSidebarMenuState> { export class NestedSidebarMenu extends React.Component<NestedSidebarMenuProps, NestedSidebarMenuState> {
public static defaultProps: Partial<NestedSidebarMenuProps> = { public static defaultProps: Partial<NestedSidebarMenuProps> = {
shouldDisplaySectionHeaders: true, shouldDisplaySectionHeaders: true,
onMenuItemClick: _.noop, onMenuItemClick: _.noop.bind(_),
}; };
public render(): React.ReactNode { public render(): React.ReactNode {
const navigation = _.map(this.props.topLevelMenu, (menuItems: string[], sectionName: string) => { const navigation = _.map(this.props.topLevelMenu, (menuItems: string[], sectionName: string) => {

View File

@ -58,13 +58,13 @@ const CONFIG_FILE = 'compiler.json';
* to artifact files. * to artifact files.
*/ */
export class Compiler { export class Compiler {
private _resolver: Resolver; private readonly _resolver: Resolver;
private _nameResolver: NameResolver; private readonly _nameResolver: NameResolver;
private _contractsDir: string; private readonly _contractsDir: string;
private _compilerSettings: solc.CompilerSettings; private readonly _compilerSettings: solc.CompilerSettings;
private _artifactsDir: string; private readonly _artifactsDir: string;
private _solcVersionIfExists: string | undefined; private readonly _solcVersionIfExists: string | undefined;
private _specifiedContracts: string[] | TYPE_ALL_FILES_IDENTIFIER; private readonly _specifiedContracts: string[] | TYPE_ALL_FILES_IDENTIFIER;
/** /**
* Instantiates a new instance of the Compiler class. * Instantiates a new instance of the Compiler class.
* @return An instance of the Compiler class. * @return An instance of the Compiler class.

View File

@ -12,7 +12,7 @@ import { constants } from './util/constants';
const expect = chai.expect; const expect = chai.expect;
describe('#Compiler', function(): void { describe('#Compiler', function(): void {
this.timeout(constants.timeoutMs); this.timeout(constants.timeoutMs); // tslint:disable-line:no-invalid-this
const artifactsDir = `${__dirname}/fixtures/artifacts`; const artifactsDir = `${__dirname}/fixtures/artifacts`;
const contractsDir = `${__dirname}/fixtures/contracts`; const contractsDir = `${__dirname}/fixtures/contracts`;
const exchangeArtifactPath = `${artifactsDir}/Exchange.json`; const exchangeArtifactPath = `${artifactsDir}/Exchange.json`;

View File

@ -12,8 +12,8 @@ import { AbstractArtifactAdapter } from './abstract_artifact_adapter';
const CONFIG_FILE = 'compiler.json'; const CONFIG_FILE = 'compiler.json';
export class SolCompilerArtifactAdapter extends AbstractArtifactAdapter { export class SolCompilerArtifactAdapter extends AbstractArtifactAdapter {
private _artifactsPath: string; private readonly _artifactsPath: string;
private _sourcesPath: string; private readonly _sourcesPath: string;
constructor(artifactsPath?: string, sourcesPath?: string) { constructor(artifactsPath?: string, sourcesPath?: string) {
super(); super();
const config: CompilerOptions = fs.existsSync(CONFIG_FILE) const config: CompilerOptions = fs.existsSync(CONFIG_FILE)

View File

@ -7,8 +7,8 @@ import { AbstractArtifactAdapter } from './abstract_artifact_adapter';
import { SolCompilerArtifactAdapter } from './sol_compiler_artifact_adapter'; import { SolCompilerArtifactAdapter } from './sol_compiler_artifact_adapter';
export class TruffleArtifactAdapter extends AbstractArtifactAdapter { export class TruffleArtifactAdapter extends AbstractArtifactAdapter {
private _solcVersion: string; private readonly _solcVersion: string;
private _sourcesPath: string; private readonly _sourcesPath: string;
constructor(sourcesPath: string, solcVersion: string) { constructor(sourcesPath: string, solcVersion: string) {
super(); super();
this._solcVersion = solcVersion; this._solcVersion = solcVersion;

View File

@ -18,15 +18,15 @@ enum BranchType {
export class ASTVisitor { export class ASTVisitor {
private _entryId = 0; private _entryId = 0;
private _fnMap: FnMap = {}; private readonly _fnMap: FnMap = {};
private _branchMap: BranchMap = {}; private readonly _branchMap: BranchMap = {};
private _modifiersStatementIds: number[] = []; private readonly _modifiersStatementIds: number[] = [];
private _statementMap: StatementMap = {}; private readonly _statementMap: StatementMap = {};
private _locationByOffset: LocationByOffset; private readonly _locationByOffset: LocationByOffset;
private _ignoreRangesBeginningAt: number[]; private readonly _ignoreRangesBeginningAt: number[];
// keep track of contract/function ranges that are to be ignored // keep track of contract/function ranges that are to be ignored
// so we can also ignore any children nodes within the contract/function // so we can also ignore any children nodes within the contract/function
private _ignoreRangesWithin: Array<[number, number]> = []; private readonly _ignoreRangesWithin: Array<[number, number]> = [];
constructor(locationByOffset: LocationByOffset, ignoreRangesBeginningAt: number[] = []) { constructor(locationByOffset: LocationByOffset, ignoreRangesBeginningAt: number[] = []) {
this._locationByOffset = locationByOffset; this._locationByOffset = locationByOffset;
this._ignoreRangesBeginningAt = ignoreRangesBeginningAt; this._ignoreRangesBeginningAt = ignoreRangesBeginningAt;

View File

@ -23,7 +23,7 @@ import { utils } from './utils';
* It's used to compute your code coverage while running solidity tests. * It's used to compute your code coverage while running solidity tests.
*/ */
export class CoverageSubprovider extends TraceInfoSubprovider { export class CoverageSubprovider extends TraceInfoSubprovider {
private _coverageCollector: TraceCollector; private readonly _coverageCollector: TraceCollector;
/** /**
* Instantiates a CoverageSubprovider instance * Instantiates a CoverageSubprovider instance
* @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.)

View File

@ -38,7 +38,7 @@ export function getSourceRangeSnippet(sourceRange: SourceRange, sourceCode: stri
// A visitor which collects ASTInfo for most nodes in the AST. // A visitor which collects ASTInfo for most nodes in the AST.
class ASTInfoVisitor { class ASTInfoVisitor {
private _astInfos: ASTInfo[] = []; private readonly _astInfos: ASTInfo[] = [];
public getASTInfoForRange(sourceRange: SourceRange): ASTInfo | null { public getASTInfoForRange(sourceRange: SourceRange): ASTInfo | null {
// HACK(albrow): Sometimes the source range doesn't exactly match that // HACK(albrow): Sometimes the source range doesn't exactly match that
// of astInfo. To work around that we try with a +/-1 offset on // of astInfo. To work around that we try with a +/-1 offset on

View File

@ -12,7 +12,7 @@ import { utils } from './utils';
* ProfilerSubprovider is used to profile Solidity code while running tests. * ProfilerSubprovider is used to profile Solidity code while running tests.
*/ */
export class ProfilerSubprovider extends TraceInfoSubprovider { export class ProfilerSubprovider extends TraceInfoSubprovider {
private _profilerCollector: TraceCollector; private readonly _profilerCollector: TraceCollector;
/** /**
* Instantiates a ProfilerSubprovider instance * Instantiates a ProfilerSubprovider instance
* @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.) * @param artifactAdapter Adapter for used artifacts format (0x, truffle, giveth, etc.)

View File

@ -18,8 +18,8 @@ import { utils } from './utils';
export class RevertTraceSubprovider extends TraceCollectionSubprovider { export class RevertTraceSubprovider extends TraceCollectionSubprovider {
// Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise // Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise
private _contractsData!: ContractData[]; private _contractsData!: ContractData[];
private _artifactAdapter: AbstractArtifactAdapter; private readonly _artifactAdapter: AbstractArtifactAdapter;
private _logger: Logger; private readonly _logger: Logger;
/** /**
* Instantiates a RevertTraceSubprovider instance * Instantiates a RevertTraceSubprovider instance

View File

@ -32,10 +32,10 @@ export interface TraceCollectionSubproviderConfig {
export abstract class TraceCollectionSubprovider extends Subprovider { export abstract class TraceCollectionSubprovider extends Subprovider {
protected _web3Wrapper!: Web3Wrapper; protected _web3Wrapper!: Web3Wrapper;
// Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise // Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise
private _lock = new Lock(); private readonly _lock = new Lock();
private _defaultFromAddress: string; private readonly _defaultFromAddress: string;
private _isEnabled = true; private _isEnabled = true;
private _config: TraceCollectionSubproviderConfig; private readonly _config: TraceCollectionSubproviderConfig;
/** /**
* Instantiates a TraceCollectionSubprovider instance * Instantiates a TraceCollectionSubprovider instance
* @param defaultFromAddress default from address to use when sending transactions * @param defaultFromAddress default from address to use when sending transactions

View File

@ -33,11 +33,11 @@ export type SingleFileSubtraceHandler = (
* TraceCollector is used by CoverageSubprovider to compute code coverage based on collected trace data. * TraceCollector is used by CoverageSubprovider to compute code coverage based on collected trace data.
*/ */
export class TraceCollector { export class TraceCollector {
private _artifactAdapter: AbstractArtifactAdapter; private readonly _artifactAdapter: AbstractArtifactAdapter;
private _logger: Logger; private readonly _logger: Logger;
private _contractsData!: ContractData[]; private _contractsData!: ContractData[];
private _collector = new Collector(); private readonly _collector = new Collector();
private _singleFileSubtraceHandler: SingleFileSubtraceHandler; private readonly _singleFileSubtraceHandler: SingleFileSubtraceHandler;
/** /**
* Instantiates a TraceCollector instance * Instantiates a TraceCollector instance

View File

@ -5,7 +5,7 @@ import { ContractSource } from '../types';
import { Resolver } from './resolver'; import { Resolver } from './resolver';
export class FallthroughResolver extends Resolver { export class FallthroughResolver extends Resolver {
private _resolvers: Resolver[] = []; private readonly _resolvers: Resolver[] = [];
public appendResolver(resolver: Resolver): void { public appendResolver(resolver: Resolver): void {
this._resolvers.push(resolver); this._resolvers.push(resolver);
} }

View File

@ -8,7 +8,7 @@ import { EnumerableResolver } from './enumerable_resolver';
const SOLIDITY_FILE_EXTENSION = '.sol'; const SOLIDITY_FILE_EXTENSION = '.sol';
export class NameResolver extends EnumerableResolver { export class NameResolver extends EnumerableResolver {
private _contractsDir: string; private readonly _contractsDir: string;
constructor(contractsDir: string) { constructor(contractsDir: string) {
super(); super();
this._contractsDir = contractsDir; this._contractsDir = contractsDir;

View File

@ -6,7 +6,7 @@ import { ContractSource } from '../types';
import { Resolver } from './resolver'; import { Resolver } from './resolver';
export class NPMResolver extends Resolver { export class NPMResolver extends Resolver {
private _packagePath: string; private readonly _packagePath: string;
constructor(packagePath: string) { constructor(packagePath: string) {
super(); super();
this._packagePath = packagePath; this._packagePath = packagePath;

View File

@ -6,7 +6,7 @@ import { ContractSource } from '../types';
import { Resolver } from './resolver'; import { Resolver } from './resolver';
export class RelativeFSResolver extends Resolver { export class RelativeFSResolver extends Resolver {
private _contractsDir: string; private readonly _contractsDir: string;
constructor(contractsDir: string) { constructor(contractsDir: string) {
super(); super();
this._contractsDir = contractsDir; this._contractsDir = contractsDir;

View File

@ -12,8 +12,8 @@ import { PrivateKeyWalletSubprovider } from './private_key_wallet';
* Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js * Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
*/ */
export class EthLightwalletSubprovider extends BaseWalletSubprovider { export class EthLightwalletSubprovider extends BaseWalletSubprovider {
private _keystore: lightwallet.keystore; private readonly _keystore: lightwallet.keystore;
private _pwDerivedKey: Uint8Array; private readonly _pwDerivedKey: Uint8Array;
constructor(keystore: lightwallet.keystore, pwDerivedKey: Uint8Array) { constructor(keystore: lightwallet.keystore, pwDerivedKey: Uint8Array) {
super(); super();
this._keystore = keystore; this._keystore = keystore;

View File

@ -14,7 +14,7 @@ import { Subprovider } from './subprovider';
* It intercepts the `eth_estimateGas` JSON RPC call and always returns a constant gas amount when queried. * It intercepts the `eth_estimateGas` JSON RPC call and always returns a constant gas amount when queried.
*/ */
export class FakeGasEstimateSubprovider extends Subprovider { export class FakeGasEstimateSubprovider extends Subprovider {
private _constantGasAmount: number; private readonly _constantGasAmount: number;
/** /**
* Instantiates an instance of the FakeGasEstimateSubprovider * Instantiates an instance of the FakeGasEstimateSubprovider
* @param constantGasAmount The constant gas amount you want returned * @param constantGasAmount The constant gas amount you want returned

View File

@ -10,7 +10,7 @@ import { Subprovider } from './subprovider';
* It intercepts all JSON RPC requests and relays them to an in-process ganache instance. * It intercepts all JSON RPC requests and relays them to an in-process ganache instance.
*/ */
export class GanacheSubprovider extends Subprovider { export class GanacheSubprovider extends Subprovider {
private _ganacheProvider: Provider; private readonly _ganacheProvider: Provider;
/** /**
* Instantiates a GanacheSubprovider * Instantiates a GanacheSubprovider
* @param opts The desired opts with which to instantiate the Ganache provider * @param opts The desired opts with which to instantiate the Ganache provider

View File

@ -32,14 +32,14 @@ const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
*/ */
export class LedgerSubprovider extends BaseWalletSubprovider { export class LedgerSubprovider extends BaseWalletSubprovider {
// tslint:disable-next-line:no-unused-variable // tslint:disable-next-line:no-unused-variable
private _nonceLock = new Lock(); private readonly _nonceLock = new Lock();
private _connectionLock = new Lock(); private readonly _connectionLock = new Lock();
private _networkId: number; private readonly _networkId: number;
private _baseDerivationPath: string; private _baseDerivationPath: string;
private _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync; private readonly _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync;
private _ledgerClientIfExists?: LedgerEthereumClient; private _ledgerClientIfExists?: LedgerEthereumClient;
private _shouldAlwaysAskForConfirmation: boolean; private readonly _shouldAlwaysAskForConfirmation: boolean;
private _addressSearchLimit: number; private readonly _addressSearchLimit: number;
/** /**
* Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`. * Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`.
* TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired. * TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired.

View File

@ -20,10 +20,10 @@ const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
* all requests with accounts derived from the supplied mnemonic. * all requests with accounts derived from the supplied mnemonic.
*/ */
export class MnemonicWalletSubprovider extends BaseWalletSubprovider { export class MnemonicWalletSubprovider extends BaseWalletSubprovider {
private _addressSearchLimit: number; private readonly _addressSearchLimit: number;
private _baseDerivationPath: string; private _baseDerivationPath: string;
private _derivedKeyInfo: DerivedHDKeyInfo; private _derivedKeyInfo: DerivedHDKeyInfo;
private _mnemonic: string; private readonly _mnemonic: string;
/** /**
* Instantiates a MnemonicWalletSubprovider. Defaults to baseDerivationPath set to `44'/60'/0'/0`. * Instantiates a MnemonicWalletSubprovider. Defaults to baseDerivationPath set to `44'/60'/0'/0`.

View File

@ -17,7 +17,7 @@ const NONCE_TOO_LOW_ERROR_MESSAGE = 'Transaction nonce is too low';
* We added the additional feature of clearing the cached nonce value when a `nonce value too low` error occurs. * We added the additional feature of clearing the cached nonce value when a `nonce value too low` error occurs.
*/ */
export class NonceTrackerSubprovider extends Subprovider { export class NonceTrackerSubprovider extends Subprovider {
private _nonceCache: { [address: string]: string } = {}; private readonly _nonceCache: { [address: string]: string } = {};
private static _reconstructTransaction(payload: JSONRPCRequestPayload): EthereumTx { private static _reconstructTransaction(payload: JSONRPCRequestPayload): EthereumTx {
const raw = payload.params[0]; const raw = payload.params[0];
if (_.isUndefined(raw)) { if (_.isUndefined(raw)) {

View File

@ -13,8 +13,8 @@ import { BaseWalletSubprovider } from './base_wallet_subprovider';
* all requests with the supplied Ethereum private key. * all requests with the supplied Ethereum private key.
*/ */
export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider { export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider {
private _address: string; private readonly _address: string;
private _privateKeyBuffer: Buffer; private readonly _privateKeyBuffer: Buffer;
/** /**
* Instantiates a PrivateKeyWalletSubprovider. * Instantiates a PrivateKeyWalletSubprovider.
* @param privateKey The corresponding private key to an Ethereum address * @param privateKey The corresponding private key to an Ethereum address

View File

@ -12,7 +12,7 @@ import { Subprovider } from './subprovider';
* set of JSON RPC endpoints. * set of JSON RPC endpoints.
*/ */
export class RedundantSubprovider extends Subprovider { export class RedundantSubprovider extends Subprovider {
private _subproviders: Subprovider[]; private readonly _subproviders: Subprovider[];
private static async _firstSuccessAsync( private static async _firstSuccessAsync(
subproviders: Subprovider[], subproviders: Subprovider[],
payload: JSONRPCRequestPayload, payload: JSONRPCRequestPayload,

View File

@ -13,8 +13,8 @@ import { Subprovider } from './subprovider';
* It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint * It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint
*/ */
export class RPCSubprovider extends Subprovider { export class RPCSubprovider extends Subprovider {
private _rpcUrl: string; private readonly _rpcUrl: string;
private _requestTimeoutMs: number; private readonly _requestTimeoutMs: number;
constructor(rpcUrl: string, requestTimeoutMs: number = 20000) { constructor(rpcUrl: string, requestTimeoutMs: number = 20000) {
super(); super();
assert.isString('rpcUrl', rpcUrl); assert.isString('rpcUrl', rpcUrl);

View File

@ -12,7 +12,7 @@ import { Subprovider } from './subprovider';
* are passed onwards for subsequent subproviders to handle. * are passed onwards for subsequent subproviders to handle.
*/ */
export class SignerSubprovider extends Subprovider { export class SignerSubprovider extends Subprovider {
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
/** /**
* Instantiates a new SignerSubprovider * Instantiates a new SignerSubprovider
* @param provider Web3 provider that should handle all user account related requests * @param provider Web3 provider that should handle all user account related requests

View File

@ -6,8 +6,8 @@ import { DerivedHDKeyInfo } from '../types';
const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
class DerivedHDKeyInfoIterator implements IterableIterator<DerivedHDKeyInfo> { class DerivedHDKeyInfoIterator implements IterableIterator<DerivedHDKeyInfo> {
private _parentDerivedKeyInfo: DerivedHDKeyInfo; private readonly _parentDerivedKeyInfo: DerivedHDKeyInfo;
private _searchLimit: number; private readonly _searchLimit: number;
private _index: number; private _index: number;
constructor(initialDerivedKey: DerivedHDKeyInfo, searchLimit: number = DEFAULT_ADDRESS_SEARCH_LIMIT) { constructor(initialDerivedKey: DerivedHDKeyInfo, searchLimit: number = DEFAULT_ADDRESS_SEARCH_LIMIT) {

View File

@ -176,7 +176,7 @@ describe('LedgerSubprovider', () => {
params: [tx], params: [tx],
id: 1, id: 1,
}; };
await promisify(defaultProvider.sendAsync, defaultProvider)(payload); await promisify(defaultProvider.sendAsync.bind(defaultProvider))(payload);
// Send transaction from Ledger // Send transaction from Ledger
tx = { tx = {

View File

@ -55,7 +55,7 @@ describe('LedgerSubprovider', () => {
return ecSignature; return ecSignature;
}, },
transport: { transport: {
close: _.noop, close: _.noop.bind(_),
} as LedgerCommunicationClient, } as LedgerCommunicationClient,
}; };
// tslint:enable:no-object-literal-type-assertion // tslint:enable:no-object-literal-type-assertion

View File

@ -60,9 +60,9 @@ describe('NonceTrackerSubprovider', () => {
const payload = { ...getTransactionCountPayload, params: ['0x0', 'pending'] }; const payload = { ...getTransactionCountPayload, params: ['0x0', 'pending'] };
const response = await promisify<any>(provider.sendAsync, provider)(payload); const response = await promisify<any>(provider.sendAsync.bind(provider))(payload);
expect(response.result).to.be.eq('0x00'); expect(response.result).to.be.eq('0x00');
const secondResponse = await promisify<any>(provider.sendAsync, provider)(payload); const secondResponse = await promisify<any>(provider.sendAsync.bind(provider))(payload);
expect(secondResponse.result).to.be.eq('0x00'); expect(secondResponse.result).to.be.eq('0x00');
}); });
it('does not cache the result for latest transaction count', async () => { it('does not cache the result for latest transaction count', async () => {
@ -74,9 +74,9 @@ describe('NonceTrackerSubprovider', () => {
const payload = { ...getTransactionCountPayload, params: ['0x0', 'latest'] }; const payload = { ...getTransactionCountPayload, params: ['0x0', 'latest'] };
const response = await promisify<any>(provider.sendAsync, provider)(payload); const response = await promisify<any>(provider.sendAsync.bind(provider))(payload);
expect(response.result).to.be.eq('0x00'); expect(response.result).to.be.eq('0x00');
const secondResponse = await promisify<any>(provider.sendAsync, provider)(payload); const secondResponse = await promisify<any>(provider.sendAsync.bind(provider))(payload);
expect(secondResponse.result).to.be.eq('0x99'); expect(secondResponse.result).to.be.eq('0x99');
}); });
it('clears the cache on a Nonce Too Low Error', async () => { it('clears the cache on a Nonce Too Low Error', async () => {
@ -103,14 +103,14 @@ describe('NonceTrackerSubprovider', () => {
params: [transaction.serialize()], params: [transaction.serialize()],
}; };
const response = await promisify<any>(provider.sendAsync, provider)(noncePayload); const response = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(response.result).to.be.eq('0x00'); expect(response.result).to.be.eq('0x00');
const secondResponse = await promisify<any>(provider.sendAsync, provider)(noncePayload); const secondResponse = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(secondResponse.result).to.be.eq('0x00'); expect(secondResponse.result).to.be.eq('0x00');
try { try {
await promisify(provider.sendAsync, provider)(txPayload); await promisify(provider.sendAsync.bind(provider))(txPayload);
} catch (err) { } catch (err) {
const thirdResponse = await promisify<any>(provider.sendAsync, provider)(noncePayload); const thirdResponse = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(thirdResponse.result).to.be.eq('0x99'); expect(thirdResponse.result).to.be.eq('0x99');
} }
}); });
@ -138,12 +138,12 @@ describe('NonceTrackerSubprovider', () => {
params: [transaction.serialize()], params: [transaction.serialize()],
}; };
const response = await promisify<any>(provider.sendAsync, provider)(noncePayload); const response = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(response.result).to.be.eq('0x00'); expect(response.result).to.be.eq('0x00');
const secondResponse = await promisify<any>(provider.sendAsync, provider)(noncePayload); const secondResponse = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(secondResponse.result).to.be.eq('0x00'); expect(secondResponse.result).to.be.eq('0x00');
await promisify(provider.sendAsync, provider)(txPayload); await promisify(provider.sendAsync.bind(provider))(txPayload);
const thirdResponse = await promisify<any>(provider.sendAsync, provider)(noncePayload); const thirdResponse = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(thirdResponse.result).to.be.eq('0x01'); expect(thirdResponse.result).to.be.eq('0x01');
}); });
}); });

View File

@ -7,8 +7,8 @@ const MAX_QUEUE_SIZE = 500;
const DEFAULT_QUEUE_INTERVAL_MS = 1000; const DEFAULT_QUEUE_INTERVAL_MS = 1000;
export class DispatchQueue { export class DispatchQueue {
private _queueIntervalMs: number; private readonly _queueIntervalMs: number;
private _queue: Array<() => Promise<void>>; private readonly _queue: Array<() => Promise<void>>;
private _queueIntervalIdIfExists?: NodeJS.Timer; private _queueIntervalIdIfExists?: NodeJS.Timer;
constructor() { constructor() {
this._queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS; this._queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS;

View File

@ -12,7 +12,7 @@ export const errorReporter = {
rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY); rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY);
process.on('unhandledRejection', async (err: Error) => { process.on('unhandledRejection', async (err: Error) => {
logUtils.log(`Uncaught exception ${err}. Stack: ${err.stack}`); logUtils.log(`Uncaught exception ${err}. Stack: ${err.stack}`);
await this.reportAsync(err); await errorReporter.reportAsync(err);
process.exit(1); process.exit(1);
}); });
}, },
@ -20,7 +20,7 @@ export const errorReporter = {
if (configs.ENVIRONMENT === 'development') { if (configs.ENVIRONMENT === 'development') {
return; // Do not log development environment errors return; // Do not log development environment errors
} }
return new Promise((resolve, reject) => { return new Promise<any>((resolve, reject) => {
rollbar.handleError(err, req, (rollbarErr: Error) => { rollbar.handleError(err, req, (rollbarErr: Error) => {
if (rollbarErr) { if (rollbarErr) {
logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`); logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`);

View File

@ -37,7 +37,7 @@ enum RequestedAssetType {
const FIVE_DAYS_IN_MS = 4.32e8; // TODO: make this configurable const FIVE_DAYS_IN_MS = 4.32e8; // TODO: make this configurable
export class Handler { export class Handler {
private _networkConfigByNetworkId: ItemByNetworkId<NetworkConfig> = {}; private readonly _networkConfigByNetworkId: ItemByNetworkId<NetworkConfig> = {};
private static _createProviderEngine(rpcUrl: string): Provider { private static _createProviderEngine(rpcUrl: string): Provider {
if (_.isUndefined(configs.DISPENSER_PRIVATE_KEY)) { if (_.isUndefined(configs.DISPENSER_PRIVATE_KEY)) {
throw new Error('Dispenser Private key not found'); throw new Error('Dispenser Private key not found');

View File

@ -24,10 +24,26 @@ app.get('/ping', (req: express.Request, res: express.Response) => {
res.status(constants.SUCCESS_STATUS).send('pong'); res.status(constants.SUCCESS_STATUS).send('pong');
}); });
app.get('/info', handler.getQueueInfo.bind(handler)); app.get('/info', handler.getQueueInfo.bind(handler));
app.get('/ether/:recipient', parameterTransformer.transform, handler.dispenseEther.bind(handler)); app.get(
app.get('/zrx/:recipient', parameterTransformer.transform, handler.dispenseZRX.bind(handler)); '/ether/:recipient',
app.get('/order/weth/:recipient', parameterTransformer.transform, handler.dispenseWETHOrderAsync.bind(handler)); parameterTransformer.transform.bind(parameterTransformer),
app.get('/order/zrx/:recipient', parameterTransformer.transform, handler.dispenseZRXOrderAsync.bind(handler)); handler.dispenseEther.bind(handler),
);
app.get(
'/zrx/:recipient',
parameterTransformer.transform.bind(parameterTransformer),
handler.dispenseZRX.bind(handler),
);
app.get(
'/order/weth/:recipient',
parameterTransformer.transform.bind(parameterTransformer),
handler.dispenseWETHOrderAsync.bind(handler),
);
app.get(
'/order/zrx/:recipient',
parameterTransformer.transform.bind(parameterTransformer),
handler.dispenseZRXOrderAsync.bind(handler),
);
// Log to rollbar any errors unhandled by handlers // Log to rollbar any errors unhandled by handlers
app.use(errorReporter.errorHandler()); app.use(errorReporter.errorHandler());

View File

@ -29,6 +29,7 @@ export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED; const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED;
return this.applyWithWalker( return this.applyWithWalker(
// tslint:disable-next-line:no-inferred-empty-object-type
new CustomNoMagicNumbersWalker(sourceFile, this.ruleName, new Set(allowedNumbers.map(String))), new CustomNoMagicNumbersWalker(sourceFile, this.ruleName, new Set(allowedNumbers.map(String))),
); );
} }

View File

@ -16,7 +16,7 @@ import { addressUtils } from './address_utils';
import { BigNumber } from './configured_bignumber'; import { BigNumber } from './configured_bignumber';
export class AbiDecoder { export class AbiDecoder {
private _methodIds: { [signatureHash: string]: EventAbi } = {}; private readonly _methodIds: { [signatureHash: string]: EventAbi } = {};
constructor(abiArrays: AbiDefinition[][]) { constructor(abiArrays: AbiDefinition[][]) {
_.forEach(abiArrays, this.addABI.bind(this)); _.forEach(abiArrays, this.addABI.bind(this));
} }

View File

@ -6,7 +6,7 @@ export const abiUtils = {
if (param.type === 'tuple') { if (param.type === 'tuple') {
// Parse out tuple types into {type_1, type_2, ..., type_N} // Parse out tuple types into {type_1, type_2, ..., type_N}
const tupleComponents = param.components; const tupleComponents = param.components;
const paramString = _.map(tupleComponents, component => this.parseFunctionParam(component)); const paramString = _.map(tupleComponents, component => abiUtils.parseFunctionParam(component));
const tupleParamString = `{${paramString}}`; const tupleParamString = `{${paramString}}`;
return tupleParamString; return tupleParamString;
} }
@ -14,7 +14,7 @@ export const abiUtils = {
}, },
getFunctionSignature(methodAbi: MethodAbi): string { getFunctionSignature(methodAbi: MethodAbi): string {
const functionName = methodAbi.name; const functionName = methodAbi.name;
const parameterTypeList = _.map(methodAbi.inputs, (param: DataItem) => this.parseFunctionParam(param)); const parameterTypeList = _.map(methodAbi.inputs, (param: DataItem) => abiUtils.parseFunctionParam(param));
const functionSignature = `${functionName}(${parameterTypeList})`; const functionSignature = `${functionName}(${parameterTypeList})`;
return functionSignature; return functionSignature;
}, },
@ -37,7 +37,7 @@ export const abiUtils = {
// Sort method Abis into alphabetical order, by function signature // Sort method Abis into alphabetical order, by function signature
const methodAbisOrdered = _.sortBy(methodAbis, [ const methodAbisOrdered = _.sortBy(methodAbis, [
(methodAbi: MethodAbi) => { (methodAbi: MethodAbi) => {
const functionSignature = this.getFunctionSignature(methodAbi); const functionSignature = abiUtils.getFunctionSignature(methodAbi);
return functionSignature; return functionSignature;
}, },
]); ]);

View File

@ -54,7 +54,7 @@ export const marshaller = {
transactions: [] as Transaction[], transactions: [] as Transaction[],
}; };
block.transactions = _.map(blockWithHexValues.transactions, (tx: TransactionRPC) => { block.transactions = _.map(blockWithHexValues.transactions, (tx: TransactionRPC) => {
const transaction = this.unmarshalTransaction(tx); const transaction = marshaller.unmarshalTransaction(tx);
return transaction; return transaction;
}); });
return block; return block;
@ -94,10 +94,10 @@ export const marshaller = {
...txData, ...txData,
}; };
delete callTxDataBase.from; delete callTxDataBase.from;
const callTxDataBaseRPC = this._marshalCallTxDataBase(callTxDataBase); const callTxDataBaseRPC = marshaller._marshalCallTxDataBase(callTxDataBase);
const txDataRPC = { const txDataRPC = {
...callTxDataBaseRPC, ...callTxDataBaseRPC,
from: this.marshalAddress(txData.from), from: marshaller.marshalAddress(txData.from),
}; };
const prunableIfUndefined = ['gasPrice', 'gas', 'value', 'nonce']; const prunableIfUndefined = ['gasPrice', 'gas', 'value', 'nonce'];
_.each(txDataRPC, (value: any, key: string) => { _.each(txDataRPC, (value: any, key: string) => {
@ -112,10 +112,10 @@ export const marshaller = {
...callData, ...callData,
}; };
delete callTxDataBase.from; delete callTxDataBase.from;
const callTxDataBaseRPC = this._marshalCallTxDataBase(callTxDataBase); const callTxDataBaseRPC = marshaller._marshalCallTxDataBase(callTxDataBase);
const callDataRPC = { const callDataRPC = {
...callTxDataBaseRPC, ...callTxDataBaseRPC,
from: _.isUndefined(callData.from) ? undefined : this.marshalAddress(callData.from), from: _.isUndefined(callData.from) ? undefined : marshaller.marshalAddress(callData.from),
}; };
return callDataRPC; return callDataRPC;
}, },
@ -144,7 +144,7 @@ export const marshaller = {
_marshalCallTxDataBase(callTxDataBase: Partial<CallTxDataBase>): Partial<CallTxDataBaseRPC> { _marshalCallTxDataBase(callTxDataBase: Partial<CallTxDataBase>): Partial<CallTxDataBaseRPC> {
const callTxDataBaseRPC = { const callTxDataBaseRPC = {
...callTxDataBase, ...callTxDataBase,
to: _.isUndefined(callTxDataBase.to) ? undefined : this.marshalAddress(callTxDataBase.to), to: _.isUndefined(callTxDataBase.to) ? undefined : marshaller.marshalAddress(callTxDataBase.to),
gasPrice: _.isUndefined(callTxDataBase.gasPrice) gasPrice: _.isUndefined(callTxDataBase.gasPrice)
? undefined ? undefined
: utils.encodeAmountAsHexString(callTxDataBase.gasPrice), : utils.encodeAmountAsHexString(callTxDataBase.gasPrice),

View File

@ -15,7 +15,7 @@ export const utils = {
if (_.isNull(hex)) { if (_.isNull(hex)) {
return null; return null;
} }
const decimal = this.convertHexToNumber(hex); const decimal = utils.convertHexToNumber(hex);
return decimal; return decimal;
}, },
convertAmountToBigNumber(value: string | number | BigNumber): BigNumber { convertAmountToBigNumber(value: string | number | BigNumber): BigNumber {
@ -40,7 +40,7 @@ export const utils = {
return valueBigNumber.lessThan(0) ? '-0x' + valueHex.substr(1) : '0x' + valueHex; return valueBigNumber.lessThan(0) ? '-0x' + valueHex.substr(1) : '0x' + valueHex;
}, },
numberToHex(value: number): string { numberToHex(value: number): string {
if (!isFinite(value) && !this.isHexStrict(value)) { if (!isFinite(value) && !utils.isHexStrict(value)) {
throw new Error(`Given input ${value} is not a number.`); throw new Error(`Given input ${value} is not a number.`);
} }

View File

@ -50,7 +50,7 @@ export class Web3Wrapper {
public isZeroExWeb3Wrapper = true; public isZeroExWeb3Wrapper = true;
public abiDecoder: AbiDecoder; public abiDecoder: AbiDecoder;
private _provider: Provider; private _provider: Provider;
private _txDefaults: Partial<TxData>; private readonly _txDefaults: Partial<TxData>;
private _jsonRpcRequestId: number; private _jsonRpcRequestId: number;
/** /**
* Check if an address is a valid Ethereum address * Check if an address is a valid Ethereum address

View File

@ -83,11 +83,11 @@ export class Blockchain {
public networkId: number; public networkId: number;
public nodeVersion: string; public nodeVersion: string;
private _contractWrappers: ContractWrappers; private _contractWrappers: ContractWrappers;
private _dispatcher: Dispatcher; private readonly _dispatcher: Dispatcher;
private _web3Wrapper?: Web3Wrapper; private _web3Wrapper?: Web3Wrapper;
private _blockchainWatcher?: BlockchainWatcher; private _blockchainWatcher?: BlockchainWatcher;
private _injectedProviderObservable?: InjectedProviderObservable; private _injectedProviderObservable?: InjectedProviderObservable;
private _injectedProviderUpdateHandler: (update: InjectedProviderUpdate) => Promise<void>; private readonly _injectedProviderUpdateHandler: (update: InjectedProviderUpdate) => Promise<void>;
private _userAddressIfExists: string; private _userAddressIfExists: string;
private _ledgerSubprovider: LedgerSubprovider; private _ledgerSubprovider: LedgerSubprovider;
private _defaultGasPrice: BigNumber; private _defaultGasPrice: BigNumber;
@ -125,7 +125,11 @@ export class Blockchain {
let networkIdIfExists: number; let networkIdIfExists: number;
if (!_.isUndefined(injectedWeb3IfExists)) { if (!_.isUndefined(injectedWeb3IfExists)) {
try { try {
networkIdIfExists = _.parseInt(await promisify<string>(injectedWeb3IfExists.version.getNetwork)()); networkIdIfExists = _.parseInt(
await promisify<string>(
injectedWeb3IfExists.version.getNetwork.bind(injectedWeb3IfExists.version),
)(),
);
} catch (err) { } catch (err) {
// Ignore error and proceed with networkId undefined // Ignore error and proceed with networkId undefined
} }

View File

@ -4,9 +4,9 @@ import * as _ from 'lodash';
import { Dispatcher } from 'ts/redux/dispatcher'; import { Dispatcher } from 'ts/redux/dispatcher';
export class BlockchainWatcher { export class BlockchainWatcher {
private _dispatcher: Dispatcher; private readonly _dispatcher: Dispatcher;
private _web3Wrapper: Web3Wrapper; private readonly _web3Wrapper: Web3Wrapper;
private _shouldPollUserAddress: boolean; private readonly _shouldPollUserAddress: boolean;
private _watchBalanceIntervalId: NodeJS.Timer; private _watchBalanceIntervalId: NodeJS.Timer;
private _prevUserEtherBalanceInWei?: BigNumber; private _prevUserEtherBalanceInWei?: BigNumber;
private _prevUserAddressIfExists: string; private _prevUserAddressIfExists: string;

View File

@ -14,9 +14,9 @@ export const U2fNotSupportedDialog = (props: U2fNotSupportedDialogProps) => {
<Dialog <Dialog
title="U2F Not Supported" title="U2F Not Supported"
titleStyle={{ fontWeight: 100 }} titleStyle={{ fontWeight: 100 }}
actions={[<FlatButton key="u2fNo" label="Ok" onTouchTap={props.onToggleDialog.bind(this)} />]} actions={[<FlatButton key="u2fNo" label="Ok" onTouchTap={props.onToggleDialog} />]}
open={props.isOpen} open={props.isOpen}
onRequestClose={props.onToggleDialog.bind(this)} onRequestClose={props.onToggleDialog}
autoScrollBodyContent={true} autoScrollBodyContent={true}
> >
<div className="pt2" style={{ color: colors.grey700 }}> <div className="pt2" style={{ color: colors.grey700 }}>

View File

@ -37,7 +37,7 @@ export class EthWethConversionButton extends React.Component<
> { > {
public static defaultProps: Partial<EthWethConversionButtonProps> = { public static defaultProps: Partial<EthWethConversionButtonProps> = {
isDisabled: false, isDisabled: false,
onConversionSuccessful: _.noop, onConversionSuccessful: _.noop.bind(_),
}; };
public constructor(props: EthWethConversionButtonProps) { public constructor(props: EthWethConversionButtonProps) {
super(props); super(props);

View File

@ -18,16 +18,16 @@ export const FillWarningDialog = (props: FillWarningDialogProps) => {
<FlatButton <FlatButton
key="fillWarningCancel" key="fillWarningCancel"
label="Cancel" label="Cancel"
onTouchTap={props.onToggleDialog.bind(this, didCancel)} onTouchTap={() => props.onToggleDialog(didCancel)} // tslint:disable-line:jsx-no-lambda
/>, />,
<FlatButton <FlatButton
key="fillWarningContinue" key="fillWarningContinue"
label="Fill Order" label="Fill Order"
onTouchTap={props.onToggleDialog.bind(this, !didCancel)} onTouchTap={() => props.onToggleDialog(!didCancel)} // tslint:disable-line:jsx-no-lambda
/>, />,
]} ]}
open={props.isOpen} open={props.isOpen}
onRequestClose={props.onToggleDialog.bind(this)} onRequestClose={() => props.onToggleDialog(didCancel)} // tslint:disable-line:jsx-no-lambda
autoScrollBodyContent={true} autoScrollBodyContent={true}
modal={true} modal={true}
> >

View File

@ -46,7 +46,7 @@ export class AssetPicker extends React.Component<AssetPickerProps, AssetPickerSt
public static defaultProps: Partial<AssetPickerProps> = { public static defaultProps: Partial<AssetPickerProps> = {
tokenVisibility: TokenVisibility.ALL, tokenVisibility: TokenVisibility.ALL,
}; };
private _dialogConfigsByAssetView: { [assetView: string]: DialogConfigs }; private readonly _dialogConfigsByAssetView: { [assetView: string]: DialogConfigs };
constructor(props: AssetPickerProps) { constructor(props: AssetPickerProps) {
super(props); super(props);
this.state = { this.state = {

View File

@ -57,7 +57,7 @@ const styles: Styles = {
export class AllowanceToggle extends React.Component<AllowanceToggleProps, AllowanceToggleState> { export class AllowanceToggle extends React.Component<AllowanceToggleProps, AllowanceToggleState> {
public static defaultProps = { public static defaultProps = {
onErrorOccurred: _.noop, onErrorOccurred: _.noop.bind(_),
isDisabled: false, isDisabled: false,
}; };
constructor(props: AllowanceToggleProps) { constructor(props: AllowanceToggleProps) {

View File

@ -35,7 +35,7 @@ export class BalanceBoundedInput extends React.Component<BalanceBoundedInputProp
isDisabled: false, isDisabled: false,
shouldShowErrs: true, shouldShowErrs: true,
hintText: 'amount', hintText: 'amount',
onErrorMsgChange: _.noop, onErrorMsgChange: _.noop.bind(_),
shouldShowUnderline: true, shouldShowUnderline: true,
}; };
constructor(props: BalanceBoundedInputProps) { constructor(props: BalanceBoundedInputProps) {
@ -125,7 +125,7 @@ export class BalanceBoundedInput extends React.Component<BalanceBoundedInputProp
const errMsg = _.isUndefined(this.props.validate) ? undefined : this.props.validate(amount); const errMsg = _.isUndefined(this.props.validate) ? undefined : this.props.validate(amount);
return errMsg; return errMsg;
} }
private _setAmountState(amount: string, balance: BigNumber, callback: () => void = _.noop): void { private _setAmountState(amount: string, balance: BigNumber, callback: () => void = _.noop.bind(_)): void {
const errorMsg = this._validate(amount, balance); const errorMsg = this._validate(amount, balance);
this.props.onErrorMsgChange(errorMsg); this.props.onErrorMsgChange(errorMsg);
this.setState( this.setState(

View File

@ -17,7 +17,7 @@ interface ExpirationInputState {
} }
export class ExpirationInput extends React.Component<ExpirationInputProps, ExpirationInputState> { export class ExpirationInput extends React.Component<ExpirationInputProps, ExpirationInputState> {
private _earliestPickableMoment: moment.Moment; private readonly _earliestPickableMoment: moment.Moment;
constructor(props: ExpirationInputProps) { constructor(props: ExpirationInputProps) {
super(props); super(props);
// Set the earliest pickable date to today at 00:00, so users can only pick the current or later dates // Set the earliest pickable date to today at 00:00, so users can only pick the current or later dates

View File

@ -127,7 +127,7 @@ export class OrderJSON extends React.Component<OrderJSONProps, OrderJSONState> {
href: this.state.shareLink, href: this.state.shareLink,
method: 'share', method: 'share',
}, },
_.noop, _.noop.bind(_),
); );
} }
private _shareViaEmailAsync(): void { private _shareViaEmailAsync(): void {

Some files were not shown because too many files have changed in this diff Show More