Merge pull request #71 from 0xProject/lodash-tree-shake

Use different lodash import syntax which allows to include only used functions
This commit is contained in:
Leonid
2017-06-21 15:04:13 +02:00
committed by GitHub
15 changed files with 93 additions and 76 deletions

View File

@@ -1,4 +1,4 @@
import * as _ from 'lodash'; import isUndefined = require('lodash/isUndefined');
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import {bigNumberConfigs} from './bignumber_config'; import {bigNumberConfigs} from './bignumber_config';
import * as ethUtil from 'ethereumjs-util'; import * as ethUtil from 'ethereumjs-util';
@@ -239,10 +239,10 @@ export class ZeroEx {
} }
private async _getExchangeAddressAsync() { private async _getExchangeAddressAsync() {
const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync(); const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync();
const exchangeNetworkConfigsIfExists = _.isUndefined(networkIdIfExists) ? const exchangeNetworkConfigsIfExists = isUndefined(networkIdIfExists) ?
undefined : undefined :
(ExchangeArtifacts as any).networks[networkIdIfExists]; (ExchangeArtifacts as any).networks[networkIdIfExists];
if (_.isUndefined(exchangeNetworkConfigsIfExists)) { if (isUndefined(exchangeNetworkConfigsIfExists)) {
throw new Error(ZeroExError.CONTRACT_NOT_DEPLOYED_ON_NETWORK); throw new Error(ZeroExError.CONTRACT_NOT_DEPLOYED_ON_NETWORK);
} }
const exchangeAddress = exchangeNetworkConfigsIfExists.address; const exchangeAddress = exchangeNetworkConfigsIfExists.address;

View File

@@ -1,4 +1,5 @@
import * as _ from 'lodash'; import includes = require('lodash/includes');
import isUndefined = require('lodash/isUndefined');
import contract = require('truffle-contract'); import contract = require('truffle-contract');
import {Web3Wrapper} from '../web3_wrapper'; import {Web3Wrapper} from '../web3_wrapper';
import {ZeroExError, Artifact, ContractInstance} from '../types'; import {ZeroExError, Artifact, ContractInstance} from '../types';
@@ -15,17 +16,17 @@ export class ContractWrapper {
c.setProvider(providerObj); c.setProvider(providerObj);
const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync(); const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync();
const artifactNetworkConfigs = _.isUndefined(networkIdIfExists) ? const artifactNetworkConfigs = isUndefined(networkIdIfExists) ?
undefined : undefined :
artifact.networks[networkIdIfExists]; artifact.networks[networkIdIfExists];
let contractAddress; let contractAddress;
if (!_.isUndefined(address)) { if (!isUndefined(address)) {
contractAddress = address; contractAddress = address;
} else if (!_.isUndefined(artifactNetworkConfigs)) { } else if (!isUndefined(artifactNetworkConfigs)) {
contractAddress = artifactNetworkConfigs.address; contractAddress = artifactNetworkConfigs.address;
} }
if (!_.isUndefined(contractAddress)) { if (!isUndefined(contractAddress)) {
const doesContractExist = await this._web3Wrapper.doesContractExistAtAddressAsync(contractAddress); const doesContractExist = await this._web3Wrapper.doesContractExistAtAddressAsync(contractAddress);
if (!doesContractExist) { if (!doesContractExist) {
throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST); throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST);
@@ -33,11 +34,11 @@ export class ContractWrapper {
} }
try { try {
const contractInstance = _.isUndefined(address) ? await c.deployed() : await c.at(address); const contractInstance = isUndefined(address) ? await c.deployed() : await c.at(address);
return contractInstance; return contractInstance;
} catch (err) { } catch (err) {
const errMsg = `${err}`; const errMsg = `${err}`;
if (_.includes(errMsg, 'not been deployed to detected network')) { if (includes(errMsg, 'not been deployed to detected network')) {
throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST); throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST);
} else { } else {
utils.consoleLog(`Notice: Error encountered: ${err} ${err.stack}`); utils.consoleLog(`Notice: Error encountered: ${err} ${err.stack}`);

View File

@@ -1,4 +1,8 @@
import * as _ from 'lodash'; import map = require('lodash/map');
import isEmpty = require('lodash/isEmpty');
import find = require('lodash/find');
import isUndefined = require('lodash/isUndefined');
import unzip = require('lodash/unzip');
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import promisify = require('es6-promisify'); import promisify = require('es6-promisify');
import {Web3Wrapper} from '../web3_wrapper'; import {Web3Wrapper} from '../web3_wrapper';
@@ -198,7 +202,7 @@ export class ExchangeWrapper extends ContractWrapper {
@decorators.contractCallErrorHandler @decorators.contractCallErrorHandler
public async fillOrdersUpToAsync(signedOrders: SignedOrder[], takerTokenFillAmount: BigNumber.BigNumber, public async fillOrdersUpToAsync(signedOrders: SignedOrder[], takerTokenFillAmount: BigNumber.BigNumber,
shouldCheckTransfer: boolean, takerAddress: string): Promise<void> { shouldCheckTransfer: boolean, takerAddress: string): Promise<void> {
const takerTokenAddresses = _.map(signedOrders, signedOrder => signedOrder.takerTokenAddress); const takerTokenAddresses = map(signedOrders, signedOrder => signedOrder.takerTokenAddress);
assert.hasAtMostOneUniqueValue(takerTokenAddresses, assert.hasAtMostOneUniqueValue(takerTokenAddresses,
ExchangeContractErrs.MULTIPLE_TAKER_TOKENS_IN_FILL_UP_TO_DISALLOWED); ExchangeContractErrs.MULTIPLE_TAKER_TOKENS_IN_FILL_UP_TO_DISALLOWED);
assert.isBigNumber('takerTokenFillAmount', takerTokenFillAmount); assert.isBigNumber('takerTokenFillAmount', takerTokenFillAmount);
@@ -209,11 +213,11 @@ export class ExchangeWrapper extends ContractWrapper {
await this._validateFillOrderAndThrowIfInvalidAsync( await this._validateFillOrderAndThrowIfInvalidAsync(
signedOrder, takerTokenFillAmount, takerAddress); signedOrder, takerTokenFillAmount, takerAddress);
} }
if (_.isEmpty(signedOrders)) { if (isEmpty(signedOrders)) {
return; // no-op return; // no-op
} }
const orderAddressesValuesAndSignatureArray = _.map(signedOrders, signedOrder => { const orderAddressesValuesAndSignatureArray = map(signedOrders, signedOrder => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(signedOrder), ...ExchangeWrapper._getOrderAddressesAndValues(signedOrder),
signedOrder.ecSignature.v, signedOrder.ecSignature.v,
@@ -221,8 +225,8 @@ export class ExchangeWrapper extends ContractWrapper {
signedOrder.ecSignature.s, signedOrder.ecSignature.s,
]; ];
}); });
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'( // We use unzip<any> because unzip doesn't type check if values have different types :'(
const [orderAddressesArray, orderValuesArray, vArray, rArray, sArray] = _.unzip<any>( const [orderAddressesArray, orderValuesArray, vArray, rArray, sArray] = unzip<any>(
orderAddressesValuesAndSignatureArray, orderAddressesValuesAndSignatureArray,
); );
@@ -277,11 +281,11 @@ export class ExchangeWrapper extends ContractWrapper {
await this._validateFillOrderAndThrowIfInvalidAsync( await this._validateFillOrderAndThrowIfInvalidAsync(
orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount, takerAddress); orderFillRequest.signedOrder, orderFillRequest.takerTokenFillAmount, takerAddress);
} }
if (_.isEmpty(orderFillRequests)) { if (isEmpty(orderFillRequests)) {
return; // no-op return; // no-op
} }
const orderAddressesValuesAmountsAndSignatureArray = _.map(orderFillRequests, orderFillRequest => { const orderAddressesValuesAmountsAndSignatureArray = map(orderFillRequests, orderFillRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(orderFillRequest.signedOrder), ...ExchangeWrapper._getOrderAddressesAndValues(orderFillRequest.signedOrder),
orderFillRequest.takerTokenFillAmount, orderFillRequest.takerTokenFillAmount,
@@ -290,8 +294,8 @@ export class ExchangeWrapper extends ContractWrapper {
orderFillRequest.signedOrder.ecSignature.s, orderFillRequest.signedOrder.ecSignature.s,
]; ];
}); });
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'( // We use unzip<any> because unzip doesn't type check if values have different types :'(
const [orderAddressesArray, orderValuesArray, takerTokenFillAmountArray, vArray, rArray, sArray] = _.unzip<any>( const [orderAddressesArray, orderValuesArray, takerTokenFillAmountArray, vArray, rArray, sArray] = unzip<any>(
orderAddressesValuesAmountsAndSignatureArray, orderAddressesValuesAmountsAndSignatureArray,
); );
@@ -390,7 +394,7 @@ export class ExchangeWrapper extends ContractWrapper {
request.fillTakerAmount); request.fillTakerAmount);
} }
const orderAddressesValuesAndTakerTokenFillAmounts = _.map(orderFillOrKillRequests, request => { const orderAddressesValuesAndTakerTokenFillAmounts = map(orderFillOrKillRequests, request => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(request.signedOrder), ...ExchangeWrapper._getOrderAddressesAndValues(request.signedOrder),
request.fillTakerAmount, request.fillTakerAmount,
@@ -400,9 +404,9 @@ export class ExchangeWrapper extends ContractWrapper {
]; ];
}); });
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'( // We use unzip<any> because unzip doesn't type check if values have different types :'(
const [orderAddresses, orderValues, fillTakerAmounts, vParams, rParams, sParams] = const [orderAddresses, orderValues, fillTakerAmounts, vParams, rParams, sParams] =
_.unzip<any>(orderAddressesValuesAndTakerTokenFillAmounts); unzip<any>(orderAddressesValuesAndTakerTokenFillAmounts);
const gas = await exchangeInstance.batchFillOrKill.estimateGas( const gas = await exchangeInstance.batchFillOrKill.estimateGas(
orderAddresses, orderAddresses,
@@ -473,7 +477,7 @@ export class ExchangeWrapper extends ContractWrapper {
*/ */
@decorators.contractCallErrorHandler @decorators.contractCallErrorHandler
public async batchCancelOrderAsync(orderCancellationRequests: OrderCancellationRequest[]): Promise<void> { public async batchCancelOrderAsync(orderCancellationRequests: OrderCancellationRequest[]): Promise<void> {
const makers = _.map(orderCancellationRequests, cancellationRequest => cancellationRequest.order.maker); const makers = map(orderCancellationRequests, cancellationRequest => cancellationRequest.order.maker);
assert.hasAtMostOneUniqueValue(makers, ExchangeContractErrs.MULTIPLE_MAKERS_IN_SINGLE_CANCEL_BATCH_DISALLOWED); assert.hasAtMostOneUniqueValue(makers, ExchangeContractErrs.MULTIPLE_MAKERS_IN_SINGLE_CANCEL_BATCH_DISALLOWED);
const maker = makers[0]; const maker = makers[0];
await assert.isSenderAddressAsync('maker', maker, this._web3Wrapper); await assert.isSenderAddressAsync('maker', maker, this._web3Wrapper);
@@ -484,19 +488,19 @@ export class ExchangeWrapper extends ContractWrapper {
cancellationRequest.order, cancellationRequest.takerTokenCancelAmount, cancellationRequest.order, cancellationRequest.takerTokenCancelAmount,
); );
} }
if (_.isEmpty(orderCancellationRequests)) { if (isEmpty(orderCancellationRequests)) {
return; // no-op return; // no-op
} }
const exchangeInstance = await this._getExchangeContractAsync(); const exchangeInstance = await this._getExchangeContractAsync();
const orderAddressesValuesAndTakerTokenCancelAmounts = _.map(orderCancellationRequests, cancellationRequest => { const orderAddressesValuesAndTakerTokenCancelAmounts = map(orderCancellationRequests, cancellationRequest => {
return [ return [
...ExchangeWrapper._getOrderAddressesAndValues(cancellationRequest.order), ...ExchangeWrapper._getOrderAddressesAndValues(cancellationRequest.order),
cancellationRequest.takerTokenCancelAmount, cancellationRequest.takerTokenCancelAmount,
]; ];
}); });
// We use _.unzip<any> because _.unzip doesn't type check if values have different types :'( // We use unzip<any> because unzip doesn't type check if values have different types :'(
const [orderAddresses, orderValues, takerTokenCancelAmounts] = const [orderAddresses, orderValues, takerTokenCancelAmounts] =
_.unzip<any>(orderAddressesValuesAndTakerTokenCancelAmounts); unzip<any>(orderAddressesValuesAndTakerTokenCancelAmounts);
const gas = await exchangeInstance.batchCancel.estimateGas( const gas = await exchangeInstance.batchCancel.estimateGas(
orderAddresses, orderAddresses,
orderValues, orderValues,
@@ -561,7 +565,7 @@ export class ExchangeWrapper extends ContractWrapper {
* Stops watching for all exchange events * Stops watching for all exchange events
*/ */
public async stopWatchingAllEventsAsync(): Promise<void> { public async stopWatchingAllEventsAsync(): Promise<void> {
const stopWatchingPromises = _.map(this._exchangeLogEventEmitters, const stopWatchingPromises = map(this._exchangeLogEventEmitters,
logEventObj => logEventObj.stopWatchingAsync()); logEventObj => logEventObj.stopWatchingAsync());
await Promise.all(stopWatchingPromises); await Promise.all(stopWatchingPromises);
this._exchangeLogEventEmitters = []; this._exchangeLogEventEmitters = [];
@@ -715,8 +719,8 @@ export class ExchangeWrapper extends ContractWrapper {
} }
} }
private _throwErrorLogsAsErrors(logs: ContractEvent[]): void { private _throwErrorLogsAsErrors(logs: ContractEvent[]): void {
const errEvent = _.find(logs, {event: 'LogError'}); const errEvent = find(logs, {event: 'LogError'});
if (!_.isUndefined(errEvent)) { if (!isUndefined(errEvent)) {
const errCode = (errEvent.args as LogErrorContractEventArgs).errorId.toNumber(); const errCode = (errEvent.args as LogErrorContractEventArgs).errorId.toNumber();
const errMessage = this._exchangeContractErrCodesToMsg[errCode]; const errMessage = this._exchangeContractErrCodesToMsg[errCode];
throw new Error(errMessage); throw new Error(errMessage);
@@ -733,7 +737,7 @@ export class ExchangeWrapper extends ContractWrapper {
return isRoundingError; return isRoundingError;
} }
private async _getExchangeContractAsync(): Promise<ExchangeContract> { private async _getExchangeContractAsync(): Promise<ExchangeContract> {
if (!_.isUndefined(this._exchangeContractIfExists)) { if (!isUndefined(this._exchangeContractIfExists)) {
return this._exchangeContractIfExists; return this._exchangeContractIfExists;
} }
const contractInstance = await this._instantiateContractIfExistsAsync((ExchangeArtifacts as any)); const contractInstance = await this._instantiateContractIfExistsAsync((ExchangeArtifacts as any));

View File

@@ -1,4 +1,5 @@
import * as _ from 'lodash'; import map = require('lodash/map');
import isUndefined = require('lodash/isUndefined');
import {Web3Wrapper} from '../web3_wrapper'; import {Web3Wrapper} from '../web3_wrapper';
import {Token, TokenRegistryContract, TokenMetadata} from '../types'; import {Token, TokenRegistryContract, TokenMetadata} from '../types';
import {assert} from '../utils/assert'; import {assert} from '../utils/assert';
@@ -24,12 +25,12 @@ export class TokenRegistryWrapper extends ContractWrapper {
const tokenRegistryContract = await this._getTokenRegistryContractAsync(); const tokenRegistryContract = await this._getTokenRegistryContractAsync();
const addresses = await tokenRegistryContract.getTokenAddresses.call(); const addresses = await tokenRegistryContract.getTokenAddresses.call();
const tokenMetadataPromises: Array<Promise<TokenMetadata>> = _.map( const tokenMetadataPromises: Array<Promise<TokenMetadata>> = map(
addresses, addresses,
(address: string) => (tokenRegistryContract.getTokenMetaData.call(address)), (address: string) => (tokenRegistryContract.getTokenMetaData.call(address)),
); );
const tokensMetadata = await Promise.all(tokenMetadataPromises); const tokensMetadata = await Promise.all(tokenMetadataPromises);
const tokens = _.map(tokensMetadata, metadata => { const tokens = map(tokensMetadata, metadata => {
return { return {
address: metadata[0], address: metadata[0],
name: metadata[1], name: metadata[1],
@@ -41,7 +42,7 @@ export class TokenRegistryWrapper extends ContractWrapper {
return tokens; return tokens;
} }
private async _getTokenRegistryContractAsync(): Promise<TokenRegistryContract> { private async _getTokenRegistryContractAsync(): Promise<TokenRegistryContract> {
if (!_.isUndefined(this._tokenRegistryContractIfExists)) { if (!isUndefined(this._tokenRegistryContractIfExists)) {
return this._tokenRegistryContractIfExists; return this._tokenRegistryContractIfExists;
} }
const contractInstance = await this._instantiateContractIfExistsAsync((TokenRegistryArtifacts as any)); const contractInstance = await this._instantiateContractIfExistsAsync((TokenRegistryArtifacts as any));

View File

@@ -1,4 +1,4 @@
import * as _ from 'lodash'; import isUndefined = require('lodash/isUndefined');
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import {Web3Wrapper} from '../web3_wrapper'; import {Web3Wrapper} from '../web3_wrapper';
import {assert} from '../utils/assert'; import {assert} from '../utils/assert';
@@ -179,7 +179,7 @@ export class TokenWrapper extends ContractWrapper {
} }
private async _getTokenContractAsync(tokenAddress: string): Promise<TokenContract> { private async _getTokenContractAsync(tokenAddress: string): Promise<TokenContract> {
let tokenContract = this._tokenContractsByAddress[tokenAddress]; let tokenContract = this._tokenContractsByAddress[tokenAddress];
if (!_.isUndefined(tokenContract)) { if (!isUndefined(tokenContract)) {
return tokenContract; return tokenContract;
} }
const contractInstance = await this._instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress); const contractInstance = await this._instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress);
@@ -189,10 +189,10 @@ export class TokenWrapper extends ContractWrapper {
} }
private async _getProxyAddressAsync() { private async _getProxyAddressAsync() {
const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync(); const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync();
const proxyNetworkConfigsIfExists = _.isUndefined(networkIdIfExists) ? const proxyNetworkConfigsIfExists = isUndefined(networkIdIfExists) ?
undefined : undefined :
(ProxyArtifacts as any).networks[networkIdIfExists]; (ProxyArtifacts as any).networks[networkIdIfExists];
if (_.isUndefined(proxyNetworkConfigsIfExists)) { if (isUndefined(proxyNetworkConfigsIfExists)) {
throw new Error(ZeroExError.CONTRACT_NOT_DEPLOYED_ON_NETWORK); throw new Error(ZeroExError.CONTRACT_NOT_DEPLOYED_ON_NETWORK);
} }
const proxyAddress = proxyNetworkConfigsIfExists.address; const proxyAddress = proxyNetworkConfigsIfExists.address;

View File

@@ -1,10 +1,10 @@
import * as _ from 'lodash'; import reduce = require('lodash/reduce');
import * as Web3 from 'web3'; import * as Web3 from 'web3';
// Utility function to create a K:V from a list of strings // Utility function to create a K:V from a list of strings
// Adapted from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html // Adapted from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
function strEnum(values: string[]): {[key: string]: string} { function strEnum(values: string[]): {[key: string]: string} {
return _.reduce(values, (result, key) => { return reduce(values, (result, key) => {
result[key] = key; result[key] = key;
return result; return result;
}, Object.create(null)); }, Object.create(null));

View File

@@ -1,4 +1,10 @@
import * as _ from 'lodash'; import uniq = require('lodash/uniq');
import isEmpty = require('lodash/isEmpty');
import isObject = require('lodash/isObject');
import isFinite = require('lodash/isFinite');
import isString = require('lodash/isString');
import isBoolean = require('lodash/isBoolean');
import isUndefined = require('lodash/isUndefined');
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import * as Web3 from 'web3'; import * as Web3 from 'web3';
import {Web3Wrapper} from '../web3_wrapper'; import {Web3Wrapper} from '../web3_wrapper';
@@ -9,17 +15,17 @@ const HEX_REGEX = /^0x[0-9A-F]*$/i;
export const assert = { export const assert = {
isBigNumber(variableName: string, value: BigNumber.BigNumber): void { isBigNumber(variableName: string, value: BigNumber.BigNumber): void {
const isBigNumber = _.isObject(value) && value.isBigNumber; const isBigNumber = isObject(value) && value.isBigNumber;
this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value)); this.assert(isBigNumber, this.typeAssertionMessage(variableName, 'BigNumber', value));
}, },
isUndefined(value: any, variableName?: string): void { isUndefined(value: any, variableName?: string): void {
this.assert(_.isUndefined(value), this.typeAssertionMessage(variableName, 'undefined', value)); this.assert(isUndefined(value), this.typeAssertionMessage(variableName, 'undefined', value));
}, },
isString(variableName: string, value: string): void { isString(variableName: string, value: string): void {
this.assert(_.isString(value), this.typeAssertionMessage(variableName, 'string', value)); this.assert(isString(value), this.typeAssertionMessage(variableName, 'string', value));
}, },
isHexString(variableName: string, value: string): void { isHexString(variableName: string, value: string): void {
this.assert(_.isString(value) && HEX_REGEX.test(value), this.assert(isString(value) && HEX_REGEX.test(value),
this.typeAssertionMessage(variableName, 'HexString', value)); this.typeAssertionMessage(variableName, 'HexString', value));
}, },
isETHAddressHex(variableName: string, value: string): void { isETHAddressHex(variableName: string, value: string): void {
@@ -36,19 +42,19 @@ export const assert = {
}, },
async isUserAddressAvailableAsync(web3Wrapper: Web3Wrapper): Promise<void> { async isUserAddressAvailableAsync(web3Wrapper: Web3Wrapper): Promise<void> {
const availableAddresses = await web3Wrapper.getAvailableAddressesAsync(); const availableAddresses = await web3Wrapper.getAvailableAddressesAsync();
this.assert(!_.isEmpty(availableAddresses), 'No addresses were available on the provided web3 instance'); this.assert(!isEmpty(availableAddresses), 'No addresses were available on the provided web3 instance');
}, },
hasAtMostOneUniqueValue(value: any[], errMsg: string): void { hasAtMostOneUniqueValue(value: any[], errMsg: string): void {
this.assert(_.uniq(value).length <= 1, errMsg); this.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)); this.assert(isFinite(value), this.typeAssertionMessage(variableName, 'number', value));
}, },
isValidOrderHash(variableName: string, value: string): void { isValidOrderHash(variableName: string, value: string): void {
this.assert(utils.isValidOrderHash(value), this.typeAssertionMessage(variableName, 'orderHash', value)); this.assert(utils.isValidOrderHash(value), this.typeAssertionMessage(variableName, 'orderHash', value));
}, },
isBoolean(variableName: string, value: boolean): void { isBoolean(variableName: string, value: boolean): void {
this.assert(_.isBoolean(value), this.typeAssertionMessage(variableName, 'boolean', value)); this.assert(isBoolean(value), this.typeAssertionMessage(variableName, 'boolean', value));
}, },
doesConformToSchema(variableName: string, value: object, schema: Schema): void { doesConformToSchema(variableName: string, value: object, schema: Schema): void {
const schemaValidator = new SchemaValidator(); const schemaValidator = new SchemaValidator();

View File

@@ -1,4 +1,4 @@
import * as _ from 'lodash'; import includes = require('lodash/includes');
import {constants} from './constants'; import {constants} from './constants';
import {AsyncMethod, ZeroExError} from '../types'; import {AsyncMethod, ZeroExError} from '../types';
@@ -20,10 +20,10 @@ export const decorators = {
const result = await originalMethod.apply(this, args); const result = await originalMethod.apply(this, args);
return result; return result;
} catch (error) { } catch (error) {
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) { if (includes(error.message, constants.INVALID_JUMP_PATTERN)) {
throw new Error(ZeroExError.INVALID_JUMP); throw new Error(ZeroExError.INVALID_JUMP);
} }
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) { if (includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
throw new Error(ZeroExError.OUT_OF_GAS); throw new Error(ZeroExError.OUT_OF_GAS);
} }
throw error; throw error;

View File

@@ -1,4 +1,5 @@
import * as _ from 'lodash'; import map = require('lodash/map');
import includes = require('lodash/includes');
import * as BN from 'bn.js'; import * as BN from 'bn.js';
import * as ethABI from 'ethereumjs-abi'; import * as ethABI from 'ethereumjs-abi';
import * as ethUtil from 'ethereumjs-util'; import * as ethUtil from 'ethereumjs-util';
@@ -20,7 +21,7 @@ export const utils = {
console.log(message); console.log(message);
}, },
isParityNode(nodeVersion: string): boolean { isParityNode(nodeVersion: string): boolean {
return _.includes(nodeVersion, 'Parity'); return includes(nodeVersion, 'Parity');
}, },
isValidOrderHash(orderHashHex: string): boolean { isValidOrderHash(orderHashHex: string): boolean {
const isValid = /^0x[0-9A-F]{64}$/i.test(orderHashHex); const isValid = /^0x[0-9A-F]{64}$/i.test(orderHashHex);
@@ -44,8 +45,8 @@ export const utils = {
{value: utils.bigNumberToBN(order.expirationUnixTimestampSec), type: SolidityTypes.uint256}, {value: utils.bigNumberToBN(order.expirationUnixTimestampSec), type: SolidityTypes.uint256},
{value: utils.bigNumberToBN(order.salt), type: SolidityTypes.uint256}, {value: utils.bigNumberToBN(order.salt), type: SolidityTypes.uint256},
]; ];
const types = _.map(orderParts, o => o.type); const types = map(orderParts, o => o.type);
const values = _.map(orderParts, o => o.value); const values = map(orderParts, o => o.value);
const hashBuff = ethABI.soliditySHA3(types, values); const hashBuff = ethABI.soliditySHA3(types, values);
const hashHex = ethUtil.bufferToHex(hashBuff); const hashHex = ethUtil.bufferToHex(hashBuff);
return hashHex; return hashHex;

View File

@@ -1,4 +1,4 @@
import * as _ from 'lodash'; import includes = require('lodash/includes');
import * as Web3 from 'web3'; import * as Web3 from 'web3';
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import promisify = require('es6-promisify'); import promisify = require('es6-promisify');
@@ -17,7 +17,7 @@ export class Web3Wrapper {
} }
public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> { public async isSenderAddressAvailableAsync(senderAddress: string): Promise<boolean> {
const addresses = await this.getAvailableAddressesAsync(); const addresses = await this.getAvailableAddressesAsync();
return _.includes(addresses, senderAddress); return includes(addresses, senderAddress);
} }
public async getNodeVersionAsync(): Promise<string> { public async getNodeVersionAsync(): Promise<string> {
const nodeVersion = await promisify(this.web3.version.getNode)(); const nodeVersion = await promisify(this.web3.version.getNode)();

View File

@@ -1,4 +1,5 @@
import * as _ from 'lodash'; import each = require('lodash/each');
import assign = require('lodash/assign');
import * as chai from 'chai'; import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup'; import {chaiSetup} from './utils/chai_setup';
import 'mocha'; import 'mocha';
@@ -67,7 +68,7 @@ describe('ZeroEx library', () => {
).to.become(false); ).to.become(false);
}); });
it('should return false if the signature doesn\'t pertain to the dataHex & address', async () => { it('should return false if the signature doesn\'t pertain to the dataHex & address', async () => {
const wrongSignature = _.assign({}, signature, {v: 28}); const wrongSignature = assign({}, signature, {v: 28});
expect(ZeroEx.isValidSignature(dataHex, wrongSignature, address)).to.be.false(); expect(ZeroEx.isValidSignature(dataHex, wrongSignature, address)).to.be.false();
return expect( return expect(
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, wrongSignature, address), (zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, wrongSignature, address),
@@ -144,7 +145,7 @@ describe('ZeroEx library', () => {
let stubs: Sinon.SinonStub[] = []; let stubs: Sinon.SinonStub[] = [];
afterEach(() => { afterEach(() => {
// clean up any stubs after the test has completed // clean up any stubs after the test has completed
_.each(stubs, s => s.restore()); each(stubs, s => s.restore());
stubs = []; stubs = [];
}); });
it('calculates the order hash', async () => { it('calculates the order hash', async () => {
@@ -171,7 +172,7 @@ describe('ZeroEx library', () => {
}); });
afterEach(() => { afterEach(() => {
// clean up any stubs after the test has completed // clean up any stubs after the test has completed
_.each(stubs, s => s.restore()); each(stubs, s => s.restore());
stubs = []; stubs = [];
}); });
it ('Should return the correct ECSignature on TestPRC nodeVersion', async () => { it ('Should return the correct ECSignature on TestPRC nodeVersion', async () => {

View File

@@ -1,5 +1,5 @@
import 'mocha'; import 'mocha';
import * as _ from 'lodash'; import forEach = require('lodash/forEach');
import * as chai from 'chai'; import * as chai from 'chai';
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import promisify = require('es6-promisify'); import promisify = require('es6-promisify');
@@ -19,7 +19,7 @@ const expect = chai.expect;
describe('Schema', () => { describe('Schema', () => {
const validator = new SchemaValidator(); const validator = new SchemaValidator();
const validateAgainstSchema = (testCases: any[], schema: any, shouldFail = false) => { const validateAgainstSchema = (testCases: any[], schema: any, shouldFail = false) => {
_.forEach(testCases, (testCase: any) => { forEach(testCases, (testCase: any) => {
if (shouldFail) { if (shouldFail) {
expect(validator.validate(testCase, schema).errors).to.be.lengthOf.at.least(1); expect(validator.validate(testCase, schema).errors).to.be.lengthOf.at.least(1);
} else { } else {
@@ -285,7 +285,7 @@ describe('Schema', () => {
'00.00': '0', '00.00': '0',
'.3': '0.3', '.3': '0.3',
}; };
_.forEach(testCases, (serialized: string, input: string) => { forEach(testCases, (serialized: string, input: string) => {
expect(JSON.parse(JSON.stringify(new BigNumber(input)))).to.be.equal(serialized); expect(JSON.parse(JSON.stringify(new BigNumber(input)))).to.be.equal(serialized);
}); });
}); });

View File

@@ -1,4 +1,4 @@
import * as _ from 'lodash'; import each = require('lodash/each');
import 'mocha'; import 'mocha';
import * as chai from 'chai'; import * as chai from 'chai';
import {chaiSetup} from './utils/chai_setup'; import {chaiSetup} from './utils/chai_setup';
@@ -32,7 +32,7 @@ describe('TokenRegistryWrapper', () => {
expect(tokens).to.have.lengthOf(TOKEN_REGISTRY_SIZE_AFTER_MIGRATION); expect(tokens).to.have.lengthOf(TOKEN_REGISTRY_SIZE_AFTER_MIGRATION);
const schemaValidator = new SchemaValidator(); const schemaValidator = new SchemaValidator();
_.each(tokens, token => { each(tokens, token => {
const validationResult = schemaValidator.validate(token, tokenSchema); const validationResult = schemaValidator.validate(token, tokenSchema);
expect(validationResult.errors).to.have.lengthOf(0); expect(validationResult.errors).to.have.lengthOf(0);
}); });

View File

@@ -1,4 +1,5 @@
import * as _ from 'lodash'; import assign = require('lodash/assign');
import isUndefined = require('lodash/isUndefined');
import * as BigNumber from 'bignumber.js'; import * as BigNumber from 'bignumber.js';
import {ZeroEx, SignedOrder} from '../../src'; import {ZeroEx, SignedOrder} from '../../src';
@@ -16,7 +17,7 @@ export const orderFactory = {
feeRecipient: string, feeRecipient: string,
expirationUnixTimestampSec?: BigNumber.BigNumber): Promise<SignedOrder> { expirationUnixTimestampSec?: BigNumber.BigNumber): Promise<SignedOrder> {
const defaultExpirationUnixTimestampSec = new BigNumber(2524604400); // Close to infinite const defaultExpirationUnixTimestampSec = new BigNumber(2524604400); // Close to infinite
expirationUnixTimestampSec = _.isUndefined(expirationUnixTimestampSec) ? expirationUnixTimestampSec = isUndefined(expirationUnixTimestampSec) ?
defaultExpirationUnixTimestampSec : defaultExpirationUnixTimestampSec :
expirationUnixTimestampSec; expirationUnixTimestampSec;
const order = { const order = {
@@ -34,7 +35,7 @@ export const orderFactory = {
}; };
const orderHash = await zeroEx.getOrderHashHexAsync(order); const orderHash = await zeroEx.getOrderHashHexAsync(order);
const ecSignature = await zeroEx.signOrderHashAsync(orderHash, maker); const ecSignature = await zeroEx.signOrderHashAsync(orderHash, maker);
const signedOrder: SignedOrder = _.assign(order, {ecSignature}); const signedOrder: SignedOrder = assign(order, {ecSignature});
return signedOrder; return signedOrder;
}, },
}; };

View File

@@ -1,4 +1,6 @@
import * as _ from 'lodash'; import find = require('lodash/find');
import filter = require('lodash/filter');
import isUndefined = require('lodash/isUndefined');
import {Token, ZeroExError} from '../../src'; import {Token, ZeroExError} from '../../src';
const PROTOCOL_TOKEN_SYMBOL = 'ZRX'; const PROTOCOL_TOKEN_SYMBOL = 'ZRX';
@@ -9,14 +11,14 @@ export class TokenUtils {
this.tokens = tokens; this.tokens = tokens;
} }
public getProtocolTokenOrThrow(): Token { public getProtocolTokenOrThrow(): Token {
const zrxToken = _.find(this.tokens, {symbol: PROTOCOL_TOKEN_SYMBOL}); const zrxToken = find(this.tokens, {symbol: PROTOCOL_TOKEN_SYMBOL});
if (_.isUndefined(zrxToken)) { if (isUndefined(zrxToken)) {
throw new Error(ZeroExError.ZRX_NOT_IN_TOKEN_REGISTRY); throw new Error(ZeroExError.ZRX_NOT_IN_TOKEN_REGISTRY);
} }
return zrxToken; return zrxToken;
} }
public getNonProtocolTokens(): Token[] { public getNonProtocolTokens(): Token[] {
const nonProtocolTokens = _.filter(this.tokens, token => { const nonProtocolTokens = filter(this.tokens, token => {
return token.symbol !== PROTOCOL_TOKEN_SYMBOL; return token.symbol !== PROTOCOL_TOKEN_SYMBOL;
}); });
return nonProtocolTokens; return nonProtocolTokens;