From 0eaca6c691d92a10b08c0e69306291aa8de06bfb Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Fri, 13 Oct 2017 12:52:59 +0300 Subject: Make logs fetching and sunscriptions more type-safe --- src/contract_wrappers/contract_wrapper.ts | 29 +++++++++++++++-------------- src/contract_wrappers/exchange_wrapper.ts | 27 +++++++++++++++++---------- src/contract_wrappers/token_wrapper.ts | 15 +++++++++------ src/index.ts | 1 - src/types.ts | 16 ++++++++-------- src/utils/abi_decoder.ts | 5 +++-- test/0x.js_test.ts | 6 +++--- test/exchange_wrapper_test.ts | 16 +++++++++------- test/token_wrapper_test.ts | 29 ++++++++++++++++------------- 9 files changed, 80 insertions(+), 64 deletions(-) diff --git a/src/contract_wrappers/contract_wrapper.ts b/src/contract_wrappers/contract_wrapper.ts index f6ccfdee4..19dccc6f2 100644 --- a/src/contract_wrappers/contract_wrapper.ts +++ b/src/contract_wrappers/contract_wrapper.ts @@ -14,6 +14,7 @@ import { IndexedFilterValues, EventCallback, BlockParamLiteral, + ContractEventArgs, } from '../types'; import {constants} from '../utils/constants'; import {intervalUtils} from '../utils/interval_utils'; @@ -25,7 +26,7 @@ export class ContractWrapper { private _blockAndLogStreamer: BlockAndLogStreamer|undefined; private _blockAndLogStreamInterval: NodeJS.Timer; private _filters: {[filterToken: string]: Web3.FilterObject}; - private _filterCallbacks: {[filterToken: string]: EventCallback}; + private _filterCallbacks: {[filterToken: string]: EventCallback}; private _onLogAddedSubscriptionToken: string|undefined; private _onLogRemovedSubscriptionToken: string|undefined; constructor(web3Wrapper: Web3Wrapper, abiDecoder?: AbiDecoder) { @@ -37,9 +38,9 @@ export class ContractWrapper { this._onLogAddedSubscriptionToken = undefined; this._onLogRemovedSubscriptionToken = undefined; } - protected _subscribe(address: string, eventName: ContractEvents, - indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi, - callback: EventCallback): string { + protected _subscribe( + address: string, eventName: ContractEvents, indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi, + callback: EventCallback): string { const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi); if (_.isUndefined(this._blockAndLogStreamer)) { this._startBlockAndLogStream(); @@ -59,32 +60,32 @@ export class ContractWrapper { this._stopBlockAndLogStream(); } } - protected async _getLogsAsync(address: string, eventName: ContractEvents, subscriptionOpts: SubscriptionOpts, - indexFilterValues: IndexedFilterValues, - abi: Web3.ContractAbi): Promise { + protected async _getLogsAsync( + address: string, eventName: ContractEvents, subscriptionOpts: SubscriptionOpts, + indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi): Promise>> { const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, subscriptionOpts); const logs = await this._web3Wrapper.getLogsAsync(filter); const logsWithDecodedArguments = _.map(logs, this._tryToDecodeLogOrNoop.bind(this)); return logsWithDecodedArguments; } - protected _tryToDecodeLogOrNoop(log: Web3.LogEntry): LogWithDecodedArgs|RawLog { + protected _tryToDecodeLogOrNoop( + log: Web3.LogEntry): LogWithDecodedArgs|RawLog { if (_.isUndefined(this._abiDecoder)) { throw new Error(InternalZeroExError.NoAbiDecoder); } const logWithDecodedArgs = this._abiDecoder.tryToDecodeLogOrNoop(log); return logWithDecodedArgs; } - protected async _instantiateContractIfExistsAsync(artifact: Artifact, - addressIfExists?: string, - ): Promise { + protected async _instantiateContractIfExistsAsync( + artifact: Artifact, addressIfExists?: string): Promise { const contractInstance = - await this._web3Wrapper.getContractInstanceFromArtifactAsync(artifact, addressIfExists); + await this._web3Wrapper.getContractInstanceFromArtifactAsync(artifact, addressIfExists); return contractInstance; } - private _onLogStateChanged(removed: boolean, log: Web3.LogEntry): void { + private _onLogStateChanged(removed: boolean, log: Web3.LogEntry): void { _.forEach(this._filters, (filter: Web3.FilterObject, filterToken: string) => { if (filterUtils.matchesFilter(log, filter)) { - const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs; + const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs; const logEvent = { ...decodedLog, removed, diff --git a/src/contract_wrappers/exchange_wrapper.ts b/src/contract_wrappers/exchange_wrapper.ts index 9e4936de6..739fe74c6 100644 --- a/src/contract_wrappers/exchange_wrapper.ts +++ b/src/contract_wrappers/exchange_wrapper.ts @@ -1,4 +1,5 @@ import * as _ from 'lodash'; +import * as Web3 from 'web3'; import * as BigNumber from 'bignumber.js'; import {schemas} from '0x-json-schemas'; import {Web3Wrapper} from '../web3_wrapper'; @@ -28,6 +29,8 @@ import { OrderTransactionOpts, RawLog, EventCallback, + ExchangeContractEventArgs, + DecodedLogArgs, } from '../types'; import {assert} from '../utils/assert'; import {utils} from '../utils/utils'; @@ -654,13 +657,14 @@ 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(eventName: ExchangeEvents, indexFilterValues: IndexedFilterValues, - callback: EventCallback): Promise { + public async subscribeAsync( + eventName: ExchangeEvents, indexFilterValues: IndexedFilterValues, + callback: EventCallback): Promise { assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.isFunction('callback', callback); const exchangeContractAddress = await this.getContractAddressAsync(); - const subscriptionToken = this._subscribe( + const subscriptionToken = this._subscribe( exchangeContractAddress, eventName, indexFilterValues, artifacts.ExchangeArtifact.abi, callback, ); this._activeSubscriptions.push(subscriptionToken); @@ -682,13 +686,14 @@ export class ExchangeWrapper extends ContractWrapper { * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` * @return Array of logs that match the parameters */ - public async getLogsAsync(eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts, - indexFilterValues: IndexedFilterValues): Promise { + public async getLogsAsync( + eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts, indexFilterValues: IndexedFilterValues, + ): Promise>> { assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents); assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); const exchangeContractAddress = await this.getContractAddressAsync(); - const logs = await this._getLogsAsync( + const logs = await this._getLogsAsync( exchangeContractAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.ExchangeArtifact.abi, ); return logs; @@ -799,12 +804,14 @@ export class ExchangeWrapper extends ContractWrapper { } /** * Checks if logs contain LogError, which is emmited by Exchange contract on transaction failure. - * @param logsWithDecodedArgs Transaction logs as returned by `zeroEx.awaitTransactionMinedAsync` + * @param logs Transaction logs as returned by `zeroEx.awaitTransactionMinedAsync` */ - public throwLogErrorsAsErrors(logsWithDecodedArgs: LogWithDecodedArgs[]): void { - const errLog = _.find(logsWithDecodedArgs, {event: ExchangeEvents.LogError}); + public throwLogErrorsAsErrors(logs: Array|Web3.LogEntry>): void { + const errLog = _.find(logs, { + event: ExchangeEvents.LogError, + }) as LogWithDecodedArgs|undefined; if (!_.isUndefined(errLog)) { - const logArgs: LogErrorContractEventArgs = errLog.args as any; + const logArgs = errLog.args; const errCode = logArgs.errorId.toNumber(); const errMessage = this._exchangeContractErrCodesToMsg[errCode]; throw new Error(errMessage); diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts index abd090f7e..8dc4e61c5 100644 --- a/src/contract_wrappers/token_wrapper.ts +++ b/src/contract_wrappers/token_wrapper.ts @@ -16,6 +16,7 @@ import { MethodOpts, LogWithDecodedArgs, EventCallback, + TokenContractEventArgs, } from '../types'; const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47155; @@ -251,13 +252,14 @@ export class TokenWrapper extends ContractWrapper { * @param callback Callback that gets called when a log is added/removed * @return Subscription token used later to unsubscribe */ - public subscribe(tokenAddress: string, eventName: TokenEvents, indexFilterValues: IndexedFilterValues, - callback: EventCallback): string { + public subscribe( + tokenAddress: string, eventName: TokenEvents, indexFilterValues: IndexedFilterValues, + callback: EventCallback): string { assert.isETHAddressHex('tokenAddress', tokenAddress); assert.doesBelongToStringEnum('eventName', eventName, TokenEvents); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.isFunction('callback', callback); - const subscriptionToken = this._subscribe( + const subscriptionToken = this._subscribe( tokenAddress, eventName, indexFilterValues, artifacts.TokenArtifact.abi, callback, ); this._activeSubscriptions.push(subscriptionToken); @@ -280,13 +282,14 @@ export class TokenWrapper extends ContractWrapper { * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` * @return Array of logs that match the parameters */ - public async getLogsAsync(tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts, - indexFilterValues: IndexedFilterValues): Promise { + public async getLogsAsync( + tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts, + indexFilterValues: IndexedFilterValues): Promise>> { assert.isETHAddressHex('tokenAddress', tokenAddress); assert.doesBelongToStringEnum('eventName', eventName, TokenEvents); assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - const logs = await this._getLogsAsync( + const logs = await this._getLogsAsync( tokenAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.TokenArtifact.abi, ); return logs; diff --git a/src/index.ts b/src/index.ts index 048050c7a..f287a8c57 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,7 +32,6 @@ export { ZeroExConfig, TransactionReceiptWithDecodedLogs, LogWithDecodedArgs, - DecodedLogArgs, MethodOpts, OrderTransactionOpts, FilterObject, diff --git a/src/types.ts b/src/types.ts index 8c0bc1cf9..d933404b7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -36,12 +36,12 @@ export type OrderAddresses = [string, string, string, string, string]; export type OrderValues = [BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber, BigNumber.BigNumber]; -export interface LogEvent extends LogWithDecodedArgs { +export interface LogEvent extends LogWithDecodedArgs { removed: boolean; } -export type EventCallbackAsync = (log: LogEvent) => Promise; -export type EventCallbackSync = (log: LogEvent) => void; -export type EventCallback = EventCallbackSync|EventCallbackAsync; +export type EventCallbackAsync = (log: LogEvent) => Promise; +export type EventCallbackSync = (log: LogEvent) => void; +export type EventCallback = EventCallbackSync|EventCallbackAsync; export interface ExchangeContract extends Web3.ContractInstance { isValidSignature: { callAsync: (signerAddressHex: string, dataHex: string, v: number, r: string, s: string, @@ -419,15 +419,15 @@ export interface DecodedLogArgs { [argName: string]: ContractEventArg; } -export interface DecodedArgs { - args: DecodedLogArgs; +export interface DecodedArgs { + args: ArgsType; event: string; } -export interface LogWithDecodedArgs extends Web3.LogEntry, DecodedArgs {} +export interface LogWithDecodedArgs extends Web3.LogEntry, DecodedArgs {} export interface TransactionReceiptWithDecodedLogs extends Web3.TransactionReceipt { - logs: Array; + logs: Array|Web3.LogEntry>; } export interface Artifact { diff --git a/src/utils/abi_decoder.ts b/src/utils/abi_decoder.ts index 52b114c12..a6c45bee7 100644 --- a/src/utils/abi_decoder.ts +++ b/src/utils/abi_decoder.ts @@ -1,7 +1,7 @@ import * as Web3 from 'web3'; import * as _ from 'lodash'; import * as BigNumber from 'bignumber.js'; -import {AbiType, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes} from '../types'; +import {AbiType, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes, ContractEventArgs} from '../types'; import * as SolidityCoder from 'web3/lib/solidity/coder'; export class AbiDecoder { @@ -11,7 +11,8 @@ export class AbiDecoder { _.map(abiArrays, this.addABI.bind(this)); } // This method can only decode logs from the 0x smart contracts - public tryToDecodeLogOrNoop(log: Web3.LogEntry): LogWithDecodedArgs|RawLog { + public tryToDecodeLogOrNoop( + log: Web3.LogEntry): LogWithDecodedArgs|RawLog { const methodId = log.topics[0]; const event = this.methodIds[methodId]; if (_.isUndefined(event)) { diff --git a/test/0x.js_test.ts b/test/0x.js_test.ts index cc6b91e99..dd5dd19b1 100644 --- a/test/0x.js_test.ts +++ b/test/0x.js_test.ts @@ -4,7 +4,7 @@ import {chaiSetup} from './utils/chai_setup'; import 'mocha'; import * as BigNumber from 'bignumber.js'; import * as Sinon from 'sinon'; -import {ZeroEx, Order, ZeroExError, LogWithDecodedArgs} from '../src'; +import {ZeroEx, Order, ZeroExError, LogWithDecodedArgs, ApprovalContractEventArgs, TokenEvents} from '../src'; import {constants} from './utils/constants'; import {TokenUtils} from './utils/token_utils'; import {web3Factory} from './utils/web3_factory'; @@ -223,8 +223,8 @@ describe('ZeroEx library', () => { const proxyAddress = await zeroEx.proxy.getContractAddressAsync(); const txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(zrxTokenAddress, coinbase); const txReceiptWithDecodedLogs = await zeroEx.awaitTransactionMinedAsync(txHash); - const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs; - expect(log.event).to.be.equal('Approval'); + const log = txReceiptWithDecodedLogs.logs[0] as LogWithDecodedArgs; + expect(log.event).to.be.equal(TokenEvents.Approval); expect(log.args._owner).to.be.equal(coinbase); expect(log.args._spender).to.be.equal(proxyAddress); expect(log.args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); diff --git a/test/exchange_wrapper_test.ts b/test/exchange_wrapper_test.ts index afc33f1f4..1bedfc4da 100644 --- a/test/exchange_wrapper_test.ts +++ b/test/exchange_wrapper_test.ts @@ -18,6 +18,7 @@ import { OrderCancellationRequest, OrderFillRequest, LogFillContractEventArgs, + LogCancelContractEventArgs, OrderFillOrKillRequest, LogEvent, } from '../src'; @@ -651,7 +652,7 @@ describe('ExchangeWrapper', () => { // Source: https://github.com/mochajs/mocha/issues/2407 it('Should receive the LogFill event when an order is filled', (done: DoneCallback) => { (async () => { - const callback = (logEvent: LogEvent) => { + const callback = (logEvent: LogEvent) => { expect(logEvent.event).to.be.equal(ExchangeEvents.LogFill); done(); }; @@ -665,7 +666,7 @@ describe('ExchangeWrapper', () => { }); it('Should receive the LogCancel event when an order is cancelled', (done: DoneCallback) => { (async () => { - const callback = (logEvent: LogEvent) => { + const callback = (logEvent: LogEvent) => { expect(logEvent.event).to.be.equal(ExchangeEvents.LogCancel); done(); }; @@ -677,7 +678,7 @@ describe('ExchangeWrapper', () => { }); it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => { (async () => { - const callbackNeverToBeCalled = (logEvent: LogEvent) => { + const callbackNeverToBeCalled = (logEvent: LogEvent) => { done(new Error('Expected this subscription to have been cancelled')); }; await zeroEx.exchange.subscribeAsync( @@ -687,7 +688,7 @@ describe('ExchangeWrapper', () => { const newProvider = web3Factory.getRpcProvider(); await zeroEx.setProviderAsync(newProvider); - const callback = (logEvent: LogEvent) => { + const callback = (logEvent: LogEvent) => { expect(logEvent.event).to.be.equal(ExchangeEvents.LogFill); done(); }; @@ -701,7 +702,7 @@ describe('ExchangeWrapper', () => { }); it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { (async () => { - const callbackNeverToBeCalled = (logEvent: LogEvent) => { + const callbackNeverToBeCalled = (logEvent: LogEvent) => { done(new Error('Expected this subscription to have been cancelled')); }; const subscriptionToken = await zeroEx.exchange.subscribeAsync( @@ -811,11 +812,12 @@ describe('ExchangeWrapper', () => { const indexFilterValues = { maker: differentMakerAddress, }; - const logs = await zeroEx.exchange.getLogsAsync( + const logs = await zeroEx.exchange.getLogsAsync( eventName, subscriptionOpts, indexFilterValues, ); expect(logs).to.have.length(1); - expect(logs[0].args.maker).to.be.equal(differentMakerAddress); + const args = logs[0].args; + expect(args.maker).to.be.equal(differentMakerAddress); }); }); }); diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index 50f2db2ac..f1f6543b7 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -14,6 +14,7 @@ import { ContractEvent, TransferContractEventArgs, ApprovalContractEventArgs, + TokenContractEventArgs, LogWithDecodedArgs, LogEvent, } from '../src'; @@ -357,9 +358,9 @@ describe('TokenWrapper', () => { // Source: https://github.com/mochajs/mocha/issues/2407 it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => { (async () => { - const callback = (logEvent: LogEvent) => { + const callback = (logEvent: LogEvent) => { expect(logEvent).to.not.be.undefined(); - const args = logEvent.args as any as TransferContractEventArgs; + const args = logEvent.args; expect(args._from).to.be.equal(coinbase); expect(args._to).to.be.equal(addressWithoutFunds); expect(args._value).to.be.bignumber.equal(transferAmount); @@ -372,9 +373,9 @@ describe('TokenWrapper', () => { }); it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => { (async () => { - const callback = (logEvent: LogEvent) => { + const callback = (logEvent: LogEvent) => { expect(logEvent).to.not.be.undefined(); - const args = logEvent.args as any as ApprovalContractEventArgs; + const args = logEvent.args; expect(args._owner).to.be.equal(coinbase); expect(args._spender).to.be.equal(addressWithoutFunds); expect(args._value).to.be.bignumber.equal(allowanceAmount); @@ -387,13 +388,13 @@ describe('TokenWrapper', () => { }); it('Outstanding subscriptions are cancelled when zeroEx.setProviderAsync called', (done: DoneCallback) => { (async () => { - const callbackNeverToBeCalled = (logEvent: LogEvent) => { + const callbackNeverToBeCalled = (logEvent: LogEvent) => { done(new Error('Expected this subscription to have been cancelled')); }; zeroEx.token.subscribe( tokenAddress, TokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled, ); - const callbackToBeCalled = (logEvent: LogEvent) => { + const callbackToBeCalled = (logEvent: LogEvent) => { done(); }; const newProvider = web3Factory.getRpcProvider(); @@ -406,7 +407,7 @@ describe('TokenWrapper', () => { }); it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => { (async () => { - const callbackNeverToBeCalled = (logEvent: LogEvent) => { + const callbackNeverToBeCalled = (logEvent: LogEvent) => { done(new Error('Expected this subscription to have been cancelled')); }; const subscriptionToken = zeroEx.token.subscribe( @@ -435,14 +436,15 @@ describe('TokenWrapper', () => { await zeroEx.awaitTransactionMinedAsync(txHash); const eventName = TokenEvents.Approval; const indexFilterValues = {}; - const logs = await zeroEx.token.getLogsAsync( + const logs = await zeroEx.token.getLogsAsync( tokenAddress, eventName, subscriptionOpts, indexFilterValues, ); expect(logs).to.have.length(1); + const args = logs[0].args; expect(logs[0].event).to.be.equal(eventName); - expect(logs[0].args._owner).to.be.equal(coinbase); - expect(logs[0].args._spender).to.be.equal(tokenTransferProxyAddress); - expect(logs[0].args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); + expect(args._owner).to.be.equal(coinbase); + expect(args._spender).to.be.equal(tokenTransferProxyAddress); + expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); }); it('should only get the logs with the correct event name', async () => { txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(tokenAddress, coinbase); @@ -463,11 +465,12 @@ describe('TokenWrapper', () => { const indexFilterValues = { _owner: coinbase, }; - const logs = await zeroEx.token.getLogsAsync( + const logs = await zeroEx.token.getLogsAsync( tokenAddress, eventName, subscriptionOpts, indexFilterValues, ); expect(logs).to.have.length(1); - expect(logs[0].args._owner).to.be.equal(coinbase); + const args = logs[0].args; + expect(args._owner).to.be.equal(coinbase); }); }); }); -- cgit v1.2.3