diff options
author | Hsuan Lee <hsuan@cobinhood.com> | 2019-01-19 18:42:04 +0800 |
---|---|---|
committer | Hsuan Lee <hsuan@cobinhood.com> | 2019-01-19 18:42:04 +0800 |
commit | 7ae38906926dc09bc10670c361af0d2bf0050426 (patch) | |
tree | 5fb10ae366b987db09e4ddb4bc3ba0f75404ad08 /packages/contract-wrappers/src/utils | |
parent | b5fd3c72a08aaa6957917d74c333387a16edf66b (diff) | |
download | dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.gz dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.zst dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.zip |
Update dependency packages
Diffstat (limited to 'packages/contract-wrappers/src/utils')
9 files changed, 0 insertions, 780 deletions
diff --git a/packages/contract-wrappers/src/utils/assert.ts b/packages/contract-wrappers/src/utils/assert.ts deleted file mode 100644 index d30c6b29c..000000000 --- a/packages/contract-wrappers/src/utils/assert.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { assert as sharedAssert } from '@0x/assert'; -// HACK: We need those two unused imports because they're actually used by sharedAssert which gets injected here -import { Schema } from '@0x/json-schemas'; // tslint:disable-line:no-unused-variable -import { assetDataUtils, signatureUtils } from '@0x/order-utils'; -import { Order } from '@0x/types'; // tslint:disable-line:no-unused-variable -import { BigNumber } from '@0x/utils'; // tslint:disable-line:no-unused-variable -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { Provider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -export const assert = { - ...sharedAssert, - async isValidSignatureAsync( - provider: Provider, - orderHash: string, - signature: string, - signerAddress: string, - ): Promise<void> { - const isValid = await signatureUtils.isValidSignatureAsync(provider, orderHash, signature, signerAddress); - sharedAssert.assert(isValid, `Expected order with hash '${orderHash}' to have a valid signature`); - }, - isValidSubscriptionToken(variableName: string, subscriptionToken: string): void { - const uuidRegex = new RegExp('^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$'); - const isValid = uuidRegex.test(subscriptionToken); - sharedAssert.assert(isValid, `Expected ${variableName} to be a valid subscription token`); - }, - async isSenderAddressAsync( - variableName: string, - senderAddressHex: string, - web3Wrapper: Web3Wrapper, - ): Promise<void> { - sharedAssert.isETHAddressHex(variableName, senderAddressHex); - const isSenderAddressAvailable = await web3Wrapper.isSenderAddressAvailableAsync(senderAddressHex); - sharedAssert.assert( - isSenderAddressAvailable, - `Specified ${variableName} ${senderAddressHex} isn't available through the supplied web3 provider`, - ); - }, - ordersCanBeUsedForForwarderContract(orders: Order[], etherTokenAddress: string): void { - sharedAssert.assert(!_.isEmpty(orders), 'Expected at least 1 signed order. Found no orders'); - assert.ordersHaveAtMostOneUniqueValueForProperty(orders, 'makerAssetData'); - assert.allTakerAssetDatasAreErc20Token(orders, etherTokenAddress); - assert.allTakerAddressesAreNull(orders); - }, - feeOrdersCanBeUsedForForwarderContract(orders: Order[], zrxTokenAddress: string, etherTokenAddress: string): void { - if (!_.isEmpty(orders)) { - assert.allMakerAssetDatasAreErc20Token(orders, zrxTokenAddress); - assert.allTakerAssetDatasAreErc20Token(orders, etherTokenAddress); - } - }, - allTakerAddressesAreNull(orders: Order[]): void { - assert.ordersHaveAtMostOneUniqueValueForProperty(orders, 'takerAddress', constants.NULL_ADDRESS); - }, - allMakerAssetDatasAreErc20Token(orders: Order[], tokenAddress: string): void { - assert.ordersHaveAtMostOneUniqueValueForProperty( - orders, - 'makerAssetData', - assetDataUtils.encodeERC20AssetData(tokenAddress), - ); - }, - allTakerAssetDatasAreErc20Token(orders: Order[], tokenAddress: string): void { - assert.ordersHaveAtMostOneUniqueValueForProperty( - orders, - 'takerAssetData', - assetDataUtils.encodeERC20AssetData(tokenAddress), - ); - }, - /* - * Asserts that all the orders have the same value for the provided propertyName - * If the value parameter is provided, this asserts that all orders have the prope - */ - ordersHaveAtMostOneUniqueValueForProperty(orders: Order[], propertyName: string, value?: any): void { - const allValues = _.map(orders, order => _.get(order, propertyName)); - sharedAssert.hasAtMostOneUniqueValue( - allValues, - `Expected all orders to have the same ${propertyName} field. Found the following ${propertyName} values: ${JSON.stringify( - allValues, - )}`, - ); - if (!_.isUndefined(value)) { - const firstValue = _.head(allValues); - sharedAssert.assert( - firstValue === value, - `Expected all orders to have a ${propertyName} field with value: ${value}. Found: ${firstValue}`, - ); - } - }, -}; diff --git a/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts b/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts deleted file mode 100644 index bee7acaa7..000000000 --- a/packages/contract-wrappers/src/utils/calldata_optimization_utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { SignedOrder } from '@0x/types'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -export const calldataOptimizationUtils = { - /** - * Takes an array of orders and outputs an array of equivalent orders where all takerAssetData are '0x' and - * all makerAssetData are '0x' except for that of the first order, which retains its original value - * @param orders An array of SignedOrder objects - * @returns optimized orders - */ - optimizeForwarderOrders(orders: SignedOrder[]): SignedOrder[] { - const optimizedOrders = _.map(orders, (order, index) => - transformOrder(order, { - makerAssetData: index === 0 ? order.makerAssetData : constants.NULL_BYTES, - takerAssetData: constants.NULL_BYTES, - }), - ); - return optimizedOrders; - }, - /** - * Takes an array of orders and outputs an array of equivalent orders where all takerAssetData are '0x' and - * all makerAssetData are '0x' - * @param orders An array of SignedOrder objects - * @returns optimized orders - */ - optimizeForwarderFeeOrders(orders: SignedOrder[]): SignedOrder[] { - const optimizedOrders = _.map(orders, (order, index) => - transformOrder(order, { - makerAssetData: constants.NULL_BYTES, - takerAssetData: constants.NULL_BYTES, - }), - ); - return optimizedOrders; - }, -}; - -const transformOrder = (order: SignedOrder, partialOrder: Partial<SignedOrder>) => { - return { - ...order, - ...partialOrder, - }; -}; diff --git a/packages/contract-wrappers/src/utils/constants.ts b/packages/contract-wrappers/src/utils/constants.ts deleted file mode 100644 index 94afdc112..000000000 --- a/packages/contract-wrappers/src/utils/constants.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { BigNumber } from '@0x/utils'; - -export const constants = { - NULL_ADDRESS: '0x0000000000000000000000000000000000000000', - NULL_BYTES: '0x', - TESTRPC_NETWORK_ID: 50, - INVALID_JUMP_PATTERN: 'invalid JUMP at', - REVERT: 'revert', - OUT_OF_GAS_PATTERN: 'out of gas', - INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string', - // tslint:disable-next-line:custom-no-magic-numbers - UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1), - DEFAULT_BLOCK_POLLING_INTERVAL: 1000, - ZERO_AMOUNT: new BigNumber(0), - ONE_AMOUNT: new BigNumber(1), - ETHER_TOKEN_DECIMALS: 18, - METAMASK_USER_DENIED_SIGNATURE_PATTERN: 'User denied transaction signature', - TRUST_WALLET_USER_DENIED_SIGNATURE_PATTERN: 'cancelled', -}; diff --git a/packages/contract-wrappers/src/utils/contract_addresses.ts b/packages/contract-wrappers/src/utils/contract_addresses.ts deleted file mode 100644 index dc156e017..000000000 --- a/packages/contract-wrappers/src/utils/contract_addresses.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ContractAddresses, getContractAddressesForNetworkOrThrow, NetworkId } from '@0x/contract-addresses'; -import * as _ from 'lodash'; - -/** - * Returns the default contract addresses for the given networkId or throws with - * a context-specific error message if the networkId is not recognized. - */ -export function _getDefaultContractAddresses(networkId: number): ContractAddresses { - if (!(networkId in NetworkId)) { - throw new Error( - `No default contract addresses found for the given network id (${networkId}). If you want to use ContractWrappers on this network, you must manually pass in the contract address(es) to the constructor.`, - ); - } - return getContractAddressesForNetworkOrThrow(networkId); -} diff --git a/packages/contract-wrappers/src/utils/decorators.ts b/packages/contract-wrappers/src/utils/decorators.ts deleted file mode 100644 index 3acfa3a88..000000000 --- a/packages/contract-wrappers/src/utils/decorators.ts +++ /dev/null @@ -1,110 +0,0 @@ -import * as _ from 'lodash'; - -import { AsyncMethod, ContractWrappersError, SyncMethod } from '../types'; - -import { constants } from './constants'; - -type ErrorTransformer = (err: Error) => Error; - -const contractCallErrorTransformer = (error: Error) => { - if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) { - return new Error(ContractWrappersError.InvalidJump); - } - if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) { - return new Error(ContractWrappersError.OutOfGas); - } - if (_.includes(error.message, constants.REVERT)) { - const revertReason = error.message.split(constants.REVERT)[1].trim(); - return new Error(revertReason); - } - return error; -}; - -const schemaErrorTransformer = (error: Error) => { - if (_.includes(error.message, constants.INVALID_TAKER_FORMAT)) { - const errMsg = - 'Order taker must be of type string. If you want anyone to be able to fill an order - pass NULL_ADDRESS'; - return new Error(errMsg); - } - return error; -}; - -const signatureRequestErrorTransformer = (error: Error) => { - if ( - _.includes(error.message, constants.METAMASK_USER_DENIED_SIGNATURE_PATTERN) || - _.includes(error.message, constants.TRUST_WALLET_USER_DENIED_SIGNATURE_PATTERN) - ) { - const errMsg = ContractWrappersError.SignatureRequestDenied; - return new Error(errMsg); - } - return error; -}; - -/** - * Source: https://stackoverflow.com/a/29837695/3546986 - */ -const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => { - const asyncErrorHandlingDecorator = ( - _target: object, - _key: string | symbol, - descriptor: TypedPropertyDescriptor<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[]): Promise<any> { - try { - const result = await originalMethod.apply(this, args); // tslint:disable-line:no-invalid-this - return result; - } catch (error) { - const transformedError = errorTransformer(error); - throw transformedError; - } - }; - - return descriptor; - }; - - return asyncErrorHandlingDecorator; -}; - -const syncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => { - const syncErrorHandlingDecorator = ( - _target: object, - _key: string | symbol, - descriptor: TypedPropertyDescriptor<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 - // tslint:disable-next-line:only-arrow-functions - descriptor.value = function(...args: any[]): any { - try { - const result = originalMethod.apply(this, args); // tslint:disable-line:no-invalid-this - return result; - } catch (error) { - const transformedError = errorTransformer(error); - throw transformedError; - } - }; - - return descriptor; - }; - - return syncErrorHandlingDecorator; -}; - -// _.flow(f, g) = f ∘ g -const zeroExErrorTransformer = _.flow( - schemaErrorTransformer, - contractCallErrorTransformer, - signatureRequestErrorTransformer, -); - -export const decorators = { - asyncZeroExErrorHandler: asyncErrorHandlerFactory(zeroExErrorTransformer), - syncZeroExErrorHandler: syncErrorHandlerFactory(zeroExErrorTransformer), -}; diff --git a/packages/contract-wrappers/src/utils/exchange_transfer_simulator.ts b/packages/contract-wrappers/src/utils/exchange_transfer_simulator.ts deleted file mode 100644 index 4b75ea386..000000000 --- a/packages/contract-wrappers/src/utils/exchange_transfer_simulator.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { ExchangeContractErrs } from '@0x/types'; -import { BigNumber } from '@0x/utils'; - -import { AbstractBalanceAndProxyAllowanceLazyStore } from '../abstract/abstract_balance_and_proxy_allowance_lazy_store'; -import { TradeSide, TransferType } from '../types'; -import { constants } from '../utils/constants'; - -enum FailureReason { - Balance = 'balance', - ProxyAllowance = 'proxyAllowance', -} - -const ERR_MSG_MAPPING = { - [FailureReason.Balance]: { - [TradeSide.Maker]: { - [TransferType.Trade]: ExchangeContractErrs.InsufficientMakerBalance, - [TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeBalance, - }, - [TradeSide.Taker]: { - [TransferType.Trade]: ExchangeContractErrs.InsufficientTakerBalance, - [TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeBalance, - }, - }, - [FailureReason.ProxyAllowance]: { - [TradeSide.Maker]: { - [TransferType.Trade]: ExchangeContractErrs.InsufficientMakerAllowance, - [TransferType.Fee]: ExchangeContractErrs.InsufficientMakerFeeAllowance, - }, - [TradeSide.Taker]: { - [TransferType.Trade]: ExchangeContractErrs.InsufficientTakerAllowance, - [TransferType.Fee]: ExchangeContractErrs.InsufficientTakerFeeAllowance, - }, - }, -}; - -export class ExchangeTransferSimulator { - private readonly _store: AbstractBalanceAndProxyAllowanceLazyStore; - private static _throwValidationError( - failureReason: FailureReason, - tradeSide: TradeSide, - transferType: TransferType, - ): never { - const errMsg = ERR_MSG_MAPPING[failureReason][tradeSide][transferType]; - throw new Error(errMsg); - } - constructor(store: AbstractBalanceAndProxyAllowanceLazyStore) { - this._store = store; - } - /** - * Simulates transferFrom call performed by a proxy - * @param tokenAddress Address of the token to be transferred - * @param from Owner of the transferred tokens - * @param to Recipient of the transferred tokens - * @param amountInBaseUnits The amount of tokens being transferred - * @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<void> { - // HACK: When simulating an open order (e.g taker is NULL_ADDRESS), we don't want to adjust balances/ - // allowances for the taker. We do however, want to increase the balance of the maker since the maker - // might be relying on those funds to fill subsequent orders or pay the order's fees. - if (from === constants.NULL_ADDRESS && tradeSide === TradeSide.Taker) { - await this._increaseBalanceAsync(tokenAddress, to, amountInBaseUnits); - return; - } - const balance = await this._store.getBalanceAsync(tokenAddress, from); - const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, from); - if (proxyAllowance.isLessThan(amountInBaseUnits)) { - ExchangeTransferSimulator._throwValidationError(FailureReason.ProxyAllowance, tradeSide, transferType); - } - if (balance.isLessThan(amountInBaseUnits)) { - ExchangeTransferSimulator._throwValidationError(FailureReason.Balance, tradeSide, transferType); - } - await this._decreaseProxyAllowanceAsync(tokenAddress, from, amountInBaseUnits); - await this._decreaseBalanceAsync(tokenAddress, from, amountInBaseUnits); - await this._increaseBalanceAsync(tokenAddress, to, amountInBaseUnits); - } - private async _decreaseProxyAllowanceAsync( - tokenAddress: string, - userAddress: string, - amountInBaseUnits: BigNumber, - ): Promise<void> { - const proxyAllowance = await this._store.getProxyAllowanceAsync(tokenAddress, userAddress); - if (!proxyAllowance.eq(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)) { - this._store.setProxyAllowance(tokenAddress, userAddress, proxyAllowance.minus(amountInBaseUnits)); - } - } - private async _increaseBalanceAsync( - tokenAddress: string, - userAddress: string, - amountInBaseUnits: BigNumber, - ): Promise<void> { - 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<void> { - const balance = await this._store.getBalanceAsync(tokenAddress, userAddress); - this._store.setBalance(tokenAddress, userAddress, balance.minus(amountInBaseUnits)); - } -} diff --git a/packages/contract-wrappers/src/utils/filter_utils.ts b/packages/contract-wrappers/src/utils/filter_utils.ts deleted file mode 100644 index c05be062c..000000000 --- a/packages/contract-wrappers/src/utils/filter_utils.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { ContractAbi, EventAbi, FilterObject, LogEntry } from 'ethereum-types'; -import * as ethUtil from 'ethereumjs-util'; -import * as jsSHA3 from 'js-sha3'; -import * as _ from 'lodash'; -import * as uuid from 'uuid/v4'; - -import { BlockRange, ContractEvents, IndexedFilterValues } from '../types'; - -const TOPIC_LENGTH = 32; - -export const filterUtils = { - generateUUID(): string { - return uuid(); - }, - getFilter( - address: string, - eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, - abi: ContractAbi, - blockRange?: BlockRange, - ): FilterObject { - const eventAbi = _.find(abi, { name: eventName }) as EventAbi; - const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi); - const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature)); - const topicsForIndexedArgs = filterUtils.getTopicsForIndexedArgs(eventAbi, indexFilterValues); - const topics = [topicForEventSignature, ...topicsForIndexedArgs]; - let filter: FilterObject = { - address, - topics, - }; - if (!_.isUndefined(blockRange)) { - filter = { - ...blockRange, - ...filter, - }; - } - return filter; - }, - getEventSignatureFromAbiByName(eventAbi: EventAbi): string { - const types = _.map(eventAbi.inputs, 'type'); - const signature = `${eventAbi.name}(${types.join(',')})`; - return signature; - }, - getTopicsForIndexedArgs(abi: EventAbi, indexFilterValues: IndexedFilterValues): Array<string | null> { - const topics: Array<string | null> = []; - for (const eventInput of abi.inputs) { - if (!eventInput.indexed) { - continue; - } - if (_.isUndefined(indexFilterValues[eventInput.name])) { - // Null is a wildcard topic in a JSON-RPC call - topics.push(null); - } else { - const value = indexFilterValues[eventInput.name] as string; - const buffer = ethUtil.toBuffer(value); - const paddedBuffer = ethUtil.setLengthLeft(buffer, TOPIC_LENGTH); - const topic = ethUtil.bufferToHex(paddedBuffer); - topics.push(topic); - } - } - return topics; - }, - matchesFilter(log: LogEntry, filter: FilterObject): boolean { - if (!_.isUndefined(filter.address) && log.address !== filter.address) { - return false; - } - if (!_.isUndefined(filter.topics)) { - return filterUtils.doesMatchTopics(log.topics, filter.topics); - } - return true; - }, - doesMatchTopics(logTopics: string[], filterTopics: Array<string[] | string | null>): boolean { - const matchesTopic = _.zipWith(logTopics, filterTopics, filterUtils.matchesTopic.bind(filterUtils)); - const doesMatchTopics = _.every(matchesTopic); - return doesMatchTopics; - }, - matchesTopic(logTopic: string, filterTopic: string[] | string | null): boolean { - if (_.isArray(filterTopic)) { - return _.includes(filterTopic, logTopic); - } - if (_.isString(filterTopic)) { - return filterTopic === logTopic; - } - // null topic is a wildcard - return true; - }, -}; diff --git a/packages/contract-wrappers/src/utils/transaction_encoder.ts b/packages/contract-wrappers/src/utils/transaction_encoder.ts deleted file mode 100644 index 0cf08a8fe..000000000 --- a/packages/contract-wrappers/src/utils/transaction_encoder.ts +++ /dev/null @@ -1,281 +0,0 @@ -import { ExchangeContract } from '@0x/abi-gen-wrappers'; - -import { schemas } from '@0x/json-schemas'; -import { eip712Utils } from '@0x/order-utils'; -import { Order, SignedOrder } from '@0x/types'; -import { BigNumber, signTypedDataUtils } from '@0x/utils'; -import _ = require('lodash'); - -import { assert } from './assert'; - -/** - * Transaction Encoder. Transaction messages exist for the purpose of calling methods on the Exchange contract - * in the context of another address. For example, UserA can encode and sign a fillOrder transaction and UserB - * can submit this to the blockchain. The Exchange context executes as if UserA had directly submitted this transaction. - */ -export class TransactionEncoder { - private readonly _exchangeInstance: ExchangeContract; - constructor(exchangeInstance: ExchangeContract) { - this._exchangeInstance = exchangeInstance; - } - /** - * Encodes the transaction data for use with the Exchange contract. - * @param data The ABI Encoded 0x Exchange method. I.e fillOrder - * @param salt A random value to provide uniqueness and prevent replay attacks. - * @param signerAddress The address which will sign this transaction. - * @return An unsigned hex encoded transaction for use in 0x Exchange executeTransaction. - */ - public getTransactionHex(data: string, salt: BigNumber, signerAddress: string): string { - const exchangeAddress = this._getExchangeContract().address; - const executeTransactionData = { - salt, - signerAddress, - data, - }; - const typedData = eip712Utils.createZeroExTransactionTypedData(executeTransactionData, exchangeAddress); - const eip712MessageBuffer = signTypedDataUtils.generateTypedDataHash(typedData); - const messageHex = `0x${eip712MessageBuffer.toString('hex')}`; - return messageHex; - } - /** - * Encodes a fillOrder transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrderTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrder.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a fillOrderNoThrow transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrderNoThrowTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrderNoThrow.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a fillOrKillOrder transaction. - * @param signedOrder An object that conforms to the SignedOrder interface. - * @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public fillOrKillOrderTx(signedOrder: SignedOrder, takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount); - const abiEncodedData = this._getExchangeContract().fillOrKillOrder.getABIEncodedTransactionData( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrKillOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrKillOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrKillOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchFillOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill. - * @return Hex encoded abi of the function call. - */ - public batchFillOrdersNoThrowTx(signedOrders: SignedOrder[], takerAssetFillAmounts: BigNumber[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - _.forEach(takerAssetFillAmounts, takerAssetFillAmount => - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount), - ); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().batchFillOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmounts, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a batchCancelOrders transaction. - * @param signedOrders An array of orders to cancel. - * @return Hex encoded abi of the function call. - */ - public batchCancelOrdersTx(signedOrders: SignedOrder[]): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - const abiEncodedData = this._getExchangeContract().batchCancelOrders.getABIEncodedTransactionData(signedOrders); - return abiEncodedData; - } - /** - * Encodes a cancelOrdersUpTo transaction. - * @param targetOrderEpoch Target order epoch. - * @return Hex encoded abi of the function call. - */ - public cancelOrdersUpToTx(targetOrderEpoch: BigNumber): string { - assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); - const abiEncodedData = this._getExchangeContract().cancelOrdersUpTo.getABIEncodedTransactionData( - targetOrderEpoch, - ); - return abiEncodedData; - } - /** - * Encodes a cancelOrder transaction. - * @param order An object that conforms to the Order or SignedOrder interface. The order you would like to cancel. - * @return Hex encoded abi of the function call. - */ - public cancelOrderTx(order: Order | SignedOrder): string { - assert.doesConformToSchema('order', order, schemas.orderSchema); - const abiEncodedData = this._getExchangeContract().cancelOrder.getABIEncodedTransactionData(order); - return abiEncodedData; - } - /** - * Encodes a marketSellOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketSellOrdersTx(signedOrders: SignedOrder[], takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketSellOrders.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a marketSellOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param takerAssetFillAmount Taker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketSellOrdersNoThrowTx(signedOrders: SignedOrder[], takerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketSellOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - takerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a maketBuyOrders transaction. - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketBuyOrdersTx(signedOrders: SignedOrder[], makerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketBuyOrders.getABIEncodedTransactionData( - signedOrders, - makerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a maketBuyOrdersNoThrow transaction. - * @param signedOrders An array of signed orders to fill. - * @param makerAssetFillAmount Maker asset fill amount. - * @return Hex encoded abi of the function call. - */ - public marketBuyOrdersNoThrowTx(signedOrders: SignedOrder[], makerAssetFillAmount: BigNumber): string { - assert.doesConformToSchema('signedOrders', signedOrders, schemas.signedOrdersSchema); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - const signatures = _.map(signedOrders, signedOrder => signedOrder.signature); - const abiEncodedData = this._getExchangeContract().marketBuyOrdersNoThrow.getABIEncodedTransactionData( - signedOrders, - makerAssetFillAmount, - signatures, - ); - return abiEncodedData; - } - /** - * Encodes a preSign transaction. - * @param hash Hash to pre-sign - * @param signerAddress Address that should have signed the given hash. - * @param signature Proof that the hash has been signed by signer. - * @return Hex encoded abi of the function call. - */ - public preSignTx(hash: string, signerAddress: string, signature: string): string { - assert.isHexString('hash', hash); - assert.isETHAddressHex('signerAddress', signerAddress); - assert.isHexString('signature', signature); - const abiEncodedData = this._getExchangeContract().preSign.getABIEncodedTransactionData( - hash, - signerAddress, - signature, - ); - return abiEncodedData; - } - /** - * Encodes a setSignatureValidatorApproval transaction. - * @param validatorAddress Validator contract address. - * @param isApproved Boolean value to set approval to. - * @return Hex encoded abi of the function call. - */ - public setSignatureValidatorApprovalTx(validatorAddress: string, isApproved: boolean): string { - assert.isETHAddressHex('validatorAddress', validatorAddress); - assert.isBoolean('isApproved', isApproved); - const abiEncodedData = this._getExchangeContract().setSignatureValidatorApproval.getABIEncodedTransactionData( - validatorAddress, - isApproved, - ); - return abiEncodedData; - } - private _getExchangeContract(): ExchangeContract { - return this._exchangeInstance; - } -} diff --git a/packages/contract-wrappers/src/utils/utils.ts b/packages/contract-wrappers/src/utils/utils.ts deleted file mode 100644 index ab69385e7..000000000 --- a/packages/contract-wrappers/src/utils/utils.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { constants } from './constants'; - -export const utils = { - getCurrentUnixTimestampSec(): BigNumber { - const milisecondsInSecond = 1000; - return new BigNumber(Date.now() / milisecondsInSecond).integerValue(); - }, - getCurrentUnixTimestampMs(): BigNumber { - return new BigNumber(Date.now()); - }, - numberPercentageToEtherTokenAmountPercentage(percentage: number): BigNumber { - return Web3Wrapper.toBaseUnitAmount(constants.ONE_AMOUNT, constants.ETHER_TOKEN_DECIMALS).multipliedBy( - percentage, - ); - }, - removeUndefinedProperties<T extends object>(obj: T): Partial<T> { - return _.pickBy(obj); - }, -}; |