From e744e4cd989bd3ae1070c59f7baa8097f18b8b06 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Fri, 22 Dec 2017 15:05:32 +0100 Subject: Apply prettier config --- packages/0x.js/src/utils/abi_decoder.ts | 15 ++- packages/0x.js/src/utils/assert.ts | 20 ++-- packages/0x.js/src/utils/decorators.ts | 21 ++-- .../0x.js/src/utils/exchange_transfer_simulator.ts | 45 ++++--- packages/0x.js/src/utils/filter_utils.ts | 22 ++-- packages/0x.js/src/utils/order_state_utils.ts | 56 +++++---- packages/0x.js/src/utils/order_validation_utils.ts | 131 ++++++++++++++------- packages/0x.js/src/utils/signature_utils.ts | 7 +- packages/0x.js/src/utils/utils.ts | 43 ++++--- 9 files changed, 236 insertions(+), 124 deletions(-) (limited to 'packages/0x.js/src/utils') diff --git a/packages/0x.js/src/utils/abi_decoder.ts b/packages/0x.js/src/utils/abi_decoder.ts index 6d15f1d6f..2d4e92558 100644 --- a/packages/0x.js/src/utils/abi_decoder.ts +++ b/packages/0x.js/src/utils/abi_decoder.ts @@ -3,11 +3,11 @@ import * as _ from 'lodash'; import * as Web3 from 'web3'; import * as SolidityCoder from 'web3/lib/solidity/coder'; -import {AbiType, ContractEventArgs, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes} from '../types'; +import { AbiType, ContractEventArgs, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes } from '../types'; export class AbiDecoder { private _savedABIs: Web3.AbiDefinition[] = []; - private _methodIds: {[signatureHash: string]: Web3.EventAbi} = {}; + private _methodIds: { [signatureHash: string]: Web3.EventAbi } = {}; private static _padZeros(address: string) { let formatted = address; if (_.startsWith(formatted, '0x')) { @@ -22,7 +22,8 @@ export class AbiDecoder { } // This method can only decode logs from the 0x & ERC20 smart contracts public tryToDecodeLogOrNoop( - log: Web3.LogEntry): LogWithDecodedArgs|RawLog { + log: Web3.LogEntry, + ): LogWithDecodedArgs | RawLog { const methodId = log.topics[0]; const event = this._methodIds[methodId]; if (_.isUndefined(event)) { @@ -42,9 +43,11 @@ export class AbiDecoder { let value = param.indexed ? log.topics[topicsIndex++] : decodedData[dataIndex++]; if (param.type === SolidityTypes.Address) { value = AbiDecoder._padZeros(new BigNumber(value).toString(16)); - } else if (param.type === SolidityTypes.Uint256 || - param.type === SolidityTypes.Uint8 || - param.type === SolidityTypes.Uint) { + } else if ( + param.type === SolidityTypes.Uint256 || + param.type === SolidityTypes.Uint8 || + param.type === SolidityTypes.Uint + ) { value = new BigNumber(value); } decodedParams[param.name] = value; diff --git a/packages/0x.js/src/utils/assert.ts b/packages/0x.js/src/utils/assert.ts index 86a6a7c01..b391a3347 100644 --- a/packages/0x.js/src/utils/assert.ts +++ b/packages/0x.js/src/utils/assert.ts @@ -1,14 +1,14 @@ -import {assert as sharedAssert} from '@0xproject/assert'; +import { assert as sharedAssert } from '@0xproject/assert'; // We need those two unused imports because they're actually used by sharedAssert which gets injected here // tslint:disable-next-line:no-unused-variable -import {Schema} from '@0xproject/json-schemas'; -import {Web3Wrapper} from '@0xproject/web3-wrapper'; +import { Schema } from '@0xproject/json-schemas'; +import { Web3Wrapper } from '@0xproject/web3-wrapper'; // tslint:disable-next-line:no-unused-variable import * as BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import {ECSignature} from '../types'; -import {signatureUtils} from '../utils/signature_utils'; +import { ECSignature } from '../types'; +import { signatureUtils } from '../utils/signature_utils'; export const assert = { ...sharedAssert, @@ -16,11 +16,15 @@ export const assert = { const isValidSignature = signatureUtils.isValidSignature(orderHash, ecSignature, signerAddress); this.assert(isValidSignature, `Expected order with hash '${orderHash}' to have a valid signature`); }, - async isSenderAddressAsync(variableName: string, senderAddressHex: string, - web3Wrapper: Web3Wrapper): Promise { + async isSenderAddressAsync( + variableName: string, + senderAddressHex: string, + web3Wrapper: Web3Wrapper, + ): Promise { sharedAssert.isETHAddressHex(variableName, senderAddressHex); const isSenderAddressAvailable = await web3Wrapper.isSenderAddressAvailableAsync(senderAddressHex); - sharedAssert.assert(isSenderAddressAvailable, + sharedAssert.assert( + isSenderAddressAvailable, `Specified ${variableName} ${senderAddressHex} isn't available through the supplied web3 provider`, ); }, diff --git a/packages/0x.js/src/utils/decorators.ts b/packages/0x.js/src/utils/decorators.ts index 2a823b9ac..99c7cce39 100644 --- a/packages/0x.js/src/utils/decorators.ts +++ b/packages/0x.js/src/utils/decorators.ts @@ -1,8 +1,8 @@ import * as _ from 'lodash'; -import {AsyncMethod, SyncMethod, ZeroExError} from '../types'; +import { AsyncMethod, SyncMethod, ZeroExError } from '../types'; -import {constants} from './constants'; +import { constants } from './constants'; type ErrorTransformer = (err: Error) => Error; @@ -19,7 +19,8 @@ const contractCallErrorTransformer = (error: Error) => { const schemaErrorTransformer = (error: Error) => { if (_.includes(error.message, constants.INVALID_TAKER_FORMAT)) { // tslint:disable-next-line:max-line-length - const errMsg = 'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS'; + const errMsg = + 'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS'; return new Error(errMsg); } return error; @@ -30,14 +31,16 @@ const schemaErrorTransformer = (error: Error) => { */ const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => { const asyncErrorHandlingDecorator = ( - target: object, key: string|symbol, descriptor: TypedPropertyDescriptor, + target: object, + key: string | symbol, + descriptor: TypedPropertyDescriptor, ) => { - const originalMethod = (descriptor.value as AsyncMethod); + const originalMethod = descriptor.value as AsyncMethod; // Do not use arrow syntax here. Use a function expression in // order to use the correct value of `this` in this method // tslint:disable-next-line:only-arrow-functions - descriptor.value = async function(...args: any[]) { + descriptor.value = async function(...args: any[]) { try { const result = await originalMethod.apply(this, args); return result; @@ -55,9 +58,11 @@ const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => { const syncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => { const syncErrorHandlingDecorator = ( - target: object, key: string|symbol, descriptor: TypedPropertyDescriptor, + target: object, + key: string | symbol, + descriptor: TypedPropertyDescriptor, ) => { - const originalMethod = (descriptor.value as SyncMethod); + const originalMethod = descriptor.value as SyncMethod; // Do not use arrow syntax here. Use a function expression in // order to use the correct value of `this` in this method diff --git a/packages/0x.js/src/utils/exchange_transfer_simulator.ts b/packages/0x.js/src/utils/exchange_transfer_simulator.ts index 8143112aa..575a2d3d2 100644 --- a/packages/0x.js/src/utils/exchange_transfer_simulator.ts +++ b/packages/0x.js/src/utils/exchange_transfer_simulator.ts @@ -1,9 +1,9 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import {TokenWrapper} from '../contract_wrappers/token_wrapper'; -import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store'; -import {BlockParamLiteral, ExchangeContractErrs, TradeSide, TransferType} from '../types'; +import { TokenWrapper } from '../contract_wrappers/token_wrapper'; +import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store'; +import { BlockParamLiteral, ExchangeContractErrs, TradeSide, TransferType } from '../types'; enum FailureReason { Balance = 'balance', @@ -36,8 +36,11 @@ const ERR_MSG_MAPPING = { export class ExchangeTransferSimulator { private _store: BalanceAndProxyAllowanceLazyStore; private _UNLIMITED_ALLOWANCE_IN_BASE_UNITS: BigNumber; - private static _throwValidationError(failureReason: FailureReason, tradeSide: TradeSide, - transferType: TransferType): never { + private static _throwValidationError( + failureReason: FailureReason, + tradeSide: TradeSide, + transferType: TransferType, + ): never { const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType]; throw new Error(errMsg); } @@ -54,9 +57,14 @@ export class ExchangeTransferSimulator { * @param tradeSide Is Maker/Taker transferring * @param transferType Is it a fee payment or a value transfer */ - public async transferFromAsync(tokenAddress: string, from: string, to: string, - amountInBaseUnits: BigNumber, tradeSide: TradeSide, - transferType: TransferType): Promise { + public async transferFromAsync( + tokenAddress: string, + from: string, + to: string, + amountInBaseUnits: BigNumber, + tradeSide: TradeSide, + transferType: TransferType, + ): Promise { const balance = await this._store.getBalanceAsync(tokenAddress, from); const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, from); if (proxyAllowance.lessThan(amountInBaseUnits)) { @@ -69,20 +77,29 @@ export class ExchangeTransferSimulator { await this._decreaseBalanceAsync(tokenAddress, from, amountInBaseUnits); await this._increaseBalanceAsync(tokenAddress, to, amountInBaseUnits); } - private async _decreaseProxyAllowanceAsync(tokenAddress: string, userAddress: string, - amountInBaseUnits: BigNumber): Promise { + private async _decreaseProxyAllowanceAsync( + tokenAddress: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, userAddress); if (!proxyAllowance.eq(this._UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) { this._store.setProxyAllowance(tokenAddress, userAddress, proxyAllowance.minus(amountInBaseUnits)); } } - private async _increaseBalanceAsync(tokenAddress: string, userAddress: string, - amountInBaseUnits: BigNumber): Promise { + private async _increaseBalanceAsync( + tokenAddress: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { const balance = await this._store.getBalanceAsync(tokenAddress, userAddress); this._store.setBalance(tokenAddress, userAddress, balance.plus(amountInBaseUnits)); } - private async _decreaseBalanceAsync(tokenAddress: string, userAddress: string, - amountInBaseUnits: BigNumber): Promise { + private async _decreaseBalanceAsync( + tokenAddress: string, + userAddress: string, + amountInBaseUnits: BigNumber, + ): Promise { const balance = await this._store.getBalanceAsync(tokenAddress, userAddress); this._store.setBalance(tokenAddress, userAddress, balance.minus(amountInBaseUnits)); } diff --git a/packages/0x.js/src/utils/filter_utils.ts b/packages/0x.js/src/utils/filter_utils.ts index 65161c33e..97205ace3 100644 --- a/packages/0x.js/src/utils/filter_utils.ts +++ b/packages/0x.js/src/utils/filter_utils.ts @@ -4,7 +4,7 @@ import * as _ from 'lodash'; import * as uuid from 'uuid/v4'; import * as Web3 from 'web3'; -import {BlockRange, ContractEvents, IndexedFilterValues} from '../types'; +import { BlockRange, ContractEvents, IndexedFilterValues } from '../types'; const TOPIC_LENGTH = 32; @@ -12,10 +12,14 @@ export const filterUtils = { generateUUID(): string { return uuid(); }, - getFilter(address: string, eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi, - blockRange?: BlockRange): Web3.FilterObject { - const eventAbi = _.find(abi, {name: eventName}) as Web3.EventAbi; + getFilter( + address: string, + eventName: ContractEvents, + indexFilterValues: IndexedFilterValues, + abi: Web3.ContractAbi, + blockRange?: BlockRange, + ): Web3.FilterObject { + const eventAbi = _.find(abi, { name: eventName }) as Web3.EventAbi; const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi, eventName); const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature)); const topicsForIndexedArgs = filterUtils.getTopicsForIndexedArgs(eventAbi, indexFilterValues); @@ -37,8 +41,8 @@ export const filterUtils = { const signature = `${eventAbi.name}(${types.join(',')})`; return signature; }, - getTopicsForIndexedArgs(abi: Web3.EventAbi, indexFilterValues: IndexedFilterValues): Array { - const topics: Array = []; + getTopicsForIndexedArgs(abi: Web3.EventAbi, indexFilterValues: IndexedFilterValues): Array { + const topics: Array = []; for (const eventInput of abi.inputs) { if (!eventInput.indexed) { continue; @@ -65,12 +69,12 @@ export const filterUtils = { } return true; }, - matchesTopics(logTopics: string[], filterTopics: Array): boolean { + matchesTopics(logTopics: string[], filterTopics: Array): boolean { const matchesTopic = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils)); const matchesTopics = _.every(matchesTopic); return matchesTopics; }, - matchesTopic(logTopic: string, filterTopic: string[]|string|null): boolean { + matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean { if (_.isArray(filterTopic)) { return _.includes(filterTopic, logTopic); } diff --git a/packages/0x.js/src/utils/order_state_utils.ts b/packages/0x.js/src/utils/order_state_utils.ts index 981f9e96c..5674528d5 100644 --- a/packages/0x.js/src/utils/order_state_utils.ts +++ b/packages/0x.js/src/utils/order_state_utils.ts @@ -1,11 +1,11 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import {ZeroEx} from '../0x'; -import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; -import {RemainingFillableCalculator} from '../order_watcher/remaining_fillable_calculator'; -import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store'; -import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store'; +import { ZeroEx } from '../0x'; +import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; +import { RemainingFillableCalculator } from '../order_watcher/remaining_fillable_calculator'; +import { BalanceAndProxyAllowanceLazyStore } from '../stores/balance_proxy_allowance_lazy_store'; +import { OrderFilledCancelledLazyStore } from '../stores/order_filled_cancelled_lazy_store'; import { ExchangeContractErrs, OrderRelevantState, @@ -44,15 +44,20 @@ export class OrderStateUtils { } } const minFillableTakerTokenAmountWithinNoRoundingErrorRange = signedOrder.takerTokenAmount - .dividedBy(ACCEPTABLE_RELATIVE_ROUNDING_ERROR) - .dividedBy(signedOrder.makerTokenAmount); - if (orderRelevantState.remainingFillableTakerTokenAmount - .lessThan(minFillableTakerTokenAmountWithinNoRoundingErrorRange)) { + .dividedBy(ACCEPTABLE_RELATIVE_ROUNDING_ERROR) + .dividedBy(signedOrder.makerTokenAmount); + if ( + orderRelevantState.remainingFillableTakerTokenAmount.lessThan( + minFillableTakerTokenAmountWithinNoRoundingErrorRange, + ) + ) { throw new Error(ExchangeContractErrs.OrderFillRoundingError); } } - constructor(balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore, - orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore) { + constructor( + balanceAndProxyAllowanceLazyStore: BalanceAndProxyAllowanceLazyStore, + orderFilledCancelledLazyStore: OrderFilledCancelledLazyStore, + ) { this._balanceAndProxyAllowanceLazyStore = balanceAndProxyAllowanceLazyStore; this._orderFilledCancelledLazyStore = orderFilledCancelledLazyStore; } @@ -85,16 +90,20 @@ export class OrderStateUtils { const zrxTokenAddress = exchange.getZRXTokenAddress(); const orderHash = ZeroEx.getOrderHashHex(signedOrder); const makerBalance = await this._balanceAndProxyAllowanceLazyStore.getBalanceAsync( - signedOrder.makerTokenAddress, signedOrder.maker, + signedOrder.makerTokenAddress, + signedOrder.maker, ); const makerProxyAllowance = await this._balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync( - signedOrder.makerTokenAddress, signedOrder.maker, + signedOrder.makerTokenAddress, + signedOrder.maker, ); const makerFeeBalance = await this._balanceAndProxyAllowanceLazyStore.getBalanceAsync( - zrxTokenAddress, signedOrder.maker, + zrxTokenAddress, + signedOrder.maker, ); const makerFeeProxyAllowance = await this._balanceAndProxyAllowanceLazyStore.getProxyAllowanceAsync( - zrxTokenAddress, signedOrder.maker, + zrxTokenAddress, + signedOrder.maker, ); const filledTakerTokenAmount = await this._orderFilledCancelledLazyStore.getFilledTakerAmountAsync(orderHash); const cancelledTakerTokenAmount = await this._orderFilledCancelledLazyStore.getCancelledTakerAmountAsync( @@ -104,17 +113,20 @@ export class OrderStateUtils { const totalMakerTokenAmount = signedOrder.makerTokenAmount; const totalTakerTokenAmount = signedOrder.takerTokenAmount; const remainingTakerTokenAmount = totalTakerTokenAmount.minus(unavailableTakerTokenAmount); - const remainingMakerTokenAmount = remainingTakerTokenAmount.times(totalMakerTokenAmount) - .dividedToIntegerBy(totalTakerTokenAmount); + const remainingMakerTokenAmount = remainingTakerTokenAmount + .times(totalMakerTokenAmount) + .dividedToIntegerBy(totalTakerTokenAmount); const transferrableMakerTokenAmount = BigNumber.min([makerProxyAllowance, makerBalance]); const transferrableFeeTokenAmount = BigNumber.min([makerFeeProxyAllowance, makerFeeBalance]); const isMakerTokenZRX = signedOrder.makerTokenAddress === zrxTokenAddress; - const remainingFillableCalculator = new RemainingFillableCalculator(signedOrder, - isMakerTokenZRX, - transferrableMakerTokenAmount, - transferrableFeeTokenAmount, - remainingMakerTokenAmount); + const remainingFillableCalculator = new RemainingFillableCalculator( + signedOrder, + isMakerTokenZRX, + transferrableMakerTokenAmount, + transferrableFeeTokenAmount, + remainingMakerTokenAmount, + ); const remainingFillableMakerTokenAmount = remainingFillableCalculator.computeRemainingMakerFillable(); const remainingFillableTakerTokenAmount = remainingFillableCalculator.computeRemainingTakerFillable(); const orderRelevantState = { diff --git a/packages/0x.js/src/utils/order_validation_utils.ts b/packages/0x.js/src/utils/order_validation_utils.ts index ad82d85b4..ebe4c49df 100644 --- a/packages/0x.js/src/utils/order_validation_utils.ts +++ b/packages/0x.js/src/utils/order_validation_utils.ts @@ -1,18 +1,20 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import {ZeroEx} from '../0x'; -import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; -import {ExchangeContractErrs, Order, SignedOrder, TradeSide, TransferType, ZeroExError} from '../types'; -import {constants} from '../utils/constants'; -import {utils} from '../utils/utils'; +import { ZeroEx } from '../0x'; +import { ExchangeWrapper } from '../contract_wrappers/exchange_wrapper'; +import { ExchangeContractErrs, Order, SignedOrder, TradeSide, TransferType, ZeroExError } from '../types'; +import { constants } from '../utils/constants'; +import { utils } from '../utils/utils'; -import {ExchangeTransferSimulator} from './exchange_transfer_simulator'; +import { ExchangeTransferSimulator } from './exchange_transfer_simulator'; export class OrderValidationUtils { private _exchangeWrapper: ExchangeWrapper; public static validateCancelOrderThrowIfInvalid( - order: Order, cancelTakerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber, + order: Order, + cancelTakerTokenAmount: BigNumber, + unavailableTakerTokenAmount: BigNumber, ): void { if (cancelTakerTokenAmount.eq(0)) { throw new Error(ExchangeContractErrs.OrderCancelAmountZero); @@ -26,8 +28,11 @@ export class OrderValidationUtils { } } public static async validateFillOrderBalancesAllowancesThrowIfInvalidAsync( - exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, - fillTakerTokenAmount: BigNumber, senderAddress: string, zrxTokenAddress: string, + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + senderAddress: string, + zrxTokenAddress: string, ): Promise { const fillMakerTokenAmount = OrderValidationUtils._getPartialAmount( fillTakerTokenAmount, @@ -35,12 +40,20 @@ export class OrderValidationUtils { signedOrder.makerTokenAmount, ); await exchangeTradeEmulator.transferFromAsync( - signedOrder.makerTokenAddress, signedOrder.maker, senderAddress, fillMakerTokenAmount, - TradeSide.Maker, TransferType.Trade, + signedOrder.makerTokenAddress, + signedOrder.maker, + senderAddress, + fillMakerTokenAmount, + TradeSide.Maker, + TransferType.Trade, ); await exchangeTradeEmulator.transferFromAsync( - signedOrder.takerTokenAddress, senderAddress, signedOrder.maker, fillTakerTokenAmount, - TradeSide.Taker, TransferType.Trade, + signedOrder.takerTokenAddress, + senderAddress, + signedOrder.maker, + fillTakerTokenAmount, + TradeSide.Taker, + TransferType.Trade, ); const makerFeeAmount = OrderValidationUtils._getPartialAmount( fillTakerTokenAmount, @@ -48,7 +61,11 @@ export class OrderValidationUtils { signedOrder.makerFee, ); await exchangeTradeEmulator.transferFromAsync( - zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount, TradeSide.Maker, + zrxTokenAddress, + signedOrder.maker, + signedOrder.feeRecipient, + makerFeeAmount, + TradeSide.Maker, TransferType.Fee, ); const takerFeeAmount = OrderValidationUtils._getPartialAmount( @@ -57,12 +74,17 @@ export class OrderValidationUtils { signedOrder.takerFee, ); await exchangeTradeEmulator.transferFromAsync( - zrxTokenAddress, senderAddress, signedOrder.feeRecipient, takerFeeAmount, TradeSide.Taker, + zrxTokenAddress, + senderAddress, + signedOrder.feeRecipient, + takerFeeAmount, + TradeSide.Taker, TransferType.Fee, ); } private static _validateRemainingFillAmountNotZeroOrThrow( - takerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber, + takerTokenAmount: BigNumber, + unavailableTakerTokenAmount: BigNumber, ) { if (takerTokenAmount.eq(unavailableTakerTokenAmount)) { throw new Error(ExchangeContractErrs.OrderRemainingFillAmountZero); @@ -74,24 +96,27 @@ export class OrderValidationUtils { throw new Error(ExchangeContractErrs.OrderFillExpired); } } - private static _getPartialAmount(numerator: BigNumber, denominator: BigNumber, - target: BigNumber): BigNumber { + private static _getPartialAmount(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { const fillMakerTokenAmount = numerator - .mul(target) - .div(denominator) - .round(0); + .mul(target) + .div(denominator) + .round(0); return fillMakerTokenAmount; } constructor(exchangeWrapper: ExchangeWrapper) { this._exchangeWrapper = exchangeWrapper; } public async validateOrderFillableOrThrowAsync( - exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, zrxTokenAddress: string, - expectedFillTakerTokenAmount?: BigNumber): Promise { + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + zrxTokenAddress: string, + expectedFillTakerTokenAmount?: BigNumber, + ): Promise { const orderHash = utils.getOrderHashHex(signedOrder); const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash); OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( - signedOrder.takerTokenAmount, unavailableTakerTokenAmount, + signedOrder.takerTokenAmount, + unavailableTakerTokenAmount, ); OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec); let fillTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount); @@ -104,8 +129,12 @@ export class OrderValidationUtils { signedOrder.makerTokenAmount, ); await exchangeTradeEmulator.transferFromAsync( - signedOrder.makerTokenAddress, signedOrder.maker, signedOrder.taker, fillMakerTokenAmount, - TradeSide.Maker, TransferType.Trade, + signedOrder.makerTokenAddress, + signedOrder.maker, + signedOrder.taker, + fillMakerTokenAmount, + TradeSide.Maker, + TransferType.Trade, ); const makerFeeAmount = OrderValidationUtils._getPartialAmount( fillTakerTokenAmount, @@ -113,14 +142,21 @@ export class OrderValidationUtils { signedOrder.makerFee, ); await exchangeTradeEmulator.transferFromAsync( - zrxTokenAddress, signedOrder.maker, signedOrder.feeRecipient, makerFeeAmount, - TradeSide.Maker, TransferType.Fee, + zrxTokenAddress, + signedOrder.maker, + signedOrder.feeRecipient, + makerFeeAmount, + TradeSide.Maker, + TransferType.Fee, ); } public async validateFillOrderThrowIfInvalidAsync( - exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, - fillTakerTokenAmount: BigNumber, takerAddress: string, - zrxTokenAddress: string): Promise { + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + takerAddress: string, + zrxTokenAddress: string, + ): Promise { if (fillTakerTokenAmount.eq(0)) { throw new Error(ExchangeContractErrs.OrderFillAmountZero); } @@ -130,22 +166,29 @@ export class OrderValidationUtils { } const unavailableTakerTokenAmount = await this._exchangeWrapper.getUnavailableTakerAmountAsync(orderHash); OrderValidationUtils._validateRemainingFillAmountNotZeroOrThrow( - signedOrder.takerTokenAmount, unavailableTakerTokenAmount, + signedOrder.takerTokenAmount, + unavailableTakerTokenAmount, ); if (signedOrder.taker !== constants.NULL_ADDRESS && signedOrder.taker !== takerAddress) { throw new Error(ExchangeContractErrs.TransactionSenderIsNotFillOrderTaker); } OrderValidationUtils._validateOrderNotExpiredOrThrow(signedOrder.expirationUnixTimestampSec); const remainingTakerTokenAmount = signedOrder.takerTokenAmount.minus(unavailableTakerTokenAmount); - const filledTakerTokenAmount = remainingTakerTokenAmount.lessThan(fillTakerTokenAmount) ? - remainingTakerTokenAmount : - fillTakerTokenAmount; + const filledTakerTokenAmount = remainingTakerTokenAmount.lessThan(fillTakerTokenAmount) + ? remainingTakerTokenAmount + : fillTakerTokenAmount; await OrderValidationUtils.validateFillOrderBalancesAllowancesThrowIfInvalidAsync( - exchangeTradeEmulator, signedOrder, filledTakerTokenAmount, takerAddress, zrxTokenAddress, + exchangeTradeEmulator, + signedOrder, + filledTakerTokenAmount, + takerAddress, + zrxTokenAddress, ); const wouldRoundingErrorOccur = await this._exchangeWrapper.isRoundingErrorAsync( - filledTakerTokenAmount, signedOrder.takerTokenAmount, signedOrder.makerTokenAmount, + filledTakerTokenAmount, + signedOrder.takerTokenAmount, + signedOrder.makerTokenAmount, ); if (wouldRoundingErrorOccur) { throw new Error(ExchangeContractErrs.OrderFillRoundingError); @@ -153,10 +196,18 @@ export class OrderValidationUtils { return filledTakerTokenAmount; } public async validateFillOrKillOrderThrowIfInvalidAsync( - exchangeTradeEmulator: ExchangeTransferSimulator, signedOrder: SignedOrder, - fillTakerTokenAmount: BigNumber, takerAddress: string, zrxTokenAddress: string): Promise { + exchangeTradeEmulator: ExchangeTransferSimulator, + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + takerAddress: string, + zrxTokenAddress: string, + ): Promise { const filledTakerTokenAmount = await this.validateFillOrderThrowIfInvalidAsync( - exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress, + exchangeTradeEmulator, + signedOrder, + fillTakerTokenAmount, + takerAddress, + zrxTokenAddress, ); if (filledTakerTokenAmount !== fillTakerTokenAmount) { throw new Error(ExchangeContractErrs.InsufficientRemainingFillAmount); diff --git a/packages/0x.js/src/utils/signature_utils.ts b/packages/0x.js/src/utils/signature_utils.ts index aaf04e7b0..b0f1d61ef 100644 --- a/packages/0x.js/src/utils/signature_utils.ts +++ b/packages/0x.js/src/utils/signature_utils.ts @@ -1,6 +1,6 @@ import * as ethUtil from 'ethereumjs-util'; -import {ECSignature} from '../types'; +import { ECSignature } from '../types'; export const signatureUtils = { isValidSignature(data: string, signature: ECSignature, signerAddress: string): boolean { @@ -11,7 +11,8 @@ export const signatureUtils = { msgHashBuff, signature.v, ethUtil.toBuffer(signature.r), - ethUtil.toBuffer(signature.s)); + ethUtil.toBuffer(signature.s), + ); const retrievedAddress = ethUtil.bufferToHex(ethUtil.pubToAddress(pubKey)); return retrievedAddress === signerAddress; } catch (err) { @@ -34,7 +35,7 @@ export const signatureUtils = { return ecSignature; }, parseSignatureHexAsRSV(signatureHex: string): ECSignature { - const {v, r, s} = ethUtil.fromRpcSig(signatureHex); + const { v, r, s } = ethUtil.fromRpcSig(signatureHex); const ecSignature: ECSignature = { v, r: ethUtil.bufferToHex(r), diff --git a/packages/0x.js/src/utils/utils.ts b/packages/0x.js/src/utils/utils.ts index 04ae34aac..09de6ce52 100644 --- a/packages/0x.js/src/utils/utils.ts +++ b/packages/0x.js/src/utils/utils.ts @@ -4,7 +4,7 @@ import * as ethABI from 'ethereumjs-abi'; import * as ethUtil from 'ethereumjs-util'; import * as _ from 'lodash'; -import {Order, SignedOrder, SolidityTypes} from '../types'; +import { Order, SignedOrder, SolidityTypes } from '../types'; export const utils = { /** @@ -29,20 +29,35 @@ export const utils = { spawnSwitchErr(name: string, value: any): Error { return new Error(`Unexpected switch value: ${value} encountered for ${name}`); }, - getOrderHashHex(order: Order|SignedOrder): string { + getOrderHashHex(order: Order | SignedOrder): string { const orderParts = [ - {value: order.exchangeContractAddress, type: SolidityTypes.Address}, - {value: order.maker, type: SolidityTypes.Address}, - {value: order.taker, type: SolidityTypes.Address}, - {value: order.makerTokenAddress, type: SolidityTypes.Address}, - {value: order.takerTokenAddress, type: SolidityTypes.Address}, - {value: order.feeRecipient, type: SolidityTypes.Address}, - {value: utils.bigNumberToBN(order.makerTokenAmount), type: SolidityTypes.Uint256}, - {value: utils.bigNumberToBN(order.takerTokenAmount), type: SolidityTypes.Uint256}, - {value: utils.bigNumberToBN(order.makerFee), type: SolidityTypes.Uint256}, - {value: utils.bigNumberToBN(order.takerFee), type: SolidityTypes.Uint256}, - {value: utils.bigNumberToBN(order.expirationUnixTimestampSec), type: SolidityTypes.Uint256}, - {value: utils.bigNumberToBN(order.salt), type: SolidityTypes.Uint256}, + { value: order.exchangeContractAddress, type: SolidityTypes.Address }, + { value: order.maker, type: SolidityTypes.Address }, + { value: order.taker, type: SolidityTypes.Address }, + { value: order.makerTokenAddress, type: SolidityTypes.Address }, + { value: order.takerTokenAddress, type: SolidityTypes.Address }, + { value: order.feeRecipient, type: SolidityTypes.Address }, + { + value: utils.bigNumberToBN(order.makerTokenAmount), + type: SolidityTypes.Uint256, + }, + { + value: utils.bigNumberToBN(order.takerTokenAmount), + type: SolidityTypes.Uint256, + }, + { + value: utils.bigNumberToBN(order.makerFee), + type: SolidityTypes.Uint256, + }, + { + value: utils.bigNumberToBN(order.takerFee), + type: SolidityTypes.Uint256, + }, + { + value: utils.bigNumberToBN(order.expirationUnixTimestampSec), + type: SolidityTypes.Uint256, + }, + { value: utils.bigNumberToBN(order.salt), type: SolidityTypes.Uint256 }, ]; const types = _.map(orderParts, o => o.type); const values = _.map(orderParts, o => o.value); -- cgit v1.2.3