Consolidate all console.log into the @0xproject/utils package

This commit is contained in:
Brandon Millman 2018-03-13 18:06:02 -07:00
parent c2f8858aab
commit c8a8b851d8
39 changed files with 98 additions and 125 deletions

View File

@ -17,10 +17,6 @@ export const utils = {
bigNumberToBN(value: BigNumber) { bigNumberToBN(value: BigNumber) {
return new BN(value.toString(), 10); return new BN(value.toString(), 10);
}, },
consoleLog(message: string): void {
// tslint:disable-next-line: no-console
console.log(message);
},
spawnSwitchErr(name: string, value: any): Error { spawnSwitchErr(name: string, value: any): Error {
return new Error(`Unexpected switch value: ${value} encountered for ${name}`); return new Error(`Unexpected switch value: ${value} encountered for ${name}`);
}, },

View File

@ -1,5 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
import { logUtils } from '@0xproject/utils';
import chalk from 'chalk'; import chalk from 'chalk';
import * as fs from 'fs'; import * as fs from 'fs';
import { sync as globSync } from 'glob'; import { sync as globSync } from 'glob';
@ -62,7 +63,7 @@ const args = yargs
function registerPartials(partialsGlob: string) { function registerPartials(partialsGlob: string) {
const partialTemplateFileNames = globSync(partialsGlob); const partialTemplateFileNames = globSync(partialsGlob);
utils.log(`Found ${chalk.green(`${partialTemplateFileNames.length}`)} ${chalk.bold('partial')} templates`); logUtils.log(`Found ${chalk.green(`${partialTemplateFileNames.length}`)} ${chalk.bold('partial')} templates`);
for (const partialTemplateFileName of partialTemplateFileNames) { for (const partialTemplateFileName of partialTemplateFileNames) {
const namedContent = utils.getNamedContent(partialTemplateFileName); const namedContent = utils.getNamedContent(partialTemplateFileName);
Handlebars.registerPartial(namedContent.name, namedContent.content); Handlebars.registerPartial(namedContent.name, namedContent.content);
@ -77,7 +78,7 @@ function writeOutputFile(name: string, renderedTsCode: string): void {
} }
const filePath = `${args.output}/${fileName}.ts`; const filePath = `${args.output}/${fileName}.ts`;
fs.writeFileSync(filePath, renderedTsCode); fs.writeFileSync(filePath, renderedTsCode);
utils.log(`Created: ${chalk.bold(filePath)}`); logUtils.log(`Created: ${chalk.bold(filePath)}`);
} }
Handlebars.registerHelper('parameterType', utils.solTypeToTsType.bind(utils, ParamKind.Input, args.backend)); Handlebars.registerHelper('parameterType', utils.solTypeToTsType.bind(utils, ParamKind.Input, args.backend));
@ -91,17 +92,17 @@ const template = Handlebars.compile<ContextData>(mainTemplate.content);
const abiFileNames = globSync(args.abis); const abiFileNames = globSync(args.abis);
if (_.isEmpty(abiFileNames)) { if (_.isEmpty(abiFileNames)) {
utils.log(`${chalk.red(`No ABI files found.`)}`); logUtils.log(`${chalk.red(`No ABI files found.`)}`);
utils.log(`Please make sure you've passed the correct folder name and that the files have logUtils.log(`Please make sure you've passed the correct folder name and that the files have
${chalk.bold('*.json')} extensions`); ${chalk.bold('*.json')} extensions`);
process.exit(1); process.exit(1);
} else { } else {
utils.log(`Found ${chalk.green(`${abiFileNames.length}`)} ${chalk.bold('ABI')} files`); logUtils.log(`Found ${chalk.green(`${abiFileNames.length}`)} ${chalk.bold('ABI')} files`);
mkdirp.sync(args.output); mkdirp.sync(args.output);
} }
for (const abiFileName of abiFileNames) { for (const abiFileName of abiFileNames) {
const namedContent = utils.getNamedContent(abiFileName); const namedContent = utils.getNamedContent(abiFileName);
utils.log(`Processing: ${chalk.bold(namedContent.name)}...`); logUtils.log(`Processing: ${chalk.bold(namedContent.name)}...`);
const parsedContent = JSON.parse(namedContent.content); const parsedContent = JSON.parse(namedContent.content);
let ABI; let ABI;
if (_.isArray(parsedContent)) { if (_.isArray(parsedContent)) {
@ -112,8 +113,8 @@ for (const abiFileName of abiFileNames) {
ABI = parsedContent.networks[args.networkId].abi; // 0x contracts package artifact ABI = parsedContent.networks[args.networkId].abi; // 0x contracts package artifact
} }
if (_.isUndefined(ABI)) { if (_.isUndefined(ABI)) {
utils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`); logUtils.log(`${chalk.red(`ABI not found in ${abiFileName}.`)}`);
utils.log( logUtils.log(
`Please make sure your ABI file is either an array with ABI entries or a truffle artifact or 0x deployer artifact`, `Please make sure your ABI file is either an array with ABI entries or a truffle artifact or 0x deployer artifact`,
); );
process.exit(1); process.exit(1);

View File

@ -73,9 +73,6 @@ export const utils = {
isObjectType(tsType: string): boolean { isObjectType(tsType: string): boolean {
return /^{.*}$/.test(tsType); return /^{.*}$/.test(tsType);
}, },
log(...args: any[]): void {
console.log(...args); // tslint:disable-line:no-console
},
getPartialNameFromFileName(filename: string): string { getPartialNameFromFileName(filename: string): string {
const name = path.parse(filename).name; const name = path.parse(filename).name;
return name; return name;

View File

@ -1,4 +1,4 @@
import { promisify } from '@0xproject/utils'; import { logUtils, promisify } from '@0xproject/utils';
import * as ethUtil from 'ethereumjs-util'; import * as ethUtil from 'ethereumjs-util';
import * as fs from 'fs'; import * as fs from 'fs';
import 'isomorphic-fetch'; import 'isomorphic-fetch';
@ -59,9 +59,9 @@ export class Compiler {
}; };
const source = await fsWrapper.readFileAsync(contentPath, opts); const source = await fsWrapper.readFileAsync(contentPath, opts);
sources[fileName] = source; sources[fileName] = source;
utils.consoleLog(`Reading ${fileName} source...`); logUtils.log(`Reading ${fileName} source...`);
} catch (err) { } catch (err) {
utils.consoleLog(`Could not find file at ${contentPath}`); logUtils.log(`Could not find file at ${contentPath}`);
} }
} else { } else {
try { try {
@ -71,7 +71,7 @@ export class Compiler {
...nestedSources, ...nestedSources,
}; };
} catch (err) { } catch (err) {
utils.consoleLog(`${contentPath} is not a directory or ${constants.SOLIDITY_FILE_EXTENSION} file`); logUtils.log(`${contentPath} is not a directory or ${constants.SOLIDITY_FILE_EXTENSION} file`);
} }
} }
} }
@ -164,7 +164,7 @@ export class Compiler {
}); });
await Promise.all(_.map(fileNames, async fileName => this._compileContractAsync(fileName))); await Promise.all(_.map(fileNames, async fileName => this._compileContractAsync(fileName)));
this._solcErrors.forEach(errMsg => { this._solcErrors.forEach(errMsg => {
utils.consoleLog(errMsg); logUtils.log(errMsg);
}); });
} }
/** /**
@ -195,7 +195,7 @@ export class Compiler {
if (isCompilerAvailableLocally) { if (isCompilerAvailableLocally) {
solcjs = fs.readFileSync(compilerBinFilename).toString(); solcjs = fs.readFileSync(compilerBinFilename).toString();
} else { } else {
utils.consoleLog(`Downloading ${fullSolcVersion}...`); logUtils.log(`Downloading ${fullSolcVersion}...`);
const url = `${constants.BASE_COMPILER_URL}${fullSolcVersion}`; const url = `${constants.BASE_COMPILER_URL}${fullSolcVersion}`;
const response = await fetch(url); const response = await fetch(url);
if (response.status !== 200) { if (response.status !== 200) {
@ -206,7 +206,7 @@ export class Compiler {
} }
const solcInstance = solc.setupMethods(requireFromString(solcjs, compilerBinFilename)); const solcInstance = solc.setupMethods(requireFromString(solcjs, compilerBinFilename));
utils.consoleLog(`Compiling ${fileName}...`); logUtils.log(`Compiling ${fileName}...`);
const source = this._contractSources[fileName]; const source = this._contractSources[fileName];
const input = { const input = {
[fileName]: source, [fileName]: source,
@ -270,7 +270,7 @@ export class Compiler {
const artifactString = utils.stringifyWithFormatting(newArtifact); const artifactString = utils.stringifyWithFormatting(newArtifact);
const currentArtifactPath = `${this._artifactsDir}/${contractName}.json`; const currentArtifactPath = `${this._artifactsDir}/${contractName}.json`;
await fsWrapper.writeFileAsync(currentArtifactPath, artifactString); await fsWrapper.writeFileAsync(currentArtifactPath, artifactString);
utils.consoleLog(`${fileName} artifact saved!`); logUtils.log(`${fileName} artifact saved!`);
} }
/** /**
* Sets the source tree hash for a file and its dependencies. * Sets the source tree hash for a file and its dependencies.
@ -323,7 +323,7 @@ export class Compiler {
*/ */
private async _createArtifactsDirIfDoesNotExistAsync(): Promise<void> { private async _createArtifactsDirIfDoesNotExistAsync(): Promise<void> {
if (!fsWrapper.doesPathExistSync(this._artifactsDir)) { if (!fsWrapper.doesPathExistSync(this._artifactsDir)) {
utils.consoleLog('Creating artifacts directory...'); logUtils.log('Creating artifacts directory...');
await fsWrapper.mkdirAsync(this._artifactsDir); await fsWrapper.mkdirAsync(this._artifactsDir);
} }
} }
@ -344,7 +344,7 @@ export class Compiler {
contractArtifact = JSON.parse(contractArtifactString); contractArtifact = JSON.parse(contractArtifactString);
return contractArtifact; return contractArtifact;
} catch (err) { } catch (err) {
utils.consoleLog(`Artifact for ${fileName} does not exist`); logUtils.log(`Artifact for ${fileName} does not exist`);
return undefined; return undefined;
} }
} }

View File

@ -1,4 +1,5 @@
import { AbiType, TxData } from '@0xproject/types'; import { AbiType, TxData } from '@0xproject/types';
import { logUtils } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as Web3 from 'web3'; import * as Web3 from 'web3';
@ -74,7 +75,7 @@ export class Deployer {
); );
} }
const web3ContractInstance = await this._deployFromAbiAsync(abi, args, txData); const web3ContractInstance = await this._deployFromAbiAsync(abi, args, txData);
utils.consoleLog(`${contractName}.sol successfully deployed at ${web3ContractInstance.address}`); logUtils.log(`${contractName}.sol successfully deployed at ${web3ContractInstance.address}`);
const contractInstance = new Contract(web3ContractInstance, this._defaults); const contractInstance = new Contract(web3ContractInstance, this._defaults);
return contractInstance; return contractInstance;
} }
@ -107,7 +108,7 @@ export class Deployer {
if (err) { if (err) {
reject(err); reject(err);
} else if (_.isUndefined(res.address) && !_.isUndefined(res.transactionHash)) { } else if (_.isUndefined(res.address) && !_.isUndefined(res.transactionHash)) {
utils.consoleLog(`transactionHash: ${res.transactionHash}`); logUtils.log(`transactionHash: ${res.transactionHash}`);
} else { } else {
resolve(res); resolve(res);
} }

View File

@ -1,9 +1,4 @@
export const utils = { export const utils = {
consoleLog(message: string): void {
/* tslint:disable */
console.log(message);
/* tslint:enable */
},
stringifyWithFormatting(obj: any): string { stringifyWithFormatting(obj: any): string {
const jsonReplacer: null = null; const jsonReplacer: null = null;
const numberOfJsonSpaces = 4; const numberOfJsonSpaces = 4;

View File

@ -28,6 +28,7 @@
"typescript": "2.7.1" "typescript": "2.7.1"
}, },
"dependencies": { "dependencies": {
"@0xproject/utils": "^0.4.1",
"chalk": "^2.3.0", "chalk": "^2.3.0",
"glob": "^7.1.2", "glob": "^7.1.2",
"lodash": "^4.17.4" "lodash": "^4.17.4"

View File

@ -1,5 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
import { logUtils } from '@0xproject/utils';
import chalk from 'chalk'; import chalk from 'chalk';
import * as fs from 'fs'; import * as fs from 'fs';
import { sync as globSync } from 'glob'; import { sync as globSync } from 'glob';
@ -17,10 +18,6 @@ interface VersionsByDependency {
const PACKAGE_JSON_GLOB = '../*/package.json'; const PACKAGE_JSON_GLOB = '../*/package.json';
function log(...args: any[]) {
console.log(...args); // tslint:disable-line:no-console
}
function getDependencies(path: string): Dependencies { function getDependencies(path: string): Dependencies {
const file = fs.readFileSync(path).toString(); const file = fs.readFileSync(path).toString();
const parsed = JSON.parse(file); const parsed = JSON.parse(file);
@ -48,9 +45,9 @@ _.map(versionsByDependency, (versions: Versions, depName: string) => {
if (_.uniq(_.values(versions)).length === 1) { if (_.uniq(_.values(versions)).length === 1) {
delete versionsByDependency[depName]; delete versionsByDependency[depName];
} else { } else {
log(chalk.bold(depName)); logUtils.log(chalk.bold(depName));
_.map(versions, (version: string, packageName: string) => { _.map(versions, (version: string, packageName: string) => {
log(`├── ${packageName} -> ${version}`); logUtils.log(`├── ${packageName} -> ${version}`);
}); });
} }
}); });

View File

@ -3,5 +3,5 @@
"compilerOptions": { "compilerOptions": {
"outDir": "lib" "outDir": "lib"
}, },
"include": ["./src/**/*"] "include": ["./src/**/*", "../../node_modules/web3-typescript-typings/index.d.ts"]
} }

View File

@ -35,6 +35,7 @@
}, },
"dependencies": { "dependencies": {
"@0xproject/react-shared": "^0.0.1", "@0xproject/react-shared": "^0.0.1",
"@0xproject/utils": "^0.4.1",
"basscss": "^8.0.3", "basscss": "^8.0.3",
"compare-versions": "^3.0.1", "compare-versions": "^3.0.1",
"lodash": "^4.17.4", "lodash": "^4.17.4",

View File

@ -1,3 +1,4 @@
import { logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as React from 'react'; import * as React from 'react';
@ -16,7 +17,7 @@ export interface CustomEnumProps {
export function CustomEnum(props: CustomEnumProps) { export function CustomEnum(props: CustomEnumProps) {
const type = props.type; const type = props.type;
if (!_.startsWith(type.defaultValue, STRING_ENUM_CODE_PREFIX)) { if (!_.startsWith(type.defaultValue, STRING_ENUM_CODE_PREFIX)) {
utils.consoleLog('We do not yet support `Variable` types that are not strEnums'); logUtils.log('We do not yet support `Variable` types that are not strEnums');
return null; return null;
} }
// Remove the prefix and postfix, leaving only the strEnum values without quotes. // Remove the prefix and postfix, leaving only the strEnum values without quotes.

View File

@ -1,9 +1,4 @@
export const utils = { export const utils = {
consoleLog(message: string) {
/* tslint:disable */
console.log(message);
/* tslint:enable */
},
spawnSwitchErr(name: string, value: any) { spawnSwitchErr(name: string, value: any) {
return new Error(`Unexpected switch value: ${value} encountered for ${name}`); return new Error(`Unexpected switch value: ${value} encountered for ${name}`);
}, },

View File

@ -9,5 +9,5 @@
"*": ["node_modules/@types/*", "*"] "*": ["node_modules/@types/*", "*"]
} }
}, },
"include": ["./src/ts/**/*"] "include": ["./src/ts/**/*", "../../node_modules/web3-typescript-typings/index.d.ts"]
} }

View File

@ -1,7 +1,7 @@
#!/usr/bin/env node #!/usr/bin/env node
import { assert } from '@0xproject/assert'; import { assert } from '@0xproject/assert';
import { Schema, schemas } from '@0xproject/json-schemas'; import { Schema, schemas } from '@0xproject/json-schemas';
import { promisify } from '@0xproject/utils'; import { logUtils, promisify } from '@0xproject/utils';
import chalk from 'chalk'; import chalk from 'chalk';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as newman from 'newman'; import * as newman from 'newman';
@ -10,7 +10,6 @@ import * as yargs from 'yargs';
import * as sraReportCollectionJSON from '../postman_configs/collections/sra_report.postman_collection.json'; import * as sraReportCollectionJSON from '../postman_configs/collections/sra_report.postman_collection.json';
import { postmanEnvironmentFactory } from './postman_environment_factory'; import { postmanEnvironmentFactory } from './postman_environment_factory';
import { utils } from './utils';
const newmanRunAsync = promisify<void>(newman.run); const newmanRunAsync = promisify<void>(newman.run);
const DEFAULT_NETWORK_ID = 1; const DEFAULT_NETWORK_ID = 1;
@ -66,12 +65,12 @@ const args = yargs
try { try {
assert.isWebUri('args', args.endpointUrl); assert.isWebUri('args', args.endpointUrl);
} catch (err) { } catch (err) {
utils.log(`${chalk.red(`Invalid url format:`)} ${args.endpointUrl}`); logUtils.log(`${chalk.red(`Invalid url format:`)} ${args.endpointUrl}`);
process.exit(1); process.exit(1);
} }
if (!_.includes(SUPPORTED_NETWORK_IDS, args.networkId)) { if (!_.includes(SUPPORTED_NETWORK_IDS, args.networkId)) {
utils.log(`${chalk.red(`Unsupported network id:`)} ${args.networkId}`); logUtils.log(`${chalk.red(`Unsupported network id:`)} ${args.networkId}`);
utils.log(`${chalk.bold(`Supported network ids:`)} ${SUPPORTED_NETWORK_IDS}`); logUtils.log(`${chalk.bold(`Supported network ids:`)} ${SUPPORTED_NETWORK_IDS}`);
process.exit(1); process.exit(1);
} }
const mainAsync = async () => { const mainAsync = async () => {
@ -99,4 +98,4 @@ const mainAsync = async () => {
}; };
await newmanRunAsync(newmanRunOptions); await newmanRunAsync(newmanRunOptions);
}; };
mainAsync().catch(utils.log); mainAsync().catch(logUtils.log);

View File

@ -1,6 +1,7 @@
import { SignedOrder, ZeroEx } from '0x.js'; import { SignedOrder, ZeroEx } from '0x.js';
import { HttpClient } from '@0xproject/connect'; import { HttpClient } from '@0xproject/connect';
import { Schema, schemas as schemasByName } from '@0xproject/json-schemas'; import { Schema, schemas as schemasByName } from '@0xproject/json-schemas';
import { logUtils } from '@0xproject/utils';
import chalk from 'chalk'; import chalk from 'chalk';
import * as _ from 'lodash'; import * as _ from 'lodash';
@ -8,7 +9,6 @@ import { addresses as kovanAddresses } from './contract_addresses/kovan_addresse
import { addresses as mainnetAddresses } from './contract_addresses/mainnet_addresses'; import { addresses as mainnetAddresses } from './contract_addresses/mainnet_addresses';
import { addresses as rinkebyAddresses } from './contract_addresses/rinkeby_addresses'; import { addresses as rinkebyAddresses } from './contract_addresses/rinkeby_addresses';
import { addresses as ropstenAddresses } from './contract_addresses/ropsten_addresses'; import { addresses as ropstenAddresses } from './contract_addresses/ropsten_addresses';
import { utils } from './utils';
const ENVIRONMENT_NAME = 'SRA Report'; const ENVIRONMENT_NAME = 'SRA Report';
@ -81,7 +81,7 @@ async function createOrderEnvironmentValuesAsync(url: string) {
createEnvironmentValue('orderHash', ZeroEx.getOrderHashHex(orderIfExists)), createEnvironmentValue('orderHash', ZeroEx.getOrderHashHex(orderIfExists)),
]; ];
} else { } else {
utils.log(`${chalk.red(`No orders from /orders found`)}`); logUtils.log(`${chalk.red(`No orders from /orders found`)}`);
return [ return [
createEnvironmentValue('order', ''), createEnvironmentValue('order', ''),
createEnvironmentValue('orderMaker', ''), createEnvironmentValue('orderMaker', ''),

View File

@ -1,8 +1,7 @@
import { intervalUtils } from '@0xproject/utils'; import { intervalUtils, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { errorReporter } from './error_reporter'; import { errorReporter } from './error_reporter';
import { utils } from './utils';
const MAX_QUEUE_SIZE = 500; const MAX_QUEUE_SIZE = 500;
const DEFAULT_QUEUE_INTERVAL_MS = 1000; const DEFAULT_QUEUE_INTERVAL_MS = 1000;
@ -45,7 +44,7 @@ export class DispatchQueue {
}, },
this._queueIntervalMs, this._queueIntervalMs,
(err: Error) => { (err: Error) => {
utils.consoleLog(`Unexpected err: ${err} - ${JSON.stringify(err)}`); logUtils.log(`Unexpected err: ${err} - ${JSON.stringify(err)}`);
// tslint:disable-next-line:no-floating-promises // tslint:disable-next-line:no-floating-promises
errorReporter.reportAsync(err); errorReporter.reportAsync(err);
}, },

View File

@ -1,11 +1,10 @@
import { ZeroEx } from '0x.js'; import { ZeroEx } from '0x.js';
import { BigNumber, promisify } from '@0xproject/utils'; import { BigNumber, logUtils, promisify } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as Web3 from 'web3'; import * as Web3 from 'web3';
import { configs } from './configs'; import { configs } from './configs';
import { errorReporter } from './error_reporter'; import { errorReporter } from './error_reporter';
import { utils } from './utils';
const DISPENSE_AMOUNT_ETHER = 0.1; const DISPENSE_AMOUNT_ETHER = 0.1;
const DISPENSE_AMOUNT_TOKEN = 0.1; const DISPENSE_AMOUNT_TOKEN = 0.1;
@ -15,11 +14,11 @@ const DISPENSE_MAX_AMOUNT_ETHER = 2;
export const dispenseAssetTasks = { export const dispenseAssetTasks = {
dispenseEtherTask(recipientAddress: string, web3: Web3) { dispenseEtherTask(recipientAddress: string, web3: Web3) {
return async () => { return async () => {
utils.consoleLog(`Processing ETH ${recipientAddress}`); logUtils.log(`Processing ETH ${recipientAddress}`);
const userBalance = await promisify<BigNumber>(web3.eth.getBalance)(recipientAddress); const userBalance = await promisify<BigNumber>(web3.eth.getBalance)(recipientAddress);
const maxAmountInWei = new BigNumber(web3.toWei(DISPENSE_MAX_AMOUNT_ETHER, 'ether')); const maxAmountInWei = new BigNumber(web3.toWei(DISPENSE_MAX_AMOUNT_ETHER, 'ether'));
if (userBalance.greaterThanOrEqualTo(maxAmountInWei)) { if (userBalance.greaterThanOrEqualTo(maxAmountInWei)) {
utils.consoleLog( logUtils.log(
`User exceeded ETH balance maximum (${maxAmountInWei}) ${recipientAddress} ${userBalance} `, `User exceeded ETH balance maximum (${maxAmountInWei}) ${recipientAddress} ${userBalance} `,
); );
return; return;
@ -30,12 +29,12 @@ export const dispenseAssetTasks = {
to: recipientAddress, to: recipientAddress,
value: web3.toWei(DISPENSE_AMOUNT_ETHER, 'ether'), value: web3.toWei(DISPENSE_AMOUNT_ETHER, 'ether'),
}); });
utils.consoleLog(`Sent ${DISPENSE_AMOUNT_ETHER} ETH to ${recipientAddress} tx: ${txHash}`); logUtils.log(`Sent ${DISPENSE_AMOUNT_ETHER} ETH to ${recipientAddress} tx: ${txHash}`);
}; };
}, },
dispenseTokenTask(recipientAddress: string, tokenSymbol: string, zeroEx: ZeroEx) { dispenseTokenTask(recipientAddress: string, tokenSymbol: string, zeroEx: ZeroEx) {
return async () => { return async () => {
utils.consoleLog(`Processing ${tokenSymbol} ${recipientAddress}`); logUtils.log(`Processing ${tokenSymbol} ${recipientAddress}`);
const amountToDispense = new BigNumber(DISPENSE_AMOUNT_TOKEN); const amountToDispense = new BigNumber(DISPENSE_AMOUNT_TOKEN);
const token = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync(tokenSymbol); const token = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync(tokenSymbol);
if (_.isUndefined(token)) { if (_.isUndefined(token)) {
@ -48,7 +47,7 @@ export const dispenseAssetTasks = {
token.decimals, token.decimals,
); );
if (userBalanceBaseUnits.greaterThanOrEqualTo(maxAmountBaseUnits)) { if (userBalanceBaseUnits.greaterThanOrEqualTo(maxAmountBaseUnits)) {
utils.consoleLog( logUtils.log(
`User exceeded token balance maximum (${maxAmountBaseUnits}) ${recipientAddress} ${userBalanceBaseUnits} `, `User exceeded token balance maximum (${maxAmountBaseUnits}) ${recipientAddress} ${userBalanceBaseUnits} `,
); );
return; return;
@ -59,7 +58,7 @@ export const dispenseAssetTasks = {
recipientAddress, recipientAddress,
baseUnitAmount, baseUnitAmount,
); );
utils.consoleLog(`Sent ${amountToDispense} ZRX to ${recipientAddress} tx: ${txHash}`); logUtils.log(`Sent ${amountToDispense} ZRX to ${recipientAddress} tx: ${txHash}`);
}; };
}, },
}; };

View File

@ -1,8 +1,8 @@
import { logUtils } from '@0xproject/utils';
import * as express from 'express'; import * as express from 'express';
import rollbar = require('rollbar'); import rollbar = require('rollbar');
import { configs } from './configs'; import { configs } from './configs';
import { utils } from './utils';
export const errorReporter = { export const errorReporter = {
setup() { setup() {
@ -11,7 +11,7 @@ export const errorReporter = {
}); });
rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY); rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY);
process.on('unhandledRejection', async (err: Error) => { process.on('unhandledRejection', async (err: Error) => {
utils.consoleLog(`Uncaught exception ${err}. Stack: ${err.stack}`); logUtils.log(`Uncaught exception ${err}. Stack: ${err.stack}`);
await this.reportAsync(err); await this.reportAsync(err);
process.exit(1); process.exit(1);
}); });
@ -23,7 +23,7 @@ export const errorReporter = {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
rollbar.handleError(err, req, (rollbarErr: Error) => { rollbar.handleError(err, req, (rollbarErr: Error) => {
if (rollbarErr) { if (rollbarErr) {
utils.consoleLog(`Error reporting to rollbar, ignoring: ${rollbarErr}`); logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`);
reject(rollbarErr); reject(rollbarErr);
} else { } else {
resolve(); resolve();

View File

@ -1,5 +1,5 @@
import { Order, SignedOrder, ZeroEx } from '0x.js'; import { Order, SignedOrder, ZeroEx } from '0x.js';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as express from 'express'; import * as express from 'express';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as Web3 from 'web3'; import * as Web3 from 'web3';
@ -19,7 +19,6 @@ import { DispatchQueue } from './dispatch_queue';
import { dispenseAssetTasks } from './dispense_asset_tasks'; import { dispenseAssetTasks } from './dispense_asset_tasks';
import { idManagement } from './id_management'; import { idManagement } from './id_management';
import { rpcUrls } from './rpc_urls'; import { rpcUrls } from './rpc_urls';
import { utils } from './utils';
interface NetworkConfig { interface NetworkConfig {
dispatchQueue: DispatchQueue; dispatchQueue: DispatchQueue;
@ -118,7 +117,7 @@ export class Handler {
res.status(503).send('QUEUE_IS_FULL'); res.status(503).send('QUEUE_IS_FULL');
return; return;
} }
utils.consoleLog(`Added ${recipient} to queue: ${requestedAssetType} networkId: ${networkId}`); logUtils.log(`Added ${recipient} to queue: ${requestedAssetType} networkId: ${networkId}`);
res.status(200).end(); res.status(200).end();
} }
private async _dispenseOrder(req: express.Request, res: express.Response, requestedAssetType: RequestedAssetType) { private async _dispenseOrder(req: express.Request, res: express.Response, requestedAssetType: RequestedAssetType) {
@ -163,7 +162,7 @@ export class Handler {
}; };
const signedOrderHash = ZeroEx.getOrderHashHex(signedOrder); const signedOrderHash = ZeroEx.getOrderHashHex(signedOrder);
const payload = JSON.stringify(signedOrder); const payload = JSON.stringify(signedOrder);
utils.consoleLog(`Dispensed signed order: ${payload}`); logUtils.log(`Dispensed signed order: ${payload}`);
res.status(200).send(payload); res.status(200).send(payload);
} }
} }

View File

@ -4,7 +4,6 @@ import * as _ from 'lodash';
import { configs } from './configs'; import { configs } from './configs';
import { rpcUrls } from './rpc_urls'; import { rpcUrls } from './rpc_urls';
import { utils } from './utils';
const DEFAULT_NETWORK_ID = 42; // kovan const DEFAULT_NETWORK_ID = 42; // kovan

View File

@ -1,7 +0,0 @@
export const utils = {
consoleLog(message: string) {
/* tslint:disable */
console.log(message);
/* tslint:enable */
},
};

View File

@ -6,6 +6,7 @@
}, },
"include": [ "include": [
"./src/ts/**/*", "./src/ts/**/*",
"../../node_modules/ethers-typescript-typings/index.d.ts",
"../../node_modules/types-bn/index.d.ts", "../../node_modules/types-bn/index.d.ts",
"../../node_modules/types-ethereumjs-util/index.d.ts", "../../node_modules/types-ethereumjs-util/index.d.ts",
"../../node_modules/web3-typescript-typings/index.d.ts" "../../node_modules/web3-typescript-typings/index.d.ts"

View File

@ -4,3 +4,4 @@ export { classUtils } from './class_utils';
export { intervalUtils } from './interval_utils'; export { intervalUtils } from './interval_utils';
export { BigNumber } from './configured_bignumber'; export { BigNumber } from './configured_bignumber';
export { AbiDecoder } from './abi_decoder'; export { AbiDecoder } from './abi_decoder';
export { logUtils } from './log_utils';

View File

@ -1,4 +1,4 @@
export const utils = { export const logUtils = {
log(...args: any[]): void { log(...args: any[]): void {
console.log(...args); // tslint:disable-line:no-console console.log(...args); // tslint:disable-line:no-console
}, },

View File

@ -23,7 +23,7 @@ import {
LedgerWalletSubprovider, LedgerWalletSubprovider,
RedundantRPCSubprovider, RedundantRPCSubprovider,
} from '@0xproject/subproviders'; } from '@0xproject/subproviders';
import { BigNumber, intervalUtils, promisify } from '@0xproject/utils'; import { BigNumber, intervalUtils, logUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import * as React from 'react'; import * as React from 'react';
@ -405,7 +405,7 @@ export class Blockchain {
}, },
5000, 5000,
(err: Error) => { (err: Error) => {
utils.consoleLog(`Polling tokenBalance failed: ${err}`); logUtils.log(`Polling tokenBalance failed: ${err}`);
intervalUtils.clearAsyncExcludingInterval(tokenPollInterval); intervalUtils.clearAsyncExcludingInterval(tokenPollInterval);
reject(err); reject(err);
}, },
@ -822,7 +822,7 @@ export class Blockchain {
if (!_.isUndefined(contractAddress)) { if (!_.isUndefined(contractAddress)) {
const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress); const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress);
if (!doesContractExist) { if (!doesContractExist) {
utils.consoleLog(`Contract does not exist: ${artifact.contract_name} at ${contractAddress}`); logUtils.log(`Contract does not exist: ${artifact.contract_name} at ${contractAddress}`);
throw new Error(BlockchainCallErrs.ContractDoesNotExist); throw new Error(BlockchainCallErrs.ContractDoesNotExist);
} }
} }
@ -832,7 +832,7 @@ export class Blockchain {
return contractInstance; return contractInstance;
} catch (err) { } catch (err) {
const errMsg = `${err}`; const errMsg = `${err}`;
utils.consoleLog(`Notice: Error encountered: ${err} ${err.stack}`); logUtils.log(`Notice: Error encountered: ${err} ${err.stack}`);
if (_.includes(errMsg, 'not been deployed to detected network')) { if (_.includes(errMsg, 'not been deployed to detected network')) {
throw new Error(BlockchainCallErrs.ContractDoesNotExist); throw new Error(BlockchainCallErrs.ContractDoesNotExist);
} else { } else {

View File

@ -1,4 +1,4 @@
import { BigNumber, intervalUtils, promisify } from '@0xproject/utils'; import { BigNumber, intervalUtils, logUtils, promisify } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { Dispatcher } from 'ts/redux/dispatcher'; import { Dispatcher } from 'ts/redux/dispatcher';
@ -87,7 +87,7 @@ export class BlockchainWatcher {
}, },
5000, 5000,
(err: Error) => { (err: Error) => {
utils.consoleLog(`Watching network and balances failed: ${err.stack}`); logUtils.log(`Watching network and balances failed: ${err.stack}`);
this._stopEmittingNetworkConnectionAndUserBalanceStateAsync(); this._stopEmittingNetworkConnectionAndUserBalanceStateAsync();
}, },
); );

View File

@ -1,6 +1,6 @@
import { ZeroEx } from '0x.js'; import { ZeroEx } from '0x.js';
import { colors, constants as sharedConstants } from '@0xproject/react-shared'; import { colors, constants as sharedConstants } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import Dialog from 'material-ui/Dialog'; import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton'; import FlatButton from 'material-ui/FlatButton';
@ -239,7 +239,7 @@ export class LedgerConfigDialog extends React.Component<LedgerConfigDialogProps,
addressBalances.push(balanceInWei); addressBalances.push(balanceInWei);
} }
} catch (err) { } catch (err) {
utils.consoleLog(`Ledger error: ${JSON.stringify(err)}`); logUtils.log(`Ledger error: ${JSON.stringify(err)}`);
this.setState({ this.setState({
connectionErrMsg: 'Failed to connect. Follow the instructions and try again.', connectionErrMsg: 'Failed to connect. Follow the instructions and try again.',
}); });
@ -265,7 +265,7 @@ export class LedgerConfigDialog extends React.Component<LedgerConfigDialogProps,
private async _onConnectLedgerClickAsync() { private async _onConnectLedgerClickAsync() {
const isU2FSupported = await utils.isU2FSupportedAsync(); const isU2FSupported = await utils.isU2FSupportedAsync();
if (!isU2FSupported) { if (!isU2FSupported) {
utils.consoleLog(`U2F not supported in this browser`); logUtils.log(`U2F not supported in this browser`);
this.setState({ this.setState({
connectionErrMsg: 'U2F not supported by this browser. Try using Chrome.', connectionErrMsg: 'U2F not supported by this browser. Try using Chrome.',
}); });

View File

@ -1,5 +1,5 @@
import { ZeroEx } from '0x.js'; import { ZeroEx } from '0x.js';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import RaisedButton from 'material-ui/RaisedButton'; import RaisedButton from 'material-ui/RaisedButton';
import * as React from 'react'; import * as React from 'react';
@ -111,8 +111,8 @@ export class EthWethConversionButton extends React.Component<
if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) { if (_.includes(errMsg, BlockchainCallErrs.UserHasNoAssociatedAddresses)) {
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true); this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
} else if (!utils.didUserDenyWeb3Request(errMsg)) { } else if (!utils.didUserDenyWeb3Request(errMsg)) {
utils.consoleLog(`Unexpected error encountered: ${err}`); logUtils.log(`Unexpected error encountered: ${err}`);
utils.consoleLog(err.stack); logUtils.log(err.stack);
const errorMsg = const errorMsg =
direction === Side.Deposit direction === Side.Deposit
? 'Failed to wrap your ETH. Please try again.' ? 'Failed to wrap your ETH. Please try again.'

View File

@ -1,6 +1,6 @@
import { Order as ZeroExOrder, ZeroEx } from '0x.js'; import { Order as ZeroExOrder, ZeroEx } from '0x.js';
import { colors, constants as sharedConstants } from '@0xproject/react-shared'; import { colors, constants as sharedConstants } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as accounting from 'accounting'; import * as accounting from 'accounting';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { Card, CardHeader, CardText } from 'material-ui/Card'; import { Card, CardHeader, CardText } from 'material-ui/Card';
@ -403,7 +403,7 @@ export class FillOrder extends React.Component<FillOrderProps, FillOrderState> {
const validationResult = validator.validate(order, portalOrderSchema); const validationResult = validator.validate(order, portalOrderSchema);
if (validationResult.errors.length > 0) { if (validationResult.errors.length > 0) {
orderJSONErrMsg = 'Submitted order JSON is not a valid order'; orderJSONErrMsg = 'Submitted order JSON is not a valid order';
utils.consoleLog(`Unexpected order JSON validation error: ${validationResult.errors.join(', ')}`); logUtils.log(`Unexpected order JSON validation error: ${validationResult.errors.join(', ')}`);
return; return;
} }
parsedOrder = order; parsedOrder = order;
@ -448,7 +448,7 @@ export class FillOrder extends React.Component<FillOrderProps, FillOrderState> {
this.props.dispatcher.updateUserSuppliedOrderCache(parsedOrder); this.props.dispatcher.updateUserSuppliedOrderCache(parsedOrder);
} }
} catch (err) { } catch (err) {
utils.consoleLog(`Validate order err: ${err}`); logUtils.log(`Validate order err: ${err}`);
if (!_.isEmpty(orderJSON)) { if (!_.isEmpty(orderJSON)) {
orderJSONErrMsg = 'Submitted order JSON is not valid JSON'; orderJSONErrMsg = 'Submitted order JSON is not valid JSON';
} }
@ -564,7 +564,7 @@ export class FillOrder extends React.Component<FillOrderProps, FillOrderState> {
return; return;
} }
globalErrMsg = 'Failed to fill order, please refresh and try again'; globalErrMsg = 'Failed to fill order, please refresh and try again';
utils.consoleLog(`${err}`); logUtils.log(`${err}`);
this.setState({ this.setState({
globalErrMsg, globalErrMsg,
}); });
@ -635,7 +635,7 @@ export class FillOrder extends React.Component<FillOrderProps, FillOrderState> {
} }
analytics.logEvent('Portal', 'Cancel Order Failure', eventLabel, parsedOrder.signedOrder.makerTokenAmount); analytics.logEvent('Portal', 'Cancel Order Failure', eventLabel, parsedOrder.signedOrder.makerTokenAmount);
globalErrMsg = 'Failed to cancel order, please refresh and try again'; globalErrMsg = 'Failed to cancel order, please refresh and try again';
utils.consoleLog(`${err}`); logUtils.log(`${err}`);
this.setState({ this.setState({
globalErrMsg, globalErrMsg,
}); });

View File

@ -1,6 +1,6 @@
import { ECSignature, Order, ZeroEx } from '0x.js'; import { ECSignature, Order, ZeroEx } from '0x.js';
import { colors, constants as sharedConstants } from '@0xproject/react-shared'; import { colors, constants as sharedConstants } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import Dialog from 'material-ui/Dialog'; import Dialog from 'material-ui/Dialog';
import Divider from 'material-ui/Divider'; import Divider from 'material-ui/Divider';
@ -326,7 +326,7 @@ export class GenerateOrderForm extends React.Component<GenerateOrderFormProps, G
const validationResult = validator.validate(order, portalOrderSchema); const validationResult = validator.validate(order, portalOrderSchema);
if (validationResult.errors.length > 0) { if (validationResult.errors.length > 0) {
globalErrMsg = 'Order signing failed. Please refresh and try again'; globalErrMsg = 'Order signing failed. Please refresh and try again';
utils.consoleLog(`Unexpected error occured: Order validation failed: logUtils.log(`Unexpected error occured: Order validation failed:
${validationResult.errors}`); ${validationResult.errors}`);
} }
} catch (err) { } catch (err) {
@ -335,8 +335,8 @@ export class GenerateOrderForm extends React.Component<GenerateOrderFormProps, G
globalErrMsg = 'User denied sign request'; globalErrMsg = 'User denied sign request';
} else { } else {
globalErrMsg = 'An unexpected error occured. Please try refreshing the page'; globalErrMsg = 'An unexpected error occured. Please try refreshing the page';
utils.consoleLog(`Unexpected error occured: ${err}`); logUtils.log(`Unexpected error occured: ${err}`);
utils.consoleLog(err.stack); logUtils.log(err.stack);
await errorReporter.reportAsync(err); await errorReporter.reportAsync(err);
} }
} }

View File

@ -1,5 +1,5 @@
import { constants as sharedConstants } from '@0xproject/react-shared'; import { constants as sharedConstants } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import Toggle from 'material-ui/Toggle'; import Toggle from 'material-ui/Toggle';
import * as React from 'react'; import * as React from 'react';
@ -93,8 +93,8 @@ export class AllowanceToggle extends React.Component<AllowanceToggleProps, Allow
if (utils.didUserDenyWeb3Request(errMsg)) { if (utils.didUserDenyWeb3Request(errMsg)) {
return; return;
} }
utils.consoleLog(`Unexpected error encountered: ${err}`); logUtils.log(`Unexpected error encountered: ${err}`);
utils.consoleLog(err.stack); logUtils.log(err.stack);
this.props.onErrorOccurred(BalanceErrs.allowanceSettingFailed); this.props.onErrorOccurred(BalanceErrs.allowanceSettingFailed);
await errorReporter.reportAsync(err); await errorReporter.reportAsync(err);
} }

View File

@ -1,5 +1,5 @@
import { ECSignature } from '0x.js'; import { ECSignature } from '0x.js';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import Paper from 'material-ui/Paper'; import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField'; import TextField from 'material-ui/TextField';
@ -153,7 +153,7 @@ You can see and fill it here: ${this.state.shareLink}`);
const bodyObj = JSON.parse(responseBody); const bodyObj = JSON.parse(responseBody);
if (response.status !== 200 || bodyObj.status_code !== 200) { if (response.status !== 200 || bodyObj.status_code !== 200) {
// TODO: Show error message in UI // TODO: Show error message in UI
utils.consoleLog(`Unexpected status code: ${response.status} -> ${responseBody}`); logUtils.log(`Unexpected status code: ${response.status} -> ${responseBody}`);
await errorReporter.reportAsync(new Error(`Bitly returned non-200: ${JSON.stringify(response)}`)); await errorReporter.reportAsync(new Error(`Bitly returned non-200: ${JSON.stringify(response)}`));
return ''; return '';
} }

View File

@ -1,5 +1,5 @@
import { colors } from '@0xproject/react-shared'; import { colors } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import CircularProgress from 'material-ui/CircularProgress'; import CircularProgress from 'material-ui/CircularProgress';
import Paper from 'material-ui/Paper'; import Paper from 'material-ui/Paper';
@ -374,7 +374,7 @@ export class Portal extends React.Component<PortalAllProps, PortalAllState> {
const order = JSON.parse(decodeURIComponent(orderPair[1])); const order = JSON.parse(decodeURIComponent(orderPair[1]));
const validationResult = validator.validate(order, portalOrderSchema); const validationResult = validator.validate(order, portalOrderSchema);
if (validationResult.errors.length > 0) { if (validationResult.errors.length > 0) {
utils.consoleLog(`Invalid shared order: ${validationResult.errors}`); logUtils.log(`Invalid shared order: ${validationResult.errors}`);
return undefined; return undefined;
} }
return order; return order;

View File

@ -1,4 +1,4 @@
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import RaisedButton from 'material-ui/RaisedButton'; import RaisedButton from 'material-ui/RaisedButton';
import * as React from 'react'; import * as React from 'react';
@ -77,8 +77,8 @@ export class SendButton extends React.Component<SendButtonProps, SendButtonState
this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true); this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
return; return;
} else if (!utils.didUserDenyWeb3Request(errMsg)) { } else if (!utils.didUserDenyWeb3Request(errMsg)) {
utils.consoleLog(`Unexpected error encountered: ${err}`); logUtils.log(`Unexpected error encountered: ${err}`);
utils.consoleLog(err.stack); logUtils.log(err.stack);
this.props.onError(); this.props.onError();
await errorReporter.reportAsync(err); await errorReporter.reportAsync(err);
} }

View File

@ -7,7 +7,7 @@ import {
Styles, Styles,
utils as sharedUtils, utils as sharedUtils,
} from '@0xproject/react-shared'; } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils'; import { BigNumber, logUtils } from '@0xproject/utils';
import DharmaLoanFrame from 'dharma-loan-frame'; import DharmaLoanFrame from 'dharma-loan-frame';
import * as _ from 'lodash'; import * as _ from 'lodash';
import Dialog from 'material-ui/Dialog'; import Dialog from 'material-ui/Dialog';
@ -591,8 +591,8 @@ export class TokenBalances extends React.Component<TokenBalancesProps, TokenBala
if (utils.didUserDenyWeb3Request(errMsg)) { if (utils.didUserDenyWeb3Request(errMsg)) {
return false; return false;
} }
utils.consoleLog(`Unexpected error encountered: ${err}`); logUtils.log(`Unexpected error encountered: ${err}`);
utils.consoleLog(err.stack); logUtils.log(err.stack);
this.setState({ this.setState({
errorType: BalanceErrs.mintingFailed, errorType: BalanceErrs.mintingFailed,
}); });
@ -623,7 +623,7 @@ export class TokenBalances extends React.Component<TokenBalancesProps, TokenBala
); );
const responseBody = await response.text(); const responseBody = await response.text();
if (response.status !== constants.SUCCESS_STATUS) { if (response.status !== constants.SUCCESS_STATUS) {
utils.consoleLog(`Unexpected status code: ${response.status} -> ${responseBody}`); logUtils.log(`Unexpected status code: ${response.status} -> ${responseBody}`);
const errorType = const errorType =
response.status === constants.UNAVAILABLE_STATUS response.status === constants.UNAVAILABLE_STATUS
? BalanceErrs.faucetQueueIsFull ? BalanceErrs.faucetQueueIsFull

View File

@ -8,6 +8,7 @@ import {
Styles, Styles,
utils as sharedUtils, utils as sharedUtils,
} from '@0xproject/react-shared'; } from '@0xproject/react-shared';
import { logUtils } from '@0xproject/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import CircularProgress from 'material-ui/CircularProgress'; import CircularProgress from 'material-ui/CircularProgress';
import RaisedButton from 'material-ui/RaisedButton'; import RaisedButton from 'material-ui/RaisedButton';
@ -213,7 +214,7 @@ export class Wiki extends React.Component<WikiProps, WikiState> {
if (response.status !== 200) { if (response.status !== 200) {
// TODO: Show the user an error message when the wiki fail to load // TODO: Show the user an error message when the wiki fail to load
const errMsg = await response.text(); const errMsg = await response.text();
utils.consoleLog(`Failed to load wiki: ${response.status} ${errMsg}`); logUtils.log(`Failed to load wiki: ${response.status} ${errMsg}`);
return; return;
} }
const articlesBySection = await response.json(); const articlesBySection = await response.json();

View File

@ -1,4 +1,5 @@
import { DoxityDocObj, TypeDocNode } from '@0xproject/react-docs'; import { DoxityDocObj, TypeDocNode } from '@0xproject/react-docs';
import { logUtils } from '@0xproject/utils';
import findVersions = require('find-versions'); import findVersions = require('find-versions');
import * as _ from 'lodash'; import * as _ from 'lodash';
import { S3FileObject, VersionToFileName } from 'ts/types'; import { S3FileObject, VersionToFileName } from 'ts/types';
@ -20,7 +21,7 @@ export const docUtils = {
if (response.status !== 200) { if (response.status !== 200) {
// TODO: Show the user an error message when the docs fail to load // TODO: Show the user an error message when the docs fail to load
const errMsg = await response.text(); const errMsg = await response.text();
utils.consoleLog(`Failed to load JSON file list: ${response.status} ${errMsg}`); logUtils.log(`Failed to load JSON file list: ${response.status} ${errMsg}`);
throw new Error(errMsg); throw new Error(errMsg);
} }
const responseXML = await response.text(); const responseXML = await response.text();
@ -43,7 +44,7 @@ export const docUtils = {
if (response.status !== 200) { if (response.status !== 200) {
// TODO: Show the user an error message when the docs fail to load // TODO: Show the user an error message when the docs fail to load
const errMsg = await response.text(); const errMsg = await response.text();
utils.consoleLog(`Failed to load Doc JSON: ${response.status} ${errMsg}`); logUtils.log(`Failed to load Doc JSON: ${response.status} ${errMsg}`);
throw new Error(errMsg); throw new Error(errMsg);
} }
const jsonDocObj = await response.json(); const jsonDocObj = await response.json();

View File

@ -1,3 +1,4 @@
import { logUtils } from '@0xproject/utils';
import { Environments } from 'ts/types'; import { Environments } from 'ts/types';
import { configs } from 'ts/utils/configs'; import { configs } from 'ts/utils/configs';
import { constants } from 'ts/utils/constants'; import { constants } from 'ts/utils/constants';
@ -40,7 +41,7 @@ export const errorReporter = {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
rollbar.error(err, (rollbarErr: Error) => { rollbar.error(err, (rollbarErr: Error) => {
if (rollbarErr) { if (rollbarErr) {
utils.consoleLog(`Error reporting to rollbar, ignoring: ${rollbarErr}`); logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`);
// We never want to reject and cause the app to throw because of rollbar // We never want to reject and cause the app to throw because of rollbar
resolve(); resolve();
} else { } else {

View File

@ -95,11 +95,6 @@ export const utils = {
}; };
return order; return order;
}, },
consoleLog(message: string) {
/* tslint:disable */
console.log(message);
/* tslint:enable */
},
async sleepAsync(ms: number) { async sleepAsync(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
}, },