diff options
Diffstat (limited to 'packages/0x.js/src/contract_wrappers')
6 files changed, 149 insertions, 126 deletions
diff --git a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts index c1c95c6db..395d974b2 100644 --- a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts @@ -1,24 +1,25 @@ +import {Block, BlockAndLogStreamer} from 'ethereumjs-blockstream'; import * as _ from 'lodash'; import * as Web3 from 'web3'; -import {BlockAndLogStreamer, Block} from 'ethereumjs-blockstream'; -import {Web3Wrapper} from '../web3_wrapper'; -import {AbiDecoder} from '../utils/abi_decoder'; + import { - ZeroExError, - InternalZeroExError, Artifact, + BlockParamLiteral, + ContractEventArgs, + ContractEvents, + EventCallback, + IndexedFilterValues, + InternalZeroExError, LogWithDecodedArgs, RawLog, - ContractEvents, SubscriptionOpts, - IndexedFilterValues, - EventCallback, - BlockParamLiteral, - ContractEventArgs, + ZeroExError, } from '../types'; +import {AbiDecoder} from '../utils/abi_decoder'; import {constants} from '../utils/constants'; -import {intervalUtils} from '../utils/interval_utils'; import {filterUtils} from '../utils/filter_utils'; +import {intervalUtils} from '../utils/interval_utils'; +import {Web3Wrapper} from '../web3_wrapper'; export class ContractWrapper { protected _web3Wrapper: Web3Wrapper; @@ -95,6 +96,18 @@ export class ContractWrapper { await this._web3Wrapper.getContractInstanceFromArtifactAsync<ContractType>(artifact, addressIfExists); return contractInstance; } + protected _getContractAddress(artifact: Artifact, addressIfExists?: string): string { + if (_.isUndefined(addressIfExists)) { + const networkId = this._web3Wrapper.getNetworkId(); + const contractAddress = artifact.networks[networkId].address; + if (_.isUndefined(contractAddress)) { + throw new Error(ZeroExError.ExchangeContractDoesNotExist); + } + return contractAddress; + } else { + return addressIfExists; + } + } private _onLogStateChanged<ArgsType extends ContractEventArgs>(isRemoved: boolean, log: Web3.LogEntry): void { _.forEach(this._filters, (filter: Web3.FilterObject, filterToken: string) => { if (filterUtils.matchesFilter(log, filter)) { diff --git a/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts b/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts index 3cd2f0224..7a3f2bc52 100644 --- a/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts @@ -1,11 +1,13 @@ -import * as _ from 'lodash'; import BigNumber from 'bignumber.js'; +import * as _ from 'lodash'; + +import {artifacts} from '../artifacts'; +import {EtherTokenContract, ZeroExError} from '../types'; +import {assert} from '../utils/assert'; import {Web3Wrapper} from '../web3_wrapper'; + import {ContractWrapper} from './contract_wrapper'; import {TokenWrapper} from './token_wrapper'; -import {EtherTokenContract, ZeroExError} from '../types'; -import {assert} from '../utils/assert'; -import {artifacts} from '../artifacts'; /** * This class includes all the functionality related to interacting with a wrapped Ether ERC20 token contract. @@ -53,7 +55,7 @@ export class EtherTokenWrapper extends ContractWrapper { assert.isValidBaseUnitAmount('amountInWei', amountInWei); await assert.isSenderAddressAsync('withdrawer', withdrawer, this._web3Wrapper); - const wethContractAddress = await this.getContractAddressAsync(); + const wethContractAddress = this.getContractAddress(); const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(wethContractAddress, withdrawer); assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal); @@ -67,9 +69,11 @@ export class EtherTokenWrapper extends ContractWrapper { * Retrieves the Wrapped Ether token contract address * @return The Wrapped Ether token contract address */ - public async getContractAddressAsync(): Promise<string> { - const wethContract = await this._getEtherTokenContractAsync(); - return wethContract.address; + public getContractAddress(): string { + const contractAddress = this._getContractAddress( + artifacts.EtherTokenArtifact, this._contractAddressIfExists, + ); + return contractAddress; } private _invalidateContractInstance(): void { delete this._etherTokenContractIfExists; @@ -81,7 +85,7 @@ export class EtherTokenWrapper extends ContractWrapper { const contractInstance = await this._instantiateContractIfExistsAsync<EtherTokenContract>( artifacts.EtherTokenArtifact, this._contractAddressIfExists, ); - this._etherTokenContractIfExists = contractInstance as EtherTokenContract; + this._etherTokenContractIfExists = contractInstance; return this._etherTokenContractIfExists; } } diff --git a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts index 7c33dc6ec..cd38c78fc 100644 --- a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts @@ -1,45 +1,46 @@ +import {schemas} from '@0xproject/json-schemas'; +import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as Web3 from 'web3'; -import BigNumber from 'bignumber.js'; -import {schemas} from '@0xproject/json-schemas'; -import {Web3Wrapper} from '../web3_wrapper'; + +import {artifacts} from '../artifacts'; import { + DecodedLogArgs, ECSignature, + EventCallback, ExchangeContract, ExchangeContractErrCodes, ExchangeContractErrs, - ZeroExError, - OrderValues, - OrderAddresses, - Order, - SignedOrder, + ExchangeContractEventArgs, ExchangeEvents, - SubscriptionOpts, IndexedFilterValues, - OrderCancellationRequest, - OrderFillRequest, + LogCancelContractEventArgs, LogErrorContractEventArgs, LogFillContractEventArgs, - LogCancelContractEventArgs, LogWithDecodedArgs, MethodOpts, - ValidateOrderFillableOpts, + Order, + OrderAddresses, + OrderCancellationRequest, + OrderFillRequest, OrderTransactionOpts, + OrderValues, RawLog, EventCallback, ExchangeContractEventArgs, DecodedLogArgs, BlockParamLiteral, } from '../types'; +import {AbiDecoder} from '../utils/abi_decoder'; import {assert} from '../utils/assert'; -import {utils} from '../utils/utils'; +import {decorators} from '../utils/decorators'; +import {ExchangeTransferSimulator} from '../utils/exchange_transfer_simulator'; import {OrderValidationUtils} from '../utils/order_validation_utils'; +import {utils} from '../utils/utils'; +import {Web3Wrapper} from '../web3_wrapper'; + import {ContractWrapper} from './contract_wrapper'; import {TokenWrapper} from './token_wrapper'; -import {decorators} from '../utils/decorators'; -import {AbiDecoder} from '../utils/abi_decoder'; -import {ExchangeTransferSimulator} from '../utils/exchange_transfer_simulator'; -import {artifacts} from '../artifacts'; const SHOULD_VALIDATE_BY_DEFAULT = true; @@ -64,6 +65,7 @@ export class ExchangeWrapper extends ContractWrapper { [ExchangeContractErrCodes.ERROR_FILL_BALANCE_ALLOWANCE]: ExchangeContractErrs.FillBalanceAllowanceError, }; private _contractAddressIfExists?: string; + private _zrxContractAddressIfExists?: string; private static _getOrderAddressesAndValues(order: Order): [OrderAddresses, OrderValues] { const orderAddresses: OrderAddresses = [ order.maker, @@ -178,7 +180,7 @@ export class ExchangeWrapper extends ContractWrapper { SHOULD_VALIDATE_BY_DEFAULT : orderTransactionOpts.shouldValidate; if (shouldValidate) { - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync( exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress); @@ -250,7 +252,7 @@ export class ExchangeWrapper extends ContractWrapper { SHOULD_VALIDATE_BY_DEFAULT : orderTransactionOpts.shouldValidate; if (shouldValidate) { - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); for (const signedOrder of signedOrders) { await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync( @@ -340,7 +342,7 @@ export class ExchangeWrapper extends ContractWrapper { SHOULD_VALIDATE_BY_DEFAULT : orderTransactionOpts.shouldValidate; if (shouldValidate) { - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); for (const orderFillRequest of orderFillRequests) { await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync( @@ -420,7 +422,7 @@ export class ExchangeWrapper extends ContractWrapper { SHOULD_VALIDATE_BY_DEFAULT : orderTransactionOpts.shouldValidate; if (shouldValidate) { - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync( exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress); @@ -484,7 +486,7 @@ export class ExchangeWrapper extends ContractWrapper { SHOULD_VALIDATE_BY_DEFAULT : orderTransactionOpts.shouldValidate; if (shouldValidate) { - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); for (const orderFillRequest of orderFillRequests) { await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync( @@ -557,7 +559,7 @@ export class ExchangeWrapper extends ContractWrapper { if (shouldValidate) { const orderHash = utils.getOrderHashHex(order); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); - await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync( + OrderValidationUtils.validateCancelOrderThrowIfInvalid( order, cancelTakerTokenAmount, unavailableTakerTokenAmount); } @@ -611,7 +613,7 @@ export class ExchangeWrapper extends ContractWrapper { for (const orderCancellationRequest of orderCancellationRequests) { const orderHash = utils.getOrderHashHex(orderCancellationRequest.order); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); - await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync( + OrderValidationUtils.validateCancelOrderThrowIfInvalid( orderCancellationRequest.order, orderCancellationRequest.takerTokenCancelAmount, unavailableTakerTokenAmount, ); @@ -658,13 +660,13 @@ export class ExchangeWrapper extends ContractWrapper { * @param callback Callback that gets called when a log is added/removed * @return Subscription token used later to unsubscribe */ - public async subscribeAsync<ArgsType extends ExchangeContractEventArgs>( + public subscribe<ArgsType extends ExchangeContractEventArgs>( eventName: ExchangeEvents, indexFilterValues: IndexedFilterValues, - callback: EventCallback<ArgsType>): Promise<string> { + callback: EventCallback<ArgsType>): string { assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.isFunction('callback', callback); - const exchangeContractAddress = await this.getContractAddressAsync(); + const exchangeContractAddress = this.getContractAddress(); const subscriptionToken = this._subscribe<ArgsType>( exchangeContractAddress, eventName, indexFilterValues, artifacts.ExchangeArtifact.abi, callback, ); @@ -691,7 +693,7 @@ export class ExchangeWrapper extends ContractWrapper { assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const exchangeContractAddress = await this.getContractAddressAsync(); + const exchangeContractAddress = this.getContractAddress(); const logs = await this._getLogsAsync<ArgsType>( exchangeContractAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.ExchangeArtifact.abi, ); @@ -702,10 +704,9 @@ export class ExchangeWrapper extends ContractWrapper { * that the user-passed web3 provider is connected to. * @returns The Ethereum address of the Exchange contract being used. */ - public async getContractAddressAsync(): Promise<string> { - const exchangeInstance = await this._getExchangeContractAsync(); - const exchangeAddress = exchangeInstance.address; - return exchangeAddress; + public getContractAddress(): string { + const contractAddress = this._getContractAddress(artifacts.ExchangeArtifact, this._contractAddressIfExists); + return contractAddress; } /** * Checks if order is still fillable and throws an error otherwise. Useful for orderbook @@ -720,7 +721,7 @@ export class ExchangeWrapper extends ContractWrapper { signedOrder: SignedOrder, opts?: ValidateOrderFillableOpts, ): Promise<void> { assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const expectedFillTakerTokenAmount = !_.isUndefined(opts) ? opts.expectedFillTakerTokenAmount : undefined; const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); await this._orderValidationUtils.validateOrderFillableOrThrowAsync( @@ -741,7 +742,7 @@ export class ExchangeWrapper extends ContractWrapper { assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); await this._orderValidationUtils.validateFillOrderThrowIfInvalidAsync( exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress); @@ -758,7 +759,7 @@ export class ExchangeWrapper extends ContractWrapper { assert.isValidBaseUnitAmount('cancelTakerTokenAmount', cancelTakerTokenAmount); const orderHash = utils.getOrderHashHex(order); const unavailableTakerTokenAmount = await this.getUnavailableTakerAmountAsync(orderHash); - await this._orderValidationUtils.validateCancelOrderThrowIfInvalidAsync( + OrderValidationUtils.validateCancelOrderThrowIfInvalid( order, cancelTakerTokenAmount, unavailableTakerTokenAmount); } /** @@ -775,7 +776,7 @@ export class ExchangeWrapper extends ContractWrapper { assert.doesConformToSchema('signedOrder', signedOrder, schemas.signedOrderSchema); assert.isValidBaseUnitAmount('fillTakerTokenAmount', fillTakerTokenAmount); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const zrxTokenAddress = await this.getZRXTokenAddressAsync(); + const zrxTokenAddress = this.getZRXTokenAddress(); const exchangeTradeEmulator = new ExchangeTransferSimulator(this._tokenWrapper, BlockParamLiteral.Latest); await this._orderValidationUtils.validateFillOrKillOrderThrowIfInvalidAsync( exchangeTradeEmulator, signedOrder, fillTakerTokenAmount, takerAddress, zrxTokenAddress); @@ -820,12 +821,13 @@ export class ExchangeWrapper extends ContractWrapper { * Returns the ZRX token address used by the exchange contract. * @return Address of ZRX token */ - public async getZRXTokenAddressAsync(): Promise<string> { - const exchangeInstance = await this._getExchangeContractAsync(); - const ZRXtokenAddress = await exchangeInstance.ZRX_TOKEN_CONTRACT.callAsync(); - return ZRXtokenAddress; + public getZRXTokenAddress(): string { + const contractAddress = this._getContractAddress( + artifacts.ZRXArtifact, this._zrxContractAddressIfExists, + ); + return contractAddress; } - private async _invalidateContractInstancesAsync(): Promise<void> { + private _invalidateContractInstances(): void { this.unsubscribeAll(); delete this._exchangeContractIfExists; } @@ -859,7 +861,7 @@ export class ExchangeWrapper extends ContractWrapper { const contractInstance = await this._instantiateContractIfExistsAsync<ExchangeContract>( artifacts.ExchangeArtifact, this._contractAddressIfExists, ); - this._exchangeContractIfExists = contractInstance as ExchangeContract; + this._exchangeContractIfExists = contractInstance; return this._exchangeContractIfExists; } private async _getTokenTransferProxyAddressAsync(): Promise<string> { @@ -868,4 +870,4 @@ export class ExchangeWrapper extends ContractWrapper { const tokenTransferProxyAddressLowerCase = tokenTransferProxyAddress.toLowerCase(); return tokenTransferProxyAddressLowerCase; } -} +} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts index 2cc5a9aa0..35337fa35 100644 --- a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts @@ -1,10 +1,12 @@ import * as _ from 'lodash'; -import {Web3Wrapper} from '../web3_wrapper'; + +import {artifacts} from '../artifacts'; +import {Token, TokenMetadata, TokenRegistryContract, ZeroExError} from '../types'; import {assert} from '../utils/assert'; -import {Token, TokenRegistryContract, TokenMetadata} from '../types'; import {constants} from '../utils/constants'; +import {Web3Wrapper} from '../web3_wrapper'; + import {ContractWrapper} from './contract_wrapper'; -import {artifacts} from '../artifacts'; /** * This class includes all the functionality related to interacting with the 0x Token Registry smart contract. @@ -12,6 +14,18 @@ import {artifacts} from '../artifacts'; export class TokenRegistryWrapper extends ContractWrapper { private _tokenRegistryContractIfExists?: TokenRegistryContract; private _contractAddressIfExists?: string; + private static _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined { + if (metadata[0] === constants.NULL_ADDRESS) { + return undefined; + } + const token = { + address: metadata[0], + name: metadata[1], + symbol: metadata[2], + decimals: metadata[3].toNumber(), + }; + return token; + } constructor(web3Wrapper: Web3Wrapper, contractAddressIfExists?: string) { super(web3Wrapper); this._contractAddressIfExists = contractAddressIfExists; @@ -26,7 +40,7 @@ export class TokenRegistryWrapper extends ContractWrapper { const addresses = await this.getTokenAddressesAsync(); const tokenPromises: Array<Promise<Token|undefined>> = _.map( addresses, - (address: string) => (this.getTokenIfExistsAsync(address)), + async (address: string) => this.getTokenIfExistsAsync(address), ); const tokens = await Promise.all(tokenPromises); return tokens as Token[]; @@ -49,7 +63,7 @@ export class TokenRegistryWrapper extends ContractWrapper { const tokenRegistryContract = await this._getTokenRegistryContractAsync(); const metadata = await tokenRegistryContract.getTokenMetaData.callAsync(address); - const token = this._createTokenFromMetadata(metadata); + const token = TokenRegistryWrapper._createTokenFromMetadata(metadata); return token; } public async getTokenAddressBySymbolIfExistsAsync(symbol: string): Promise<string|undefined> { @@ -74,14 +88,14 @@ export class TokenRegistryWrapper extends ContractWrapper { assert.isString('symbol', symbol); const tokenRegistryContract = await this._getTokenRegistryContractAsync(); const metadata = await tokenRegistryContract.getTokenBySymbol.callAsync(symbol); - const token = this._createTokenFromMetadata(metadata); + const token = TokenRegistryWrapper._createTokenFromMetadata(metadata); return token; } public async getTokenByNameIfExistsAsync(name: string): Promise<Token|undefined> { assert.isString('name', name); const tokenRegistryContract = await this._getTokenRegistryContractAsync(); const metadata = await tokenRegistryContract.getTokenByName.callAsync(name); - const token = this._createTokenFromMetadata(metadata); + const token = TokenRegistryWrapper._createTokenFromMetadata(metadata); return token; } /** @@ -89,22 +103,11 @@ export class TokenRegistryWrapper extends ContractWrapper { * that the user-passed web3 provider is connected to. * @returns The Ethereum address of the TokenRegistry contract being used. */ - public async getContractAddressAsync(): Promise<string> { - const tokenRegistryInstance = await this._getTokenRegistryContractAsync(); - const tokenRegistryAddress = tokenRegistryInstance.address; - return tokenRegistryAddress; - } - private _createTokenFromMetadata(metadata: TokenMetadata): Token|undefined { - if (metadata[0] === constants.NULL_ADDRESS) { - return undefined; - } - const token = { - address: metadata[0], - name: metadata[1], - symbol: metadata[2], - decimals: metadata[3].toNumber(), - }; - return token; + public getContractAddress(): string { + const contractAddress = this._getContractAddress( + artifacts.TokenRegistryArtifact, this._contractAddressIfExists, + ); + return contractAddress; } private _invalidateContractInstance(): void { delete this._tokenRegistryContractIfExists; @@ -116,7 +119,7 @@ export class TokenRegistryWrapper extends ContractWrapper { const contractInstance = await this._instantiateContractIfExistsAsync<TokenRegistryContract>( artifacts.TokenRegistryArtifact, this._contractAddressIfExists, ); - this._tokenRegistryContractIfExists = contractInstance as TokenRegistryContract; + this._tokenRegistryContractIfExists = contractInstance; return this._tokenRegistryContractIfExists; } } diff --git a/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts index f81845af9..c3df7d3eb 100644 --- a/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts @@ -1,18 +1,20 @@ import * as _ from 'lodash'; + +import {artifacts} from '../artifacts'; +import {TokenTransferProxyContract, ZeroExError} from '../types'; import {Web3Wrapper} from '../web3_wrapper'; + import {ContractWrapper} from './contract_wrapper'; -import {artifacts} from '../artifacts'; -import {TokenTransferProxyContract} from '../types'; /** * This class includes the functionality related to interacting with the TokenTransferProxy contract. */ export class TokenTransferProxyWrapper extends ContractWrapper { private _tokenTransferProxyContractIfExists?: TokenTransferProxyContract; - private _tokenTransferProxyContractAddressFetcher: () => Promise<string>; - constructor(web3Wrapper: Web3Wrapper, tokenTransferProxyContractAddressFetcher: () => Promise<string>) { + private _contractAddressIfExists?: string; + constructor(web3Wrapper: Web3Wrapper, contractAddressIfExists?: string) { super(web3Wrapper); - this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher; + this._contractAddressIfExists = contractAddressIfExists; } /** * Check if the Exchange contract address is authorized by the TokenTransferProxy contract. @@ -38,10 +40,11 @@ export class TokenTransferProxyWrapper extends ContractWrapper { * that the user-passed web3 provider is connected to. * @returns The Ethereum address of the TokenTransferProxy contract being used. */ - public async getContractAddressAsync(): Promise<string> { - const proxyInstance = await this._getTokenTransferProxyContractAsync(); - const proxyAddress = proxyInstance.address; - return proxyAddress; + public getContractAddress(): string { + const contractAddress = this._getContractAddress( + artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists, + ); + return contractAddress; } private _invalidateContractInstance(): void { delete this._tokenTransferProxyContractIfExists; @@ -50,11 +53,10 @@ export class TokenTransferProxyWrapper extends ContractWrapper { if (!_.isUndefined(this._tokenTransferProxyContractIfExists)) { return this._tokenTransferProxyContractIfExists; } - const contractAddress = await this._tokenTransferProxyContractAddressFetcher(); const contractInstance = await this._instantiateContractIfExistsAsync<TokenTransferProxyContract>( - artifacts.TokenTransferProxyArtifact, contractAddress, + artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists, ); - this._tokenTransferProxyContractIfExists = contractInstance as TokenTransferProxyContract; + this._tokenTransferProxyContractIfExists = contractInstance; return this._tokenTransferProxyContractIfExists; } } diff --git a/packages/0x.js/src/contract_wrappers/token_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_wrapper.ts index 4b89d3cfc..5c6cfeaed 100644 --- a/packages/0x.js/src/contract_wrappers/token_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_wrapper.ts @@ -1,23 +1,26 @@ -import * as _ from 'lodash'; -import BigNumber from 'bignumber.js'; import {schemas} from '@0xproject/json-schemas'; -import {Web3Wrapper} from '../web3_wrapper'; -import {assert} from '../utils/assert'; -import {constants} from '../utils/constants'; -import {ContractWrapper} from './contract_wrapper'; -import {AbiDecoder} from '../utils/abi_decoder'; +import BigNumber from 'bignumber.js'; +import * as _ from 'lodash'; + import {artifacts} from '../artifacts'; import { - TokenContract, - ZeroExError, - TokenEvents, + EventCallback, IndexedFilterValues, - SubscriptionOpts, - MethodOpts, LogWithDecodedArgs, - EventCallback, + MethodOpts, + SubscriptionOpts, + TokenContract, TokenContractEventArgs, + TokenEvents, + ZeroExError, } from '../types'; +import {AbiDecoder} from '../utils/abi_decoder'; +import {assert} from '../utils/assert'; +import {constants} from '../utils/constants'; +import {Web3Wrapper} from '../web3_wrapper'; + +import {ContractWrapper} from './contract_wrapper'; +import {TokenTransferProxyWrapper} from './token_transfer_proxy_wrapper'; const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275; @@ -29,12 +32,12 @@ const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275; export class TokenWrapper extends ContractWrapper { public UNLIMITED_ALLOWANCE_IN_BASE_UNITS = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; private _tokenContractsByAddress: {[address: string]: TokenContract}; - private _tokenTransferProxyContractAddressFetcher: () => Promise<string>; + private _tokenTransferProxyWrapper: TokenTransferProxyWrapper; constructor(web3Wrapper: Web3Wrapper, abiDecoder: AbiDecoder, - tokenTransferProxyContractAddressFetcher: () => Promise<string>) { + tokenTransferProxyWrapper: TokenTransferProxyWrapper) { super(web3Wrapper, abiDecoder); this._tokenContractsByAddress = {}; - this._tokenTransferProxyContractAddressFetcher = tokenTransferProxyContractAddressFetcher; + this._tokenTransferProxyWrapper = tokenTransferProxyWrapper; } /** * Retrieves an owner's ERC20 token balance. @@ -76,8 +79,8 @@ export class TokenWrapper extends ContractWrapper { // Hack: for some reason default estimated gas amount causes `base fee exceeds gas limit` exception // on testrpc. Probably related to https://github.com/ethereumjs/testrpc/issues/294 // TODO: Debug issue in testrpc and submit a PR, then remove this hack - const networkIdIfExists = await this._web3Wrapper.getNetworkIdIfExistsAsync(); - const gas = networkIdIfExists === constants.TESTRPC_NETWORK_ID ? ALLOWANCE_TO_ZERO_GAS_AMOUNT : undefined; + const networkId = this._web3Wrapper.getNetworkId(); + const gas = networkId === constants.TESTRPC_NETWORK_ID ? ALLOWANCE_TO_ZERO_GAS_AMOUNT : undefined; const txHash = await tokenContract.approve.sendTransactionAsync(spenderAddress, amountInBaseUnits, { from: ownerAddress, gas, @@ -133,7 +136,7 @@ export class TokenWrapper extends ContractWrapper { assert.isETHAddressHex('ownerAddress', ownerAddress); assert.isETHAddressHex('tokenAddress', tokenAddress); - const proxyAddress = await this._getTokenTransferProxyAddressAsync(); + const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress(); const allowanceInBaseUnits = await this.getAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, methodOpts); return allowanceInBaseUnits; } @@ -152,7 +155,7 @@ export class TokenWrapper extends ContractWrapper { assert.isETHAddressHex('tokenAddress', tokenAddress); assert.isValidBaseUnitAmount('amountInBaseUnits', amountInBaseUnits); - const proxyAddress = await this._getTokenTransferProxyAddressAsync(); + const proxyAddress = this._tokenTransferProxyWrapper.getContractAddress(); const txHash = await this.setAllowanceAsync(tokenAddress, ownerAddress, proxyAddress, amountInBaseUnits); return txHash; } @@ -290,7 +293,7 @@ export class TokenWrapper extends ContractWrapper { ); return logs; } - private _invalidateContractInstancesAsync(): void { + private _invalidateContractInstances(): void { this.unsubscribeAll(); this._tokenContractsByAddress = {}; } @@ -302,12 +305,8 @@ export class TokenWrapper extends ContractWrapper { const contractInstance = await this._instantiateContractIfExistsAsync<TokenContract>( artifacts.TokenArtifact, tokenAddress, ); - tokenContract = contractInstance as TokenContract; + tokenContract = contractInstance; this._tokenContractsByAddress[tokenAddress] = tokenContract; return tokenContract; } - private async _getTokenTransferProxyAddressAsync(): Promise<string> { - const tokenTransferProxyContractAddress = await this._tokenTransferProxyContractAddressFetcher(); - return tokenTransferProxyContractAddress; - } } |