From 5913d654bdf77d25b95570b1e656f63cc89ff97a Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Tue, 22 May 2018 16:18:52 -0700 Subject: Remove 0x.js as a dependency from website --- packages/website/ts/blockchain.ts | 118 +++++++++++++++++++------------------- 1 file changed, 60 insertions(+), 58 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 32acb9d43..17dbee5c8 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -1,20 +1,15 @@ import { - BlockParam, BlockRange, + ContractWrappers, DecodedLogEvent, - ECSignature, ExchangeContractEventArgs, ExchangeEvents, IndexedFilterValues, LogCancelContractEventArgs, LogFillContractEventArgs, - LogWithDecodedArgs, - Order, - SignedOrder, Token as ZeroExToken, - TransactionReceiptWithDecodedLogs, - ZeroEx, -} from '0x.js'; +} from '@0xproject/contract-wrappers'; +import { isValidOrderHash, signOrderHashAsync } from '@0xproject/order-utils'; import { EtherscanLinkSuffixes, utils as sharedUtils } from '@0xproject/react-shared'; import { InjectedWeb3Subprovider, @@ -23,7 +18,15 @@ import { RedundantSubprovider, Subprovider, } from '@0xproject/subproviders'; -import { Provider } from '@0xproject/types'; +import { + BlockParam, + ECSignature, + LogWithDecodedArgs, + Order, + Provider, + SignedOrder, + TransactionReceiptWithDecodedLogs, +} from '@0xproject/types'; import { BigNumber, intervalUtils, logUtils, promisify } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; @@ -72,7 +75,7 @@ const providerToName: { [provider: string]: string } = { export class Blockchain { public networkId: number; public nodeVersion: string; - private _zeroEx: ZeroEx; + private _contractWrappers: ContractWrappers; private _dispatcher: Dispatcher; private _web3Wrapper?: Web3Wrapper; private _blockchainWatcher?: BlockchainWatcher; @@ -164,8 +167,8 @@ export class Blockchain { } } public async isAddressInTokenRegistryAsync(tokenAddress: string): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); - const tokenIfExists = await this._zeroEx.tokenRegistry.getTokenIfExistsAsync(tokenAddress); + utils.assert(!_.isUndefined(this._contractWrappers), 'Contract Wrappers must be instantiated.'); + const tokenIfExists = await this._contractWrappers.tokenRegistry.getTokenIfExistsAsync(tokenAddress); return !_.isUndefined(tokenIfExists); } public getLedgerDerivationPathIfExists(): string { @@ -182,7 +185,7 @@ export class Blockchain { this._ledgerSubprovider.setPath(path); } public async updateProviderToLedgerAsync(networkId: number): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'Contract Wrappers must be instantiated.'); const isU2FSupported = await utils.isU2FSupportedAsync(); if (!isU2FSupported) { @@ -225,12 +228,12 @@ export class Blockchain { this.networkId, shouldPollUserAddress, ); - this._zeroEx.setProvider(provider, this.networkId); + this._contractWrappers.setProvider(provider, this.networkId); this._blockchainWatcher.startEmittingNetworkConnectionAndUserBalanceState(); this._dispatcher.updateProviderType(ProviderType.Ledger); } public async updateProviderToInjectedAsync(): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'Contract Wrappers must be instantiated.'); if (_.isUndefined(this._cachedProvider)) { return; // Going from injected to injected, so we noop @@ -253,7 +256,7 @@ export class Blockchain { const userAddresses = await this._web3Wrapper.getAvailableAddressesAsync(); this._userAddressIfExists = userAddresses[0]; - this._zeroEx.setProvider(provider, this.networkId); + this._contractWrappers.setProvider(provider, this.networkId); await this.fetchTokenInformationAsync(); this._blockchainWatcher.startEmittingNetworkConnectionAndUserBalanceState(); @@ -264,10 +267,10 @@ export class Blockchain { public async setProxyAllowanceAsync(token: Token, amountInBaseUnits: BigNumber): Promise { utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TokenAddressIsInvalid); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'Contract Wrappers must be instantiated.'); this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.token.setProxyAllowanceAsync( + const txHash = await this._contractWrappers.token.setProxyAllowanceAsync( token.address, this._userAddressIfExists, amountInBaseUnits, @@ -278,11 +281,11 @@ export class Blockchain { await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async transferAsync(token: Token, toAddress: string, amountInBaseUnits: BigNumber): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.token.transferAsync( + const txHash = await this._contractWrappers.token.transferAsync( token.address, this._userAddressIfExists, toAddress, @@ -326,13 +329,13 @@ export class Blockchain { return zeroExSignedOrder; } public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const shouldThrowOnInsufficientBalanceOrAllowance = true; this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.exchange.fillOrderAsync( + const txHash = await this._contractWrappers.exchange.fillOrderAsync( signedOrder, fillTakerTokenAmount, shouldThrowOnInsufficientBalanceOrAllowance, @@ -343,7 +346,7 @@ export class Blockchain { ); const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; - this._zeroEx.exchange.throwLogErrorsAsErrors(logs); + this._contractWrappers.exchange.throwLogErrorsAsErrors(logs); const logFill = _.find(logs, { event: 'LogFill' }); const args = (logFill.args as any) as LogFillContractEventArgs; const filledTakerTokenAmount = args.filledTakerTokenAmount; @@ -351,32 +354,32 @@ export class Blockchain { } public async cancelOrderAsync(signedOrder: SignedOrder, cancelTakerTokenAmount: BigNumber): Promise { this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.exchange.cancelOrderAsync(signedOrder, cancelTakerTokenAmount, { + const txHash = await this._contractWrappers.exchange.cancelOrderAsync(signedOrder, cancelTakerTokenAmount, { gasPrice: this._defaultGasPrice, }); const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; - this._zeroEx.exchange.throwLogErrorsAsErrors(logs); + this._contractWrappers.exchange.throwLogErrorsAsErrors(logs); const logCancel = _.find(logs, { event: ExchangeEvents.LogCancel }); const args = (logCancel.args as any) as LogCancelContractEventArgs; const cancelledTakerTokenAmount = args.cancelledTakerTokenAmount; return cancelledTakerTokenAmount; } public async getUnavailableTakerAmountAsync(orderHash: string): Promise { - utils.assert(ZeroEx.isValidOrderHash(orderHash), 'Must be valid orderHash'); - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); - const unavailableTakerAmount = await this._zeroEx.exchange.getUnavailableTakerAmountAsync(orderHash); + utils.assert(isValidOrderHash(orderHash), 'Must be valid orderHash'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); + const unavailableTakerAmount = await this._contractWrappers.exchange.getUnavailableTakerAmountAsync(orderHash); return unavailableTakerAmount; } public getExchangeContractAddressIfExists(): string | undefined { - return this._zeroEx.exchange.getContractAddress(); + return this._contractWrappers.exchange.getContractAddress(); } public async validateFillOrderThrowIfInvalidAsync( signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber, takerAddress: string, ): Promise { - await this._zeroEx.exchange.validateFillOrderThrowIfInvalidAsync( + await this._contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync( signedOrder, fillTakerTokenAmount, takerAddress, @@ -386,7 +389,7 @@ export class Blockchain { order: Order, cancelTakerTokenAmount: BigNumber, ): Promise { - await this._zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount); + await this._contractWrappers.exchange.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount); } public isValidAddress(address: string): boolean { const lowercaseAddress = address.toLowerCase(); @@ -421,7 +424,7 @@ export class Blockchain { return newTokenBalancePromise; } public async signOrderHashAsync(orderHash: string): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); const makerAddress = this._userAddressIfExists; // If makerAddress is undefined, this means they have a web3 instance injected into their browser // but no account addresses associated with it. @@ -438,11 +441,8 @@ export class Blockchain { if ((isParityNode && !isLedgerSigner) || isTestRpc || isLedgerSigner) { shouldAddPersonalMessagePrefix = false; } - const ecSignature = await this._zeroEx.signOrderHashAsync( - orderHash, - makerAddress, - shouldAddPersonalMessagePrefix, - ); + const provider = this._contractWrappers.getProvider(); + const ecSignature = await signOrderHashAsync(provider, orderHash, makerAddress, shouldAddPersonalMessagePrefix); this._dispatcher.updateECSignature(ecSignature); return ecSignature; } @@ -461,11 +461,11 @@ export class Blockchain { return balanceInWei; } public async convertEthToWrappedEthTokensAsync(etherTokenAddress: string, amount: BigNumber): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.etherToken.depositAsync( + const txHash = await this._contractWrappers.etherToken.depositAsync( etherTokenAddress, amount, this._userAddressIfExists, @@ -476,11 +476,11 @@ export class Blockchain { await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); this._showFlashMessageIfLedger(); - const txHash = await this._zeroEx.etherToken.withdrawAsync( + const txHash = await this._contractWrappers.etherToken.withdrawAsync( etherTokenAddress, amount, this._userAddressIfExists, @@ -507,7 +507,7 @@ export class Blockchain { ownerAddressIfExists: string, tokenAddress: string, ): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); if (_.isUndefined(ownerAddressIfExists)) { const zero = new BigNumber(0); @@ -516,14 +516,16 @@ export class Blockchain { let balance = new BigNumber(0); let allowance = new BigNumber(0); if (this._doesUserAddressExist()) { - balance = await this._zeroEx.token.getBalanceAsync(tokenAddress, ownerAddressIfExists); - allowance = await this._zeroEx.token.getProxyAllowanceAsync(tokenAddress, ownerAddressIfExists); + balance = await this._contractWrappers.token.getBalanceAsync(tokenAddress, ownerAddressIfExists); + allowance = await this._contractWrappers.token.getProxyAllowanceAsync(tokenAddress, ownerAddressIfExists); } return [balance, allowance]; } public async getUserAccountsAsync(): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); - const userAccountsIfExists = await this._zeroEx.getAvailableAddressesAsync(); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); + const provider = this._contractWrappers.getProvider(); + const web3Wrapper = new Web3Wrapper(provider); + const userAccountsIfExists = await web3Wrapper.getAvailableAddressesAsync(); return userAccountsIfExists; } // HACK: When a user is using a Ledger, we simply dispatch the selected userAddress, which @@ -619,7 +621,9 @@ export class Blockchain { etherScanLinkIfExists, }), ); - const receipt = await this._zeroEx.awaitTransactionMinedAsync(txHash); + const provider = this._contractWrappers.getProvider(); + const web3Wrapper = new Web3Wrapper(provider); + const receipt = await web3Wrapper.awaitTransactionMinedAsync(txHash); return receipt; } private _doesUserAddressExist(): boolean { @@ -633,7 +637,7 @@ export class Blockchain { return; // short-circuit } - if (!_.isUndefined(this._zeroEx)) { + if (!_.isUndefined(this._contractWrappers)) { // Since we do not have an index on the `taker` address and want to show // transactions where an account is either the `maker` or `taker`, we loop // through all fill events, and filter/cache them client-side. @@ -642,14 +646,14 @@ export class Blockchain { } } private async _startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); // Fetch historical logs await this._fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); // Start a subscription for new logs - this._zeroEx.exchange.subscribe( + this._contractWrappers.exchange.subscribe( ExchangeEvents.LogFill, indexFilterValues, async (err: Error, decodedLogEvent: DecodedLogEvent) => { @@ -684,7 +688,7 @@ export class Blockchain { fromBlock, toBlock: 'latest' as BlockParam, }; - const decodedLogs = await this._zeroEx.exchange.getLogsAsync( + const decodedLogs = await this._contractWrappers.exchange.getLogsAsync( ExchangeEvents.LogFill, blockRange, indexFilterValues, @@ -741,11 +745,11 @@ export class Blockchain { } } private _stopWatchingExchangeLogFillEvents(): void { - this._zeroEx.exchange.unsubscribeAll(); + this._contractWrappers.exchange.unsubscribeAll(); } private async _getTokenRegistryTokensByAddressAsync(): Promise { - utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); - const tokenRegistryTokens = await this._zeroEx.tokenRegistry.getTokensAsync(); + utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.'); + const tokenRegistryTokens = await this._contractWrappers.tokenRegistry.getTokensAsync(); const tokenByAddress: TokenByAddress = {}; _.each(tokenRegistryTokens, (t: ZeroExToken, i: number) => { @@ -787,14 +791,12 @@ export class Blockchain { const provider = await Blockchain._getProviderAsync(injectedWeb3, networkIdIfExists); this.networkId = !_.isUndefined(networkIdIfExists) ? networkIdIfExists - : configs.IS_MAINNET_ENABLED - ? constants.NETWORK_ID_MAINNET - : constants.NETWORK_ID_KOVAN; + : configs.IS_MAINNET_ENABLED ? constants.NETWORK_ID_MAINNET : constants.NETWORK_ID_KOVAN; this._dispatcher.updateNetworkId(this.networkId); const zeroExConfigs = { networkId: this.networkId, }; - this._zeroEx = new ZeroEx(provider, zeroExConfigs); + this._contractWrappers = new ContractWrappers(provider, zeroExConfigs); this._updateProviderName(injectedWeb3); const shouldPollUserAddress = true; this._web3Wrapper = new Web3Wrapper(provider); -- cgit