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.
*/
public erc721Proxy: ERC721ProxyWrapper;
private _contractWrappers: ContractWrappers;
private readonly _contractWrappers: ContractWrappers;
/**
* Generates a pseudo-random 256-bit salt.
* 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
// we manually increase it for this before hook.
const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs);
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = {
gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS,

View File

@ -8,33 +8,33 @@ const HEX_REGEX = /^0x[0-9A-F]*$/i;
export const assert = {
isBigNumber(variableName: string, value: BigNumber): void {
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 {
assert.isBigNumber(variableName, value);
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;
this.assert(
assert.assert(
!hasDecimals,
`${variableName} should be in baseUnits (no decimals), found value: ${value.toNumber()}`,
);
},
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 {
this.assert(_.isFunction(value), this.typeAssertionMessage(variableName, 'function', value));
assert.assert(_.isFunction(value), assert.typeAssertionMessage(variableName, 'function', value));
},
isHexString(variableName: string, value: string): void {
this.assert(
assert.assert(
_.isString(value) && HEX_REGEX.test(value),
this.typeAssertionMessage(variableName, 'HexString', value),
assert.typeAssertionMessage(variableName, 'HexString', value),
);
},
isETHAddressHex(variableName: string, value: string): void {
this.assert(_.isString(value), this.typeAssertionMessage(variableName, 'string', value));
this.assert(addressUtils.isAddress(value), this.typeAssertionMessage(variableName, 'ETHAddressHex', value));
assert.assert(_.isString(value), assert.typeAssertionMessage(variableName, 'string', value));
assert.assert(addressUtils.isAddress(value), assert.typeAssertionMessage(variableName, 'ETHAddressHex', value));
},
doesBelongToStringEnum(
variableName: string,
@ -51,17 +51,17 @@ export const assert = {
);
},
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 {
this.assert(_.isFinite(value), this.typeAssertionMessage(variableName, 'number', value));
assert.assert(_.isFinite(value), assert.typeAssertionMessage(variableName, 'number', value));
},
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 {
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 {
if (_.isUndefined(value)) {
@ -76,15 +76,15 @@ export const assert = {
const msg = `Expected ${variableName} to conform to schema ${schema.id}
Encountered: ${JSON.stringify(value, null, '\t')}
Validation errors: ${validationResult.errors.join(', ')}`;
this.assert(!hasValidationErrors, msg);
assert.assert(!hasValidationErrors, msg);
},
isWebUri(variableName: string, value: any): void {
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 {
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 {
if (!condition) {

View File

@ -49,7 +49,7 @@ describe('Assertions', () => {
});
describe('#isFunction', () => {
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());
});
it('should throw for invalid input', () => {

View File

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

View File

@ -38,7 +38,7 @@ const OPTS_TO_QUERY_FIELD_MAP = {
* that implement the standard relayer API v0
*/
export class HttpClient implements Client {
private _apiEndpointUrl: string;
private readonly _apiEndpointUrl: string;
/**
* 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 asks = _.get(orderbook, 'asks', []);
return {
bids: bids.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)),
asks: asks.map((order: any) => this.convertOrderStringFieldsToBigNumber(order)),
bids: bids.map((order: any) => typeConverters.convertOrderStringFieldsToBigNumber(order)),
asks: asks.map((order: any) => typeConverters.convertOrderStringFieldsToBigNumber(order)),
};
},
convertOrderStringFieldsToBigNumber(order: any): any {
return this.convertStringsFieldsToBigNumbers(order, [
return typeConverters.convertStringsFieldsToBigNumbers(order, [
'makerTokenAmount',
'takerTokenAmount',
'makerFee',

View File

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

View File

@ -29,7 +29,7 @@ describe('WebSocketOrderbookChannel', () => {
const websocketUrl = 'ws://localhost:8080';
const openClient = new WebSocket.w3cwebsocket(websocketUrl);
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 subscriptionOpts = {
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
// we manually increase it for this before hook.
const mochaTestTimeoutMs = 50000;
this.timeout(mochaTestTimeoutMs);
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = {
gas: devConstants.GAS_LIMIT,
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.
*/
export class AssetWrapper {
private _proxyIdToAssetWrappers: ProxyIdToAssetWrappers;
private readonly _proxyIdToAssetWrappers: ProxyIdToAssetWrappers;
constructor(assetWrappers: AbstractAssetWrapper[]) {
this._proxyIdToAssetWrappers = {};
_.each(assetWrappers, assetWrapper => {

View File

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

View File

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

View File

@ -11,9 +11,9 @@ import { orderUtils } from './order_utils';
import { OrderInfo, SignedTransaction } from './types';
export class ExchangeWrapper {
private _exchange: ExchangeContract;
private _web3Wrapper: Web3Wrapper;
private _logDecoder: LogDecoder;
private readonly _exchange: ExchangeContract;
private readonly _web3Wrapper: Web3Wrapper;
private readonly _logDecoder: LogDecoder;
constructor(exchangeContract: ExchangeContract, provider: Provider) {
this._exchange = exchangeContract;
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';
export class ForwarderWrapper {
private _web3Wrapper: Web3Wrapper;
private _forwarderContract: ForwarderContract;
private _logDecoder: LogDecoder;
private _zrxAddress: string;
private readonly _web3Wrapper: Web3Wrapper;
private readonly _forwarderContract: ForwarderContract;
private readonly _logDecoder: LogDecoder;
private readonly _zrxAddress: string;
private static _createOptimizedSellOrders(signedOrders: SignedOrder[]): MarketSellOrders {
const marketSellOrders = formatters.createMarketSellOrders(signedOrders, ZERO_AMOUNT);
const assetDataId = assetProxyUtils.decodeAssetDataId(signedOrders[0].makerAssetData);

View File

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

View File

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

View File

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

View File

@ -6,8 +6,8 @@ import { constants } from './constants';
import { signingUtils } from './signing_utils';
export class OrderFactory {
private _defaultOrderParams: Partial<Order>;
private _privateKey: Buffer;
private readonly _defaultOrderParams: Partial<Order>;
private readonly _privateKey: Buffer;
constructor(privateKey: Buffer, defaultOrderParams: Partial<Order>) {
this._defaultOrderParams = defaultOrderParams;
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);
export class OrderFactoryFromScenario {
private _userAddresses: string[];
private _zrxAddress: string;
private _nonZrxERC20EighteenDecimalTokenAddresses: string[];
private _erc20FiveDecimalTokenAddresses: string[];
private _erc721Token: DummyERC721TokenContract;
private _erc721Balances: ERC721TokenIdsByOwner;
private _exchangeAddress: string;
private readonly _userAddresses: string[];
private readonly _zrxAddress: string;
private readonly _nonZrxERC20EighteenDecimalTokenAddresses: string[];
private readonly _erc20FiveDecimalTokenAddresses: string[];
private readonly _erc721Token: DummyERC721TokenContract;
private readonly _erc721Balances: ERC721TokenIdsByOwner;
private readonly _exchangeAddress: string;
constructor(
userAddresses: string[],
zrxAddress: string,

View File

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

View File

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

View File

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

View File

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

View File

@ -51,8 +51,10 @@ export const provider = web3Factory.getRpcProvider(providerConfigs);
const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage);
const isProfilerEnabled = env.parseBoolean(EnvVars.SolidityProfiler);
const isRevertTraceEnabled = env.parseBoolean(EnvVars.SolidityRevertTrace);
const enabledSubproviderCount = _.filter([isCoverageEnabled, isProfilerEnabled, isRevertTraceEnabled], _.identity)
.length;
const enabledSubproviderCount = _.filter(
[isCoverageEnabled, isProfilerEnabled, isRevertTraceEnabled],
_.identity.bind(_),
).length;
if (enabledSubproviderCount > 1) {
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;
export class BlockchainLifecycle {
private _web3Wrapper: Web3Wrapper;
private _snapshotIdsStack: number[];
private readonly _web3Wrapper: Web3Wrapper;
private readonly _snapshotIdsStack: number[];
private _addresses: string[] = [];
private _nodeType: NodeType | undefined;
constructor(web3Wrapper: Web3Wrapper) {

View File

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

View File

@ -7,7 +7,7 @@ import { schemas } from './schemas';
* A validator for [JSON-schemas](http://json-schema.org/)
*/
export class SchemaValidator {
private _validator: Validator;
private readonly _validator: Validator;
/**
* 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';
export class ArtifactWriter {
private _artifactsDir: string;
private _networkId: number;
private readonly _artifactsDir: string;
private readonly _networkId: number;
constructor(artifactsDir: string, networkId: number) {
this._artifactsDir = artifactsDir;
this._networkId = networkId;

View File

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

View File

@ -10,7 +10,7 @@ import { Change, Changelog, VersionChangelog } from '../types';
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.
-->
@ -74,7 +74,7 @@ export const changelogUtils = {
},
getChangelogOrCreateIfMissing(packageName: string, packageLocation: string): Changelog {
const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json');
let changelogJsonIfExists = this.getChangelogJSONIfExists(changelogJSONPath);
let changelogJsonIfExists = changelogUtils.getChangelogJSONIfExists(changelogJSONPath);
if (_.isUndefined(changelogJsonIfExists)) {
// If none exists, create new, empty one.
changelogJsonIfExists = '[]';
@ -91,12 +91,12 @@ export const changelogUtils = {
async writeChangelogJsonFileAsync(packageLocation: string, changelog: Changelog): Promise<void> {
const changelogJSONPath = path.join(packageLocation, 'CHANGELOG.json');
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> {
const changelogMarkdownPath = path.join(packageLocation, 'CHANGELOG.md');
fs.writeFileSync(changelogMarkdownPath, changelogMdString);
await this.prettifyAsync(changelogMarkdownPath, constants.monorepoRootPath);
await changelogUtils.prettifyAsync(changelogMarkdownPath, constants.monorepoRootPath);
},
async prettifyAsync(filePath: string, cwd: string): Promise<void> {
await execAsync(`prettier --write ${filePath} --config .prettierrc`, {

View File

@ -13,7 +13,7 @@ export const utils = {
console.log(...args); // tslint:disable-line:no-console
},
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 allLernaPackages = lernaGetPackages(constants.monorepoRootPath);
@ -110,7 +110,7 @@ export const utils = {
} catch (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> {
try {
@ -120,6 +120,6 @@ export const utils = {
} catch (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 {
private _store: AbstractBalanceAndProxyAllowanceLazyStore;
private readonly _store: AbstractBalanceAndProxyAllowanceLazyStore;
private static _throwValidationError(
failureReason: FailureReason,
tradeSide: TradeSide,

View File

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

View File

@ -13,7 +13,7 @@ import { isValidSignatureAsync } from './signature_utils';
import { utils } from './utils';
export class OrderValidationUtils {
private _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher;
private readonly _orderFilledCancelledFetcher: AbstractOrderFilledCancelledFetcher;
public static isRoundingError(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean {
// Solidity's mulmod() in JS
// 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';
export class RemainingFillableCalculator {
private _isTraderAssetZRX: boolean;
private readonly _isTraderAssetZRX: boolean;
// Transferrable Amount is the minimum of Approval and Balance
private _transferrableAssetAmount: BigNumber;
private _transferrableFeeAmount: BigNumber;
private _remainingOrderAssetAmount: BigNumber;
private _remainingOrderFeeAmount: BigNumber;
private _orderFee: BigNumber;
private _orderAssetAmount: BigNumber;
private readonly _transferrableAssetAmount: BigNumber;
private readonly _transferrableFeeAmount: BigNumber;
private readonly _remainingOrderAssetAmount: BigNumber;
private readonly _remainingOrderFeeAmount: BigNumber;
private readonly _orderFee: BigNumber;
private readonly _orderAssetAmount: BigNumber;
constructor(
orderFee: BigNumber,
orderAssetAmount: BigNumber,

View File

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

View File

@ -34,7 +34,7 @@ describe('ExchangeTransferSimulator', async () => {
let erc20ProxyAddress: string;
before(async function(): Promise<void> {
const mochaTestTimeoutMs = 20000;
this.timeout(mochaTestTimeoutMs);
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
userAddresses = await web3Wrapper.getAvailableAddressesAsync();
[coinbase, sender, recipient] = userAddresses;
@ -77,8 +77,7 @@ describe('ExchangeTransferSimulator', async () => {
describe('#transferFromAsync', function(): void {
// HACK: For some reason these tests need a slightly longer timeout
const mochaTestTimeoutMs = 3000;
this.timeout(mochaTestTimeoutMs);
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
beforeEach(() => {
const simpleERC20BalanceAndProxyAllowanceFetcher = new SimpleERC20BalanceAndProxyAllowanceFetcher(
(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';
export class SimpleERC20BalanceAndProxyAllowanceFetcher implements AbstractBalanceAndProxyAllowanceFetcher {
private _erc20TokenContract: ERC20TokenContract;
private _erc20ProxyAddress: string;
private readonly _erc20TokenContract: ERC20TokenContract;
private readonly _erc20ProxyAddress: string;
constructor(erc20TokenWrapper: ERC20TokenContract, erc20ProxyAddress: string) {
this._erc20TokenContract = erc20TokenWrapper;
this._erc20ProxyAddress = erc20ProxyAddress;

View File

@ -19,14 +19,14 @@ enum LogEventState {
* depth.
*/
export class EventWatcher {
private _web3Wrapper: Web3Wrapper;
private readonly _web3Wrapper: Web3Wrapper;
private _blockAndLogStreamerIfExists: BlockAndLogStreamer<Block, Log> | undefined;
private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer;
private _onLogAddedSubscriptionToken: string | undefined;
private _onLogRemovedSubscriptionToken: string | undefined;
private _pollingIntervalMs: number;
private _stateLayer: BlockParamLiteral;
private _isVerbose: boolean;
private readonly _pollingIntervalMs: number;
private readonly _stateLayer: BlockParamLiteral;
private readonly _isVerbose: boolean;
constructor(
web3Wrapper: Web3Wrapper,
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`
*/
export class ExpirationWatcher {
private _orderHashByExpirationRBTree: RBTree<string>;
private _expiration: { [orderHash: string]: BigNumber } = {};
private _orderExpirationCheckingIntervalMs: number;
private _expirationMarginMs: number;
private readonly _orderHashByExpirationRBTree: RBTree<string>;
private readonly _expiration: { [orderHash: string]: BigNumber } = {};
private readonly _orderExpirationCheckingIntervalMs: number;
private readonly _expirationMarginMs: number;
private _orderExpirationCheckingIntervalIdIfExists?: NodeJS.Timer;
constructor(expirationMarginIfExistsMs?: number, orderExpirationCheckingIntervalIfExistsMs?: number) {
this._orderExpirationCheckingIntervalMs =
@ -44,7 +44,7 @@ export class ExpirationWatcher {
this._orderExpirationCheckingIntervalIdIfExists = intervalUtils.setInterval(
this._pruneExpiredOrders.bind(this, callback),
this._orderExpirationCheckingIntervalMs,
_.noop, // _pruneExpiredOrders never throws
_.noop.bind(_), // _pruneExpiredOrders never throws
);
}
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.
*/
export class OrderWatcher {
private _contractWrappers: ContractWrappers;
private _orderStateByOrderHashCache: OrderStateByOrderHash = {};
private _orderByOrderHash: OrderByOrderHash = {};
private _dependentOrderHashes: DependentOrderHashes = {};
private readonly _contractWrappers: ContractWrappers;
private readonly _orderStateByOrderHashCache: OrderStateByOrderHash = {};
private readonly _orderByOrderHash: OrderByOrderHash = {};
private readonly _dependentOrderHashes: DependentOrderHashes = {};
private _callbackIfExists?: OnOrderStateChangeCallback;
private _eventWatcher: EventWatcher;
private _web3Wrapper: Web3Wrapper;
private _expirationWatcher: ExpirationWatcher;
private _orderStateUtils: OrderStateUtils;
private _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
private _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
private _cleanupJobInterval: number;
private readonly _eventWatcher: EventWatcher;
private readonly _web3Wrapper: Web3Wrapper;
private readonly _expirationWatcher: ExpirationWatcher;
private readonly _orderStateUtils: OrderStateUtils;
private readonly _orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore;
private readonly _balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore;
private readonly _cleanupJobInterval: number;
private _cleanupJobIntervalIdIfExists?: NodeJS.Timer;
constructor(provider: Provider, networkId: number, config?: OrderWatcherConfig) {
this._web3Wrapper = new Web3Wrapper(provider);

View File

@ -12,6 +12,6 @@ export const assert = {
...sharedAssert,
isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string): void {
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
// we manually increase it for this before hook.
const mochaTestTimeoutMs = 25000;
this.timeout(mochaTestTimeoutMs);
this.timeout(mochaTestTimeoutMs); // tslint:disable-line:no-invalid-this
const txDefaults = {
gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -58,13 +58,13 @@ const CONFIG_FILE = 'compiler.json';
* to artifact files.
*/
export class Compiler {
private _resolver: Resolver;
private _nameResolver: NameResolver;
private _contractsDir: string;
private _compilerSettings: solc.CompilerSettings;
private _artifactsDir: string;
private _solcVersionIfExists: string | undefined;
private _specifiedContracts: string[] | TYPE_ALL_FILES_IDENTIFIER;
private readonly _resolver: Resolver;
private readonly _nameResolver: NameResolver;
private readonly _contractsDir: string;
private readonly _compilerSettings: solc.CompilerSettings;
private readonly _artifactsDir: string;
private readonly _solcVersionIfExists: string | undefined;
private readonly _specifiedContracts: string[] | TYPE_ALL_FILES_IDENTIFIER;
/**
* Instantiates a new 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;
describe('#Compiler', function(): void {
this.timeout(constants.timeoutMs);
this.timeout(constants.timeoutMs); // tslint:disable-line:no-invalid-this
const artifactsDir = `${__dirname}/fixtures/artifacts`;
const contractsDir = `${__dirname}/fixtures/contracts`;
const exchangeArtifactPath = `${artifactsDir}/Exchange.json`;

View File

@ -12,8 +12,8 @@ import { AbstractArtifactAdapter } from './abstract_artifact_adapter';
const CONFIG_FILE = 'compiler.json';
export class SolCompilerArtifactAdapter extends AbstractArtifactAdapter {
private _artifactsPath: string;
private _sourcesPath: string;
private readonly _artifactsPath: string;
private readonly _sourcesPath: string;
constructor(artifactsPath?: string, sourcesPath?: string) {
super();
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';
export class TruffleArtifactAdapter extends AbstractArtifactAdapter {
private _solcVersion: string;
private _sourcesPath: string;
private readonly _solcVersion: string;
private readonly _sourcesPath: string;
constructor(sourcesPath: string, solcVersion: string) {
super();
this._solcVersion = solcVersion;

View File

@ -18,15 +18,15 @@ enum BranchType {
export class ASTVisitor {
private _entryId = 0;
private _fnMap: FnMap = {};
private _branchMap: BranchMap = {};
private _modifiersStatementIds: number[] = [];
private _statementMap: StatementMap = {};
private _locationByOffset: LocationByOffset;
private _ignoreRangesBeginningAt: number[];
private readonly _fnMap: FnMap = {};
private readonly _branchMap: BranchMap = {};
private readonly _modifiersStatementIds: number[] = [];
private readonly _statementMap: StatementMap = {};
private readonly _locationByOffset: LocationByOffset;
private readonly _ignoreRangesBeginningAt: number[];
// keep track of contract/function ranges that are to be ignored
// 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[] = []) {
this._locationByOffset = locationByOffset;
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.
*/
export class CoverageSubprovider extends TraceInfoSubprovider {
private _coverageCollector: TraceCollector;
private readonly _coverageCollector: TraceCollector;
/**
* Instantiates a CoverageSubprovider instance
* @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.
class ASTInfoVisitor {
private _astInfos: ASTInfo[] = [];
private readonly _astInfos: ASTInfo[] = [];
public getASTInfoForRange(sourceRange: SourceRange): ASTInfo | null {
// HACK(albrow): Sometimes the source range doesn't exactly match that
// 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.
*/
export class ProfilerSubprovider extends TraceInfoSubprovider {
private _profilerCollector: TraceCollector;
private readonly _profilerCollector: TraceCollector;
/**
* Instantiates a ProfilerSubprovider instance
* @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 {
// Lock is used to not accept normal transactions while doing call/snapshot magic because they'll be reverted later otherwise
private _contractsData!: ContractData[];
private _artifactAdapter: AbstractArtifactAdapter;
private _logger: Logger;
private readonly _artifactAdapter: AbstractArtifactAdapter;
private readonly _logger: Logger;
/**
* Instantiates a RevertTraceSubprovider instance

View File

@ -32,10 +32,10 @@ export interface TraceCollectionSubproviderConfig {
export abstract class TraceCollectionSubprovider extends Subprovider {
protected _web3Wrapper!: Web3Wrapper;
// 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 _defaultFromAddress: string;
private readonly _lock = new Lock();
private readonly _defaultFromAddress: string;
private _isEnabled = true;
private _config: TraceCollectionSubproviderConfig;
private readonly _config: TraceCollectionSubproviderConfig;
/**
* Instantiates a TraceCollectionSubprovider instance
* @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.
*/
export class TraceCollector {
private _artifactAdapter: AbstractArtifactAdapter;
private _logger: Logger;
private readonly _artifactAdapter: AbstractArtifactAdapter;
private readonly _logger: Logger;
private _contractsData!: ContractData[];
private _collector = new Collector();
private _singleFileSubtraceHandler: SingleFileSubtraceHandler;
private readonly _collector = new Collector();
private readonly _singleFileSubtraceHandler: SingleFileSubtraceHandler;
/**
* Instantiates a TraceCollector instance

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@ import { ContractSource } from '../types';
import { Resolver } from './resolver';
export class RelativeFSResolver extends Resolver {
private _contractsDir: string;
private readonly _contractsDir: string;
constructor(contractsDir: string) {
super();
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
*/
export class EthLightwalletSubprovider extends BaseWalletSubprovider {
private _keystore: lightwallet.keystore;
private _pwDerivedKey: Uint8Array;
private readonly _keystore: lightwallet.keystore;
private readonly _pwDerivedKey: Uint8Array;
constructor(keystore: lightwallet.keystore, pwDerivedKey: Uint8Array) {
super();
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.
*/
export class FakeGasEstimateSubprovider extends Subprovider {
private _constantGasAmount: number;
private readonly _constantGasAmount: number;
/**
* Instantiates an instance of the FakeGasEstimateSubprovider
* @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.
*/
export class GanacheSubprovider extends Subprovider {
private _ganacheProvider: Provider;
private readonly _ganacheProvider: Provider;
/**
* Instantiates a GanacheSubprovider
* @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 {
// tslint:disable-next-line:no-unused-variable
private _nonceLock = new Lock();
private _connectionLock = new Lock();
private _networkId: number;
private readonly _nonceLock = new Lock();
private readonly _connectionLock = new Lock();
private readonly _networkId: number;
private _baseDerivationPath: string;
private _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync;
private readonly _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync;
private _ledgerClientIfExists?: LedgerEthereumClient;
private _shouldAlwaysAskForConfirmation: boolean;
private _addressSearchLimit: number;
private readonly _shouldAlwaysAskForConfirmation: boolean;
private readonly _addressSearchLimit: number;
/**
* 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.

View File

@ -20,10 +20,10 @@ const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
* all requests with accounts derived from the supplied mnemonic.
*/
export class MnemonicWalletSubprovider extends BaseWalletSubprovider {
private _addressSearchLimit: number;
private readonly _addressSearchLimit: number;
private _baseDerivationPath: string;
private _derivedKeyInfo: DerivedHDKeyInfo;
private _mnemonic: string;
private readonly _mnemonic: string;
/**
* 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.
*/
export class NonceTrackerSubprovider extends Subprovider {
private _nonceCache: { [address: string]: string } = {};
private readonly _nonceCache: { [address: string]: string } = {};
private static _reconstructTransaction(payload: JSONRPCRequestPayload): EthereumTx {
const raw = payload.params[0];
if (_.isUndefined(raw)) {

View File

@ -13,8 +13,8 @@ import { BaseWalletSubprovider } from './base_wallet_subprovider';
* all requests with the supplied Ethereum private key.
*/
export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider {
private _address: string;
private _privateKeyBuffer: Buffer;
private readonly _address: string;
private readonly _privateKeyBuffer: Buffer;
/**
* Instantiates a PrivateKeyWalletSubprovider.
* @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.
*/
export class RedundantSubprovider extends Subprovider {
private _subproviders: Subprovider[];
private readonly _subproviders: Subprovider[];
private static async _firstSuccessAsync(
subproviders: Subprovider[],
payload: JSONRPCRequestPayload,

View File

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

View File

@ -12,7 +12,7 @@ import { Subprovider } from './subprovider';
* are passed onwards for subsequent subproviders to handle.
*/
export class SignerSubprovider extends Subprovider {
private _web3Wrapper: Web3Wrapper;
private readonly _web3Wrapper: Web3Wrapper;
/**
* Instantiates a new SignerSubprovider
* @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;
class DerivedHDKeyInfoIterator implements IterableIterator<DerivedHDKeyInfo> {
private _parentDerivedKeyInfo: DerivedHDKeyInfo;
private _searchLimit: number;
private readonly _parentDerivedKeyInfo: DerivedHDKeyInfo;
private readonly _searchLimit: number;
private _index: number;
constructor(initialDerivedKey: DerivedHDKeyInfo, searchLimit: number = DEFAULT_ADDRESS_SEARCH_LIMIT) {

View File

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

View File

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

View File

@ -60,9 +60,9 @@ describe('NonceTrackerSubprovider', () => {
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');
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');
});
it('does not cache the result for latest transaction count', async () => {
@ -74,9 +74,9 @@ describe('NonceTrackerSubprovider', () => {
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');
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');
});
it('clears the cache on a Nonce Too Low Error', async () => {
@ -103,14 +103,14 @@ describe('NonceTrackerSubprovider', () => {
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');
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');
try {
await promisify(provider.sendAsync, provider)(txPayload);
await promisify(provider.sendAsync.bind(provider))(txPayload);
} 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');
}
});
@ -138,12 +138,12 @@ describe('NonceTrackerSubprovider', () => {
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');
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');
await promisify(provider.sendAsync, provider)(txPayload);
const thirdResponse = await promisify<any>(provider.sendAsync, provider)(noncePayload);
await promisify(provider.sendAsync.bind(provider))(txPayload);
const thirdResponse = await promisify<any>(provider.sendAsync.bind(provider))(noncePayload);
expect(thirdResponse.result).to.be.eq('0x01');
});
});

View File

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

View File

@ -12,7 +12,7 @@ export const errorReporter = {
rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY);
process.on('unhandledRejection', async (err: Error) => {
logUtils.log(`Uncaught exception ${err}. Stack: ${err.stack}`);
await this.reportAsync(err);
await errorReporter.reportAsync(err);
process.exit(1);
});
},
@ -20,7 +20,7 @@ export const errorReporter = {
if (configs.ENVIRONMENT === 'development') {
return; // Do not log development environment errors
}
return new Promise((resolve, reject) => {
return new Promise<any>((resolve, reject) => {
rollbar.handleError(err, req, (rollbarErr: Error) => {
if (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
export class Handler {
private _networkConfigByNetworkId: ItemByNetworkId<NetworkConfig> = {};
private readonly _networkConfigByNetworkId: ItemByNetworkId<NetworkConfig> = {};
private static _createProviderEngine(rpcUrl: string): Provider {
if (_.isUndefined(configs.DISPENSER_PRIVATE_KEY)) {
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');
});
app.get('/info', handler.getQueueInfo.bind(handler));
app.get('/ether/:recipient', parameterTransformer.transform, handler.dispenseEther.bind(handler));
app.get('/zrx/:recipient', parameterTransformer.transform, handler.dispenseZRX.bind(handler));
app.get('/order/weth/:recipient', parameterTransformer.transform, handler.dispenseWETHOrderAsync.bind(handler));
app.get('/order/zrx/:recipient', parameterTransformer.transform, handler.dispenseZRXOrderAsync.bind(handler));
app.get(
'/ether/:recipient',
parameterTransformer.transform.bind(parameterTransformer),
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
app.use(errorReporter.errorHandler());

View File

@ -29,6 +29,7 @@ export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED;
return this.applyWithWalker(
// tslint:disable-next-line:no-inferred-empty-object-type
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';
export class AbiDecoder {
private _methodIds: { [signatureHash: string]: EventAbi } = {};
private readonly _methodIds: { [signatureHash: string]: EventAbi } = {};
constructor(abiArrays: AbiDefinition[][]) {
_.forEach(abiArrays, this.addABI.bind(this));
}

View File

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

View File

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

View File

@ -15,7 +15,7 @@ export const utils = {
if (_.isNull(hex)) {
return null;
}
const decimal = this.convertHexToNumber(hex);
const decimal = utils.convertHexToNumber(hex);
return decimal;
},
convertAmountToBigNumber(value: string | number | BigNumber): BigNumber {
@ -40,7 +40,7 @@ export const utils = {
return valueBigNumber.lessThan(0) ? '-0x' + valueHex.substr(1) : '0x' + valueHex;
},
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.`);
}

View File

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

View File

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

View File

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

View File

@ -14,9 +14,9 @@ export const U2fNotSupportedDialog = (props: U2fNotSupportedDialogProps) => {
<Dialog
title="U2F Not Supported"
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}
onRequestClose={props.onToggleDialog.bind(this)}
onRequestClose={props.onToggleDialog}
autoScrollBodyContent={true}
>
<div className="pt2" style={{ color: colors.grey700 }}>

View File

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

View File

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

View File

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

View File

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

View File

@ -35,7 +35,7 @@ export class BalanceBoundedInput extends React.Component<BalanceBoundedInputProp
isDisabled: false,
shouldShowErrs: true,
hintText: 'amount',
onErrorMsgChange: _.noop,
onErrorMsgChange: _.noop.bind(_),
shouldShowUnderline: true,
};
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);
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);
this.props.onErrorMsgChange(errorMsg);
this.setState(

View File

@ -17,7 +17,7 @@ interface ExpirationInputState {
}
export class ExpirationInput extends React.Component<ExpirationInputProps, ExpirationInputState> {
private _earliestPickableMoment: moment.Moment;
private readonly _earliestPickableMoment: moment.Moment;
constructor(props: ExpirationInputProps) {
super(props);
// 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,
method: 'share',
},
_.noop,
_.noop.bind(_),
);
}
private _shareViaEmailAsync(): void {

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