diff options
author | Leonid Logvinov <logvinov.leon@gmail.com> | 2018-03-28 22:26:05 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-03-28 22:26:05 +0800 |
commit | 8926dac78c3ac8d75ad5ffd5b4febe36def4e53c (patch) | |
tree | 01c1b3f8dba486beb4e83e67ad0bc35c3da6a14e /packages | |
parent | 18cac3f0927a0424e3618fd56dba73fc9dfc0288 (diff) | |
parent | 01e27426d643b525661e044dbb8c8f27734329e7 (diff) | |
download | dexon-0x-contracts-8926dac78c3ac8d75ad5ffd5b4febe36def4e53c.tar.gz dexon-0x-contracts-8926dac78c3ac8d75ad5ffd5b4febe36def4e53c.tar.zst dexon-0x-contracts-8926dac78c3ac8d75ad5ffd5b4febe36def4e53c.zip |
Merge pull request #482 from 0xProject/feature/web3-types
Move common types out of web3 types
Diffstat (limited to 'packages')
54 files changed, 490 insertions, 498 deletions
diff --git a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts index ad7727de5..6c96428ed 100644 --- a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts @@ -1,4 +1,4 @@ -import { BlockParamLiteral, LogWithDecodedArgs, RawLog } from '@0xproject/types'; +import { BlockParamLiteral, ContractAbi, FilterObject, LogEntry, LogWithDecodedArgs, RawLog } from '@0xproject/types'; import { AbiDecoder, intervalUtils } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import { Block, BlockAndLogStreamer } from 'ethereumjs-blockstream'; @@ -35,7 +35,7 @@ export class ContractWrapper { private _abiDecoder?: AbiDecoder; private _blockAndLogStreamerIfExists?: BlockAndLogStreamer; private _blockAndLogStreamIntervalIfExists?: NodeJS.Timer; - private _filters: { [filterToken: string]: Web3.FilterObject }; + private _filters: { [filterToken: string]: FilterObject }; private _filterCallbacks: { [filterToken: string]: EventCallback<ContractEventArgs>; }; @@ -75,7 +75,7 @@ export class ContractWrapper { address: string, eventName: ContractEvents, indexFilterValues: IndexedFilterValues, - abi: Web3.ContractAbi, + abi: ContractAbi, callback: EventCallback<ArgsType>, ): string { const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi); @@ -92,7 +92,7 @@ export class ContractWrapper { eventName: ContractEvents, blockRange: BlockRange, indexFilterValues: IndexedFilterValues, - abi: Web3.ContractAbi, + abi: ContractAbi, ): Promise<Array<LogWithDecodedArgs<ArgsType>>> { const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, blockRange); const logs = await this._web3Wrapper.getLogsAsync(filter); @@ -100,7 +100,7 @@ export class ContractWrapper { return logsWithDecodedArguments; } protected _tryToDecodeLogOrNoop<ArgsType extends ContractEventArgs>( - log: Web3.LogEntry, + log: LogEntry, ): LogWithDecodedArgs<ArgsType> | RawLog { if (_.isUndefined(this._abiDecoder)) { throw new Error(InternalZeroExError.NoAbiDecoder); @@ -111,7 +111,7 @@ export class ContractWrapper { protected async _getContractAbiAndAddressFromArtifactsAsync( artifact: Artifact, addressIfExists?: string, - ): Promise<[Web3.ContractAbi, string]> { + ): Promise<[ContractAbi, string]> { let contractAddress: string; if (_.isUndefined(addressIfExists)) { if (_.isUndefined(artifact.networks[this._networkId])) { @@ -125,7 +125,7 @@ export class ContractWrapper { if (!doesContractExist) { throw new Error(CONTRACT_NAME_TO_NOT_FOUND_ERROR[artifact.contract_name]); } - const abiAndAddress: [Web3.ContractAbi, string] = [artifact.abi, contractAddress]; + const abiAndAddress: [ContractAbi, string] = [artifact.abi, contractAddress]; return abiAndAddress; } protected _getContractAddress(artifact: Artifact, addressIfExists?: string): string { @@ -139,8 +139,8 @@ export class ContractWrapper { return addressIfExists; } } - private _onLogStateChanged<ArgsType extends ContractEventArgs>(isRemoved: boolean, log: Web3.LogEntry): void { - _.forEach(this._filters, (filter: Web3.FilterObject, filterToken: string) => { + private _onLogStateChanged<ArgsType extends ContractEventArgs>(isRemoved: boolean, log: LogEntry): void { + _.forEach(this._filters, (filter: FilterObject, filterToken: string) => { if (filterUtils.matchesFilter(log, filter)) { const decodedLog = this._tryToDecodeLogOrNoop(log) as LogWithDecodedArgs<ArgsType>; const logEvent = { diff --git a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts index 59bd4db6b..6b5a75a9a 100644 --- a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts @@ -3,6 +3,7 @@ import { BlockParamLiteral, DecodedLogArgs, ECSignature, + LogEntry, LogWithDecodedArgs, Order, SignedOrder, @@ -10,7 +11,6 @@ import { import { AbiDecoder, BigNumber } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import { artifacts } from '../artifacts'; import { @@ -863,7 +863,7 @@ export class ExchangeWrapper extends ContractWrapper { * Checks if logs contain LogError, which is emitted by Exchange contract on transaction failure. * @param logs Transaction logs as returned by `zeroEx.awaitTransactionMinedAsync` */ - public throwLogErrorsAsErrors(logs: Array<LogWithDecodedArgs<DecodedLogArgs> | Web3.LogEntry>): void { + public throwLogErrorsAsErrors(logs: Array<LogWithDecodedArgs<DecodedLogArgs> | LogEntry>): void { const errLog = _.find(logs, { event: ExchangeEvents.LogError, }); diff --git a/packages/0x.js/src/globals.d.ts b/packages/0x.js/src/globals.d.ts index e2c321f38..3e8ea21bc 100644 --- a/packages/0x.js/src/globals.d.ts +++ b/packages/0x.js/src/globals.d.ts @@ -37,12 +37,13 @@ declare module 'ethereumjs-abi' { // truffle-hdwallet-provider declarations declare module 'truffle-hdwallet-provider' { + import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types'; import * as Web3 from 'web3'; class HDWalletProvider implements Web3.Provider { constructor(mnemonic: string, rpcUrl: string); public sendAsync( - payload: Web3.JSONRPCRequestPayload, - callback: (err: Error, result: Web3.JSONRPCResponsePayload) => void, + payload: JSONRPCRequestPayload, + callback: (err: Error, result: JSONRPCResponsePayload) => void, ): void; } export = HDWalletProvider; diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts index 7885fb82a..e353a1d3d 100644 --- a/packages/0x.js/src/index.ts +++ b/packages/0x.js/src/index.ts @@ -16,7 +16,6 @@ export { MethodOpts, OrderTransactionOpts, TransactionOpts, - FilterObject, LogEvent, DecodedLogEvent, EventWatcherCallback, @@ -28,6 +27,7 @@ export { export { BlockParamLiteral, + FilterObject, BlockParam, ContractEventArg, LogWithDecodedArgs, diff --git a/packages/0x.js/src/order_watcher/event_watcher.ts b/packages/0x.js/src/order_watcher/event_watcher.ts index e67b93251..246ab8292 100644 --- a/packages/0x.js/src/order_watcher/event_watcher.ts +++ b/packages/0x.js/src/order_watcher/event_watcher.ts @@ -1,9 +1,7 @@ +import { BlockParamLiteral, LogEntry } from '@0xproject/types'; import { intervalUtils } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; - -import { BlockParamLiteral } from '@0xproject/types'; import { EventWatcherCallback, ZeroExError } from '../types'; import { assert } from '../utils/assert'; @@ -23,7 +21,7 @@ export class EventWatcher { private _web3Wrapper: Web3Wrapper; private _pollingIntervalMs: number; private _intervalIdIfExists?: NodeJS.Timer; - private _lastEvents: Web3.LogEntry[] = []; + private _lastEvents: LogEntry[] = []; constructor(web3Wrapper: Web3Wrapper, pollingIntervalIfExistsMs: undefined | number) { this._web3Wrapper = web3Wrapper; this._pollingIntervalMs = _.isUndefined(pollingIntervalIfExistsMs) @@ -69,7 +67,7 @@ export class EventWatcher { await this._emitDifferencesAsync(newEvents, LogEventState.Added, callback); this._lastEvents = pendingEvents; } - private async _getEventsAsync(): Promise<Web3.LogEntry[]> { + private async _getEventsAsync(): Promise<LogEntry[]> { const eventFilter = { fromBlock: BlockParamLiteral.Pending, toBlock: BlockParamLiteral.Pending, @@ -78,7 +76,7 @@ export class EventWatcher { return events; } private async _emitDifferencesAsync( - logs: Web3.LogEntry[], + logs: LogEntry[], logEventState: LogEventState, callback: EventWatcherCallback, ): Promise<void> { diff --git a/packages/0x.js/src/types.ts b/packages/0x.js/src/types.ts index 65342b694..38cfb6306 100644 --- a/packages/0x.js/src/types.ts +++ b/packages/0x.js/src/types.ts @@ -3,7 +3,10 @@ import { BigNumber } from '@0xproject/utils'; import { BlockParam, BlockParamLiteral, + ContractAbi, ContractEventArg, + FilterObject, + LogEntryEvent, LogWithDecodedArgs, Order, SignedOrder, @@ -48,7 +51,7 @@ export type OrderAddresses = [string, string, string, string, string]; export type OrderValues = [BigNumber, BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]; -export type LogEvent = Web3.LogEntryEvent; +export type LogEvent = LogEntryEvent; export interface DecodedLogEvent<ArgsType> { isRemoved: boolean; log: LogWithDecodedArgs<ArgsType>; @@ -197,7 +200,7 @@ export type ArtifactContractName = 'ZRX' | 'TokenTransferProxy' | 'TokenRegistry export interface Artifact { contract_name: ArtifactContractName; - abi: Web3.ContractAbi; + abi: ContractAbi; networks: { [networkId: number]: { address: string; @@ -222,7 +225,7 @@ export interface ValidateOrderFillableOpts { * flag when running Parity). */ export interface MethodOpts { - defaultBlock?: Web3.BlockParam; + defaultBlock?: BlockParam; } /* @@ -242,8 +245,6 @@ export interface OrderTransactionOpts extends TransactionOpts { shouldValidate?: boolean; } -export type FilterObject = Web3.FilterObject; - export enum TradeSide { Maker = 'maker', Taker = 'taker', diff --git a/packages/0x.js/src/utils/filter_utils.ts b/packages/0x.js/src/utils/filter_utils.ts index 97205ace3..c5df7321e 100644 --- a/packages/0x.js/src/utils/filter_utils.ts +++ b/packages/0x.js/src/utils/filter_utils.ts @@ -1,8 +1,16 @@ +import { + ConstructorAbi, + ContractAbi, + EventAbi, + FallbackAbi, + FilterObject, + LogEntry, + MethodAbi, +} from '@0xproject/types'; import * as ethUtil from 'ethereumjs-util'; import * as jsSHA3 from 'js-sha3'; import * as _ from 'lodash'; import * as uuid from 'uuid/v4'; -import * as Web3 from 'web3'; import { BlockRange, ContractEvents, IndexedFilterValues } from '../types'; @@ -16,15 +24,15 @@ export const filterUtils = { address: string, eventName: ContractEvents, indexFilterValues: IndexedFilterValues, - abi: Web3.ContractAbi, + abi: ContractAbi, blockRange?: BlockRange, - ): Web3.FilterObject { - const eventAbi = _.find(abi, { name: eventName }) as Web3.EventAbi; + ): FilterObject { + const eventAbi = _.find(abi, { name: eventName }) as EventAbi; const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi, eventName); const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature)); const topicsForIndexedArgs = filterUtils.getTopicsForIndexedArgs(eventAbi, indexFilterValues); const topics = [topicForEventSignature, ...topicsForIndexedArgs]; - let filter: Web3.FilterObject = { + let filter: FilterObject = { address, topics, }; @@ -36,12 +44,12 @@ export const filterUtils = { } return filter; }, - getEventSignatureFromAbiByName(eventAbi: Web3.EventAbi, eventName: ContractEvents): string { + getEventSignatureFromAbiByName(eventAbi: EventAbi, eventName: ContractEvents): string { const types = _.map(eventAbi.inputs, 'type'); const signature = `${eventAbi.name}(${types.join(',')})`; return signature; }, - getTopicsForIndexedArgs(abi: Web3.EventAbi, indexFilterValues: IndexedFilterValues): Array<string | null> { + getTopicsForIndexedArgs(abi: EventAbi, indexFilterValues: IndexedFilterValues): Array<string | null> { const topics: Array<string | null> = []; for (const eventInput of abi.inputs) { if (!eventInput.indexed) { @@ -60,7 +68,7 @@ export const filterUtils = { } return topics; }, - matchesFilter(log: Web3.LogEntry, filter: Web3.FilterObject): boolean { + matchesFilter(log: LogEntry, filter: FilterObject): boolean { if (!_.isUndefined(filter.address) && log.address !== filter.address) { return false; } diff --git a/packages/0x.js/test/0x.js_test.ts b/packages/0x.js/test/0x.js_test.ts index 8ba2e53f7..70e85aa52 100644 --- a/packages/0x.js/test/0x.js_test.ts +++ b/packages/0x.js/test/0x.js_test.ts @@ -237,7 +237,7 @@ describe('ZeroEx library', () => { s: '0x2dea66f25a608bbae457e020fb6decb763deb8b7192abab624997242da248960', }; stubs = [ - Sinon.stub((zeroEx as any)._web3Wrapper, 'signTransactionAsync').returns(Promise.resolve(signature)), + Sinon.stub((zeroEx as any)._web3Wrapper, 'signMessageAsync').returns(Promise.resolve(signature)), Sinon.stub(ZeroEx, 'isValidSignature').returns(true), ]; diff --git a/packages/0x.js/test/event_watcher_test.ts b/packages/0x.js/test/event_watcher_test.ts index 93ee9cd1c..2fa6c0580 100644 --- a/packages/0x.js/test/event_watcher_test.ts +++ b/packages/0x.js/test/event_watcher_test.ts @@ -1,4 +1,5 @@ import { web3Factory } from '@0xproject/dev-utils'; +import { LogEntry } from '@0xproject/types'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as chai from 'chai'; import * as _ from 'lodash'; @@ -21,7 +22,7 @@ describe('EventWatcher', () => { let stubs: Sinon.SinonStub[] = []; let eventWatcher: EventWatcher; let web3Wrapper: Web3Wrapper; - const logA: Web3.LogEntry = { + const logA: LogEntry = { address: '0x71d271f8b14adef568f8f28f1587ce7271ac4ca5', blockHash: null, blockNumber: null, @@ -31,7 +32,7 @@ describe('EventWatcher', () => { transactionHash: '0x004881d38cd4a8f72f1a0d68c8b9b8124504706041ff37019c1d1ed6bfda8e17', transactionIndex: 0, }; - const logB: Web3.LogEntry = { + const logB: LogEntry = { address: '0x8d12a197cb00d4747a1fe03395095ce2a5cc6819', blockHash: null, blockNumber: null, @@ -41,7 +42,7 @@ describe('EventWatcher', () => { transactionHash: '0x01ef3c048b18d9b09ea195b4ed94cf8dd5f3d857a1905ff886b152cfb1166f25', transactionIndex: 0, }; - const logC: Web3.LogEntry = { + const logC: LogEntry = { address: '0x1d271f8b174adef58f1587ce68f8f27271ac4ca5', blockHash: null, blockNumber: null, @@ -64,7 +65,7 @@ describe('EventWatcher', () => { eventWatcher.unsubscribe(); }); it('correctly emits initial log events', (done: DoneCallback) => { - const logs: Web3.LogEntry[] = [logA, logB]; + const logs: LogEntry[] = [logA, logB]; const expectedLogEvents = [ { removed: false, @@ -89,8 +90,8 @@ describe('EventWatcher', () => { eventWatcher.subscribe(callback); }); it('correctly computes the difference and emits only changes', (done: DoneCallback) => { - const initialLogs: Web3.LogEntry[] = [logA, logB]; - const changedLogs: Web3.LogEntry[] = [logA, logC]; + const initialLogs: LogEntry[] = [logA, logB]; + const changedLogs: LogEntry[] = [logA, logC]; const expectedLogEvents = [ { removed: false, diff --git a/packages/abi-gen/package.json b/packages/abi-gen/package.json index 2fdf19320..3c20249dd 100644 --- a/packages/abi-gen/package.json +++ b/packages/abi-gen/package.json @@ -24,6 +24,7 @@ "homepage": "https://github.com/0xProject/0x-monorepo/packages/abi-gen/README.md", "dependencies": { "@0xproject/utils": "^0.4.3", + "@0xproject/types": "^0.4.1", "@0xproject/typescript-typings": "^0.0.1", "chalk": "^2.3.0", "glob": "^7.1.2", @@ -31,7 +32,6 @@ "lodash": "^4.17.4", "mkdirp": "^0.5.1", "to-snake-case": "^1.0.0", - "web3": "^0.20.0", "yargs": "^10.0.3" }, "devDependencies": { diff --git a/packages/abi-gen/src/index.ts b/packages/abi-gen/src/index.ts index 8932e4045..942bb12db 100644 --- a/packages/abi-gen/src/index.ts +++ b/packages/abi-gen/src/index.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node +import { AbiDefinition, ConstructorAbi, EventAbi, MethodAbi } from '@0xproject/types'; import { logUtils } from '@0xproject/utils'; import chalk from 'chalk'; import * as fs from 'fs'; @@ -10,7 +11,6 @@ import * as mkdirp from 'mkdirp'; import * as yargs from 'yargs'; import toSnakeCase = require('to-snake-case'); -import * as Web3 from 'web3'; import { ContextData, ContractsBackend, ParamKind } from './types'; import { utils } from './utils'; @@ -120,12 +120,12 @@ for (const abiFileName of abiFileNames) { process.exit(1); } - let ctor = ABI.find((abi: Web3.AbiDefinition) => abi.type === ABI_TYPE_CONSTRUCTOR) as Web3.ConstructorAbi; + let ctor = ABI.find((abi: AbiDefinition) => abi.type === ABI_TYPE_CONSTRUCTOR) as ConstructorAbi; if (_.isUndefined(ctor)) { ctor = utils.getEmptyConstructor(); // The constructor exists, but it's implicit in JSON's ABI definition } - const methodAbis = ABI.filter((abi: Web3.AbiDefinition) => abi.type === ABI_TYPE_METHOD) as Web3.MethodAbi[]; + const methodAbis = ABI.filter((abi: AbiDefinition) => abi.type === ABI_TYPE_METHOD) as MethodAbi[]; const methodsData = _.map(methodAbis, methodAbi => { _.map(methodAbi.inputs, (input, i: number) => { if (_.isEmpty(input.name)) { @@ -142,7 +142,7 @@ for (const abiFileName of abiFileNames) { return methodData; }); - const eventAbis = ABI.filter((abi: Web3.AbiDefinition) => abi.type === ABI_TYPE_EVENT) as Web3.EventAbi[]; + const eventAbis = ABI.filter((abi: AbiDefinition) => abi.type === ABI_TYPE_EVENT) as EventAbi[]; const contextData = { contractName: namedContent.name, diff --git a/packages/abi-gen/src/types.ts b/packages/abi-gen/src/types.ts index deddb1857..df5b1feaf 100644 --- a/packages/abi-gen/src/types.ts +++ b/packages/abi-gen/src/types.ts @@ -1,4 +1,4 @@ -import * as Web3 from 'web3'; +import { EventAbi, MethodAbi } from '@0xproject/types'; export enum ParamKind { Input = 'input', @@ -17,7 +17,7 @@ export enum ContractsBackend { Ethers = 'ethers', } -export interface Method extends Web3.MethodAbi { +export interface Method extends MethodAbi { singleReturnValue: boolean; hasReturnValue: boolean; } @@ -25,5 +25,5 @@ export interface Method extends Web3.MethodAbi { export interface ContextData { contractName: string; methods: Method[]; - events: Web3.EventAbi[]; + events: EventAbi[]; } diff --git a/packages/abi-gen/src/utils.ts b/packages/abi-gen/src/utils.ts index c4520ade0..755fbc71a 100644 --- a/packages/abi-gen/src/utils.ts +++ b/packages/abi-gen/src/utils.ts @@ -1,17 +1,12 @@ +import { ConstructorAbi, DataItem } from '@0xproject/types'; import * as fs from 'fs'; import * as _ from 'lodash'; import * as path from 'path'; -import * as Web3 from 'web3'; import { AbiType, ContractsBackend, ParamKind } from './types'; export const utils = { - solTypeToTsType( - paramKind: ParamKind, - backend: ContractsBackend, - solType: string, - components?: Web3.DataItem[], - ): string { + solTypeToTsType(paramKind: ParamKind, backend: ContractsBackend, solType: string, components?: DataItem[]): string { const trailingArrayRegex = /\[\d*\]$/; if (solType.match(trailingArrayRegex)) { const arrayItemSolType = solType.replace(trailingArrayRegex, ''); @@ -89,7 +84,7 @@ export const utils = { throw new Error(`Failed to read ${filename}: ${err}`); } }, - getEmptyConstructor(): Web3.ConstructorAbi { + getEmptyConstructor(): ConstructorAbi { return { type: AbiType.Constructor, stateMutability: 'nonpayable', diff --git a/packages/base-contract/package.json b/packages/base-contract/package.json index 554f0a41c..e9015713c 100644 --- a/packages/base-contract/package.json +++ b/packages/base-contract/package.json @@ -34,8 +34,7 @@ "@0xproject/web3-wrapper": "^0.3.1", "@0xproject/typescript-typings": "^0.0.1", "ethers-contracts": "^2.2.1", - "lodash": "^4.17.4", - "web3": "^0.20.0" + "lodash": "^4.17.4" }, "publishConfig": { "access": "public" diff --git a/packages/base-contract/src/index.ts b/packages/base-contract/src/index.ts index cc1e16a13..961da8842 100644 --- a/packages/base-contract/src/index.ts +++ b/packages/base-contract/src/index.ts @@ -1,16 +1,15 @@ -import { TxData, TxDataPayable } from '@0xproject/types'; +import { ContractAbi, DataItem, TxData, TxDataPayable } from '@0xproject/types'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as ethersContracts from 'ethers-contracts'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; export class BaseContract { protected _ethersInterface: ethersContracts.Interface; protected _web3Wrapper: Web3Wrapper; - public abi: Web3.ContractAbi; + public abi: ContractAbi; public address: string; protected static _transformABIData( - abis: Web3.DataItem[], + abis: DataItem[], values: any[], transformation: (type: string, value: any) => any, ): any { @@ -46,20 +45,20 @@ export class BaseContract { // 2. Global config passed in at library instantiation // 3. Gas estimate calculation + safety margin const removeUndefinedProperties = _.pickBy; - const txDataWithDefaults = { + const txDataWithDefaults = ({ to: this.address, ...removeUndefinedProperties(this._web3Wrapper.getContractDefaults()), ...removeUndefinedProperties(txData as any), // HACK: TS can't prove that T is spreadable. // Awaiting https://github.com/Microsoft/TypeScript/pull/13288 to be merged - }; + } as any) as TxData; if (_.isUndefined(txDataWithDefaults.gas) && !_.isUndefined(estimateGasAsync)) { const estimatedGas = await estimateGasAsync(txData); txDataWithDefaults.gas = estimatedGas; } return txDataWithDefaults; } - constructor(web3Wrapper: Web3Wrapper, abi: Web3.ContractAbi, address: string) { + constructor(web3Wrapper: Web3Wrapper, abi: ContractAbi, address: string) { this._web3Wrapper = web3Wrapper; this.abi = abi; this.address = address; diff --git a/packages/contract_templates/contract.handlebars b/packages/contract_templates/contract.handlebars index 132cd60cc..08310c8f2 100644 --- a/packages/contract_templates/contract.handlebars +++ b/packages/contract_templates/contract.handlebars @@ -5,7 +5,7 @@ // tslint:disable:no-consecutive-blank-lines // tslint:disable-next-line:no-unused-variable import { BaseContract } from '@0xproject/base-contract'; -import { TxData, TxDataPayable } from '@0xproject/types'; +import { BlockParam, BlockParamLiteral, CallData, ContractAbi, DataItem, MethodAbi, TxData, TxDataPayable } from '@0xproject/types'; import { BigNumber, classUtils, promisify } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as ethersContracts from 'ethers-contracts'; @@ -40,7 +40,7 @@ export class {{contractName}}Contract extends BaseContract { {{> tx contractName=../contractName}} {{/this.constant}} {{/each}} - constructor(web3Wrapper: Web3Wrapper, abi: Web3.ContractAbi, address: string) { + constructor(web3Wrapper: Web3Wrapper, abi: ContractAbi, address: string) { super(web3Wrapper, abi, address); classUtils.bindAll(this, ['_ethersInterface', 'address', 'abi', '_web3Wrapper']); } diff --git a/packages/contract_templates/partials/callAsync.handlebars b/packages/contract_templates/partials/callAsync.handlebars index 93d347145..e3fc2bdf9 100644 --- a/packages/contract_templates/partials/callAsync.handlebars +++ b/packages/contract_templates/partials/callAsync.handlebars @@ -1,27 +1,22 @@ {{#hasReturnValue}} async callAsync( {{> typed_params inputs=inputs}} -{{#this.payable}} - txData: TxDataPayable = {}, -{{/this.payable}} -{{^this.payable}} - txData: TxData = {}, -{{/this.payable}} - defaultBlock?: Web3.BlockParam, + callData: Partial<CallData> = {}, + defaultBlock?: BlockParam, ): Promise<{{> return_type outputs=outputs}}> { const self = this as {{contractName}}Contract; - const inputAbi = _.find(this.abi, {name: '{{this.name}}'}).inputs; - [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this)); + const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs; + [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self)); const encodedData = self._ethersInterface.functions.{{this.name}}( {{> params inputs=inputs}} ).data; - const callData = await self._applyDefaultsToTxDataAsync( + const callDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: encodedData, } ) - const rawCallResult = await self._web3Wrapper.callAsync(callData, defaultBlock); - const outputAbi = _.find(this.abi, {name: '{{this.name}}'}).outputs as Web3.DataItem[]; + const rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + const outputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).outputs; const outputParamsTypes = _.map(outputAbi, 'type'); let resultArray = ethersContracts.Interface.decodeParams(outputParamsTypes, rawCallResult) as any; resultArray = BaseContract._transformABIData(outputAbi, resultArray, BaseContract._lowercaseAddress.bind(this)); diff --git a/packages/contract_templates/partials/tx.handlebars b/packages/contract_templates/partials/tx.handlebars index d517a9f7f..f76de3a70 100644 --- a/packages/contract_templates/partials/tx.handlebars +++ b/packages/contract_templates/partials/tx.handlebars @@ -2,16 +2,16 @@ public {{this.name}} = { async sendTransactionAsync( {{> typed_params inputs=inputs}} {{#this.payable}} - txData: TxDataPayable = {}, + txData: Partial<TxDataPayable> = {}, {{/this.payable}} {{^this.payable}} - txData: TxData = {}, + txData: Partial<TxData> = {}, {{/this.payable}} ): Promise<string> { const self = this as {{contractName}}Contract; - const inputAbi = _.find(this.abi, {name: '{{this.name}}'}).inputs; - [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this)); - const encodedData = this._ethersInterface.functions.{{this.name}}( + const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs; + [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self)); + const encodedData = self._ethersInterface.functions.{{this.name}}( {{> params inputs=inputs}} ).data const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( @@ -24,17 +24,17 @@ public {{this.name}} = { {{> params inputs=inputs}} ), ); - const txHash = await this._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); return txHash; }, async estimateGasAsync( {{> typed_params inputs=inputs}} - txData: TxData = {}, + txData: Partial<TxData> = {}, ): Promise<number> { const self = this as {{contractName}}Contract; - const inputAbi = _.find(this.abi, {name: '{{this.name}}'}).inputs; + const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs; [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this)); - const encodedData = this._ethersInterface.functions.{{this.name}}( + const encodedData = self._ethersInterface.functions.{{this.name}}( {{> params inputs=inputs}} ).data const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( @@ -43,17 +43,16 @@ public {{this.name}} = { data: encodedData, } ); - const gas = await this._web3Wrapper.estimateGasAsync(txDataWithDefaults); + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); return gas; }, getABIEncodedTransactionData( {{> typed_params inputs=inputs}} - txData: TxData = {}, ): string { const self = this as {{contractName}}Contract; - const inputAbi = _.find(this.abi, {name: '{{this.name}}'}).inputs; - [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(this)); - const abiEncodedTransactionData = this._ethersInterface.functions.{{this.name}}( + const inputAbi = (_.find(self.abi, {name: '{{this.name}}'}) as MethodAbi).inputs; + [{{> params inputs=inputs}}] = BaseContract._transformABIData(inputAbi, [{{> params inputs=inputs}}], BaseContract._bigNumberToString.bind(self)); + const abiEncodedTransactionData = self._ethersInterface.functions.{{this.name}}( {{> params inputs=inputs}} ).data return abiEncodedTransactionData; diff --git a/packages/contracts/util/multi_sig_wrapper.ts b/packages/contracts/util/multi_sig_wrapper.ts index 3b83ccb7b..9f6dcec52 100644 --- a/packages/contracts/util/multi_sig_wrapper.ts +++ b/packages/contracts/util/multi_sig_wrapper.ts @@ -1,3 +1,4 @@ +import { AbiDefinition, MethodAbi } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import ABI = require('ethereumjs-abi'); import ethUtil = require('ethereumjs-util'); @@ -10,8 +11,8 @@ import { TransactionDataParams } from './types'; export class MultiSigWrapper { private _multiSig: MultiSigWalletContract; - public static encodeFnArgs(name: string, abi: Web3.AbiDefinition[], args: any[]) { - const abiEntity = _.find(abi, { name }) as Web3.MethodAbi; + public static encodeFnArgs(name: string, abi: AbiDefinition[], args: any[]) { + const abiEntity = _.find(abi, { name }) as MethodAbi; if (_.isUndefined(abiEntity)) { throw new Error(`Did not find abi entry for name: ${name}`); } diff --git a/packages/contracts/util/types.ts b/packages/contracts/util/types.ts index 61a19acb4..321084c42 100644 --- a/packages/contracts/util/types.ts +++ b/packages/contracts/util/types.ts @@ -1,5 +1,5 @@ +import { AbiDefinition, ContractAbi } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; -import * as Web3 from 'web3'; export interface BalancesByOwner { [ownerAddress: string]: { @@ -51,7 +51,7 @@ export interface DefaultOrderParams { export interface TransactionDataParams { name: string; - abi: Web3.AbiDefinition[]; + abi: AbiDefinition[]; args: any[]; } @@ -105,7 +105,7 @@ export interface Artifact { contract_name: ContractName; networks: { [networkId: number]: { - abi: Web3.ContractAbi; + abi: ContractAbi; solc_version: string; keccak256: string; optimizer_enabled: number; diff --git a/packages/deployer/src/compiler.ts b/packages/deployer/src/compiler.ts index 1f521dca1..4741a9086 100644 --- a/packages/deployer/src/compiler.ts +++ b/packages/deployer/src/compiler.ts @@ -1,3 +1,4 @@ +import { ContractAbi } from '@0xproject/types'; import { logUtils, promisify } from '@0xproject/utils'; import * as ethUtil from 'ethereumjs-util'; import * as fs from 'fs'; @@ -7,7 +8,6 @@ import * as path from 'path'; import * as requireFromString from 'require-from-string'; import * as semver from 'semver'; import solc = require('solc'); -import * as Web3 from 'web3'; import { binPaths } from './solc/bin_paths'; import { @@ -189,7 +189,7 @@ export class Compiler { `Contract ${contractName} not found in ${fileName}. Please make sure your contract has the same name as it's file name`, ); } - const abi: Web3.ContractAbi = JSON.parse(compiled.contracts[contractIdentifier].interface); + const abi: ContractAbi = JSON.parse(compiled.contracts[contractIdentifier].interface); const bytecode = `0x${compiled.contracts[contractIdentifier].bytecode}`; const runtimeBytecode = `0x${compiled.contracts[contractIdentifier].runtimeBytecode}`; const sourceMap = compiled.contracts[contractIdentifier].srcmap; diff --git a/packages/deployer/src/deployer.ts b/packages/deployer/src/deployer.ts index 68518a931..7ee45fed5 100644 --- a/packages/deployer/src/deployer.ts +++ b/packages/deployer/src/deployer.ts @@ -1,4 +1,4 @@ -import { AbiType, TxData } from '@0xproject/types'; +import { AbiType, ConstructorAbi, ContractAbi, TxData } from '@0xproject/types'; import { logUtils } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; @@ -71,7 +71,7 @@ export class Deployer { gas, }; const abi = contractNetworkDataIfExists.abi; - const constructorAbi = _.find(abi, { type: AbiType.Constructor }) as Web3.ConstructorAbi; + const constructorAbi = _.find(abi, { type: AbiType.Constructor }) as ConstructorAbi; const constructorArgs = _.isUndefined(constructorAbi) ? [] : constructorAbi.inputs; if (constructorArgs.length !== args.length) { const constructorSignature = `constructor(${_.map(constructorArgs, arg => `${arg.type} ${arg.name}`).join( @@ -107,7 +107,7 @@ export class Deployer { * @param txData Tx options used for deployment. * @return Promise that resolves to a web3 contract instance. */ - private async _deployFromAbiAsync(abi: Web3.ContractAbi, args: any[], txData: Web3.TxData): Promise<any> { + private async _deployFromAbiAsync(abi: ContractAbi, args: any[], txData: TxData): Promise<any> { const contract: Web3.Contract<Web3.ContractInstance> = this.web3Wrapper.getContractFromAbi(abi); const deployPromise = new Promise((resolve, reject) => { /** diff --git a/packages/deployer/src/globals.d.ts b/packages/deployer/src/globals.d.ts index 83db346f9..5b0d495d5 100644 --- a/packages/deployer/src/globals.d.ts +++ b/packages/deployer/src/globals.d.ts @@ -2,7 +2,6 @@ declare module 'dirty-chai'; // tslint:disable:completed-docs declare module 'solc' { - import * as Web3 from 'web3'; export interface ContractCompilationResult { srcmap: string; srcmapRuntime: string; diff --git a/packages/deployer/src/utils/contract.ts b/packages/deployer/src/utils/contract.ts index 9c57751ff..9b7baac11 100644 --- a/packages/deployer/src/utils/contract.ts +++ b/packages/deployer/src/utils/contract.ts @@ -1,4 +1,5 @@ import { schemas, SchemaValidator } from '@0xproject/json-schemas'; +import { ContractAbi, EventAbi, FunctionAbi, MethodAbi, TxData } from '@0xproject/types'; import { promisify } from '@0xproject/utils'; import * as _ from 'lodash'; import * as Web3 from 'web3'; @@ -7,14 +8,14 @@ import { AbiType } from './types'; export class Contract implements Web3.ContractInstance { public address: string; - public abi: Web3.ContractAbi; + public abi: ContractAbi; private _contract: Web3.ContractInstance; - private _defaults: Partial<Web3.TxData>; + private _defaults: Partial<TxData>; private _validator: SchemaValidator; // This class instance is going to be populated with functions and events depending on the ABI // and we don't know their types in advance [name: string]: any; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<Web3.TxData>) { + constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { this._contract = web3ContractInstance; this.address = web3ContractInstance.address; this.abi = web3ContractInstance.abi; @@ -24,8 +25,8 @@ export class Contract implements Web3.ContractInstance { this._validator = new SchemaValidator(); } private _populateFunctions(): void { - const functionsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Function) as Web3.FunctionAbi[]; - _.forEach(functionsAbi, (functionAbi: Web3.MethodAbi) => { + const functionsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Function) as FunctionAbi[]; + _.forEach(functionsAbi, (functionAbi: MethodAbi) => { if (functionAbi.constant) { const cbStyleCallFunction = this._contract[functionAbi.name].call; this[functionAbi.name] = promisify(cbStyleCallFunction, this._contract); @@ -42,8 +43,8 @@ export class Contract implements Web3.ContractInstance { }); } private _populateEvents(): void { - const eventsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Event) as Web3.EventAbi[]; - _.forEach(eventsAbi, (eventAbi: Web3.EventAbi) => { + const eventsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Event) as EventAbi[]; + _.forEach(eventsAbi, (eventAbi: EventAbi) => { this[eventAbi.name] = this._contract[eventAbi.name]; }); } @@ -51,7 +52,7 @@ export class Contract implements Web3.ContractInstance { const promisifiedWithDefaultParams = async (...args: any[]) => { const promise = new Promise((resolve, reject) => { const lastArg = args[args.length - 1]; - let txData: Partial<Web3.TxData> = {}; + let txData: Partial<TxData> = {}; if (this._isTxData(lastArg)) { txData = args.pop(); } diff --git a/packages/deployer/src/utils/encoder.ts b/packages/deployer/src/utils/encoder.ts index e3acde252..4f62662e1 100644 --- a/packages/deployer/src/utils/encoder.ts +++ b/packages/deployer/src/utils/encoder.ts @@ -1,15 +1,15 @@ +import { AbiDefinition, ContractAbi, DataItem } from '@0xproject/types'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import * as web3Abi from 'web3-eth-abi'; import { AbiType } from './types'; export const encoder = { - encodeConstructorArgsFromAbi(args: any[], abi: Web3.ContractAbi): string { + encodeConstructorArgsFromAbi(args: any[], abi: ContractAbi): string { const constructorTypes: string[] = []; - _.each(abi, (element: Web3.AbiDefinition) => { + _.each(abi, (element: AbiDefinition) => { if (element.type === AbiType.Constructor) { - _.each(element.inputs, (input: Web3.DataItem) => { + _.each(element.inputs, (input: DataItem) => { constructorTypes.push(input.type); }); } diff --git a/packages/deployer/src/utils/types.ts b/packages/deployer/src/utils/types.ts index 540b31aff..7cb3958cb 100644 --- a/packages/deployer/src/utils/types.ts +++ b/packages/deployer/src/utils/types.ts @@ -1,4 +1,4 @@ -import { TxData } from '@0xproject/types'; +import { ContractAbi, TxData } from '@0xproject/types'; import * as Web3 from 'web3'; import * as yargs from 'yargs'; @@ -23,7 +23,7 @@ export interface ContractNetworkData { optimizer_enabled: boolean; keccak256: string; source_tree_hash: string; - abi: Web3.ContractAbi; + abi: ContractAbi; bytecode: string; runtime_bytecode: string; address?: string; diff --git a/packages/monorepo-scripts/tsconfig.json b/packages/monorepo-scripts/tsconfig.json index c56d255d5..5ec2db5e0 100644 --- a/packages/monorepo-scripts/tsconfig.json +++ b/packages/monorepo-scripts/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig", "compilerOptions": { + "typeRoots": ["node_modules/@types"], "outDir": "lib" }, "include": ["./src/**/*"] diff --git a/packages/react-docs-example/ts/docs.tsx b/packages/react-docs-example/ts/docs.tsx index 68db66b60..eef331813 100644 --- a/packages/react-docs-example/ts/docs.tsx +++ b/packages/react-docs-example/ts/docs.tsx @@ -46,26 +46,25 @@ const docsInfoConfig: DocsInfoConfig = { typeConfigs: { // Note: This needs to be kept in sync with the types exported in index.ts. Unfortunately there is // currently no way to extract the re-exported types from index.ts via TypeDoc :( - publicTypes: ['TxData', 'TransactionReceipt', 'RawLogEntry'], + publicTypes: [ + 'TxData', + 'TransactionReceipt', + 'RawLogEntry', + 'BlockParam', + 'ContractAbi', + 'FilterObject', + 'LogEntry', + 'BlockWithoutTransactionData', + 'CallData', + 'LogEntryEvent', + ], typeNameToExternalLink: { Web3: 'https://github.com/ethereum/wiki/wiki/JavaScript-API', Provider: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L150', - BigNumber: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L127', - LogEntryEvent: 'http://mikemcl.github.io/bignumber.js', - CallData: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L348', - BlockWithoutTransactionData: - 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L314', - LogEntry: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L366', - FilterObject: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L109', - ['Web3.BlockParam']: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L278', - ['Web3.ContractAbi']: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L47', + BigNumber: 'http://mikemcl.github.io/bignumber.js', }, typeNameToPrefix: { Provider: 'Web3', - CallData: 'Web3', - BlockWithoutTransactionData: 'Web3', - LogEntry: 'Web3', - FilterObject: 'Web3', }, typeNameToDocSection: { Web3Wrapper: docSections.web3Wrapper, diff --git a/packages/sol-cov/package.json b/packages/sol-cov/package.json index 6b5183ff2..1e3124822 100644 --- a/packages/sol-cov/package.json +++ b/packages/sol-cov/package.json @@ -39,8 +39,9 @@ "homepage": "https://github.com/0xProject/0x.js/packages/sol-cov/README.md", "dependencies": { "@0xproject/subproviders": "^0.8.2", - "@0xproject/utils": "^0.3.4", + "@0xproject/utils": "^0.4.3", "@0xproject/typescript-typings": "^0.0.1", + "@0xproject/types": "^0.4.1", "ethereumjs-util": "^5.1.1", "glob": "^7.1.2", "istanbul": "^0.4.5", @@ -48,8 +49,7 @@ "semaphore-async-await": "^1.5.1", "solidity-coverage": "^0.4.10", "solidity-parser-antlr": "^0.2.7", - "solidity-parser-sc": "^0.4.4", - "web3": "^0.20.0" + "solidity-parser-sc": "^0.4.4" }, "devDependencies": { "@0xproject/monorepo-scripts": "^0.1.14", @@ -67,8 +67,7 @@ "sinon": "^4.0.0", "tslint": "5.8.0", "typedoc": "0xProject/typedoc", - "typescript": "2.7.1", - "web3-typescript-typings": "^0.9.11" + "typescript": "2.7.1" }, "publishConfig": { "access": "public" diff --git a/packages/sol-cov/src/coverage_subprovider.ts b/packages/sol-cov/src/coverage_subprovider.ts index 37682c45f..1c80dca7b 100644 --- a/packages/sol-cov/src/coverage_subprovider.ts +++ b/packages/sol-cov/src/coverage_subprovider.ts @@ -1,14 +1,14 @@ import { Callback, ErrorCallback, NextCallback, Subprovider } from '@0xproject/subproviders'; +import { BlockParam, CallData, JSONRPCRequestPayload, TransactionTrace, TxData } from '@0xproject/types'; import { promisify } from '@0xproject/utils'; import * as _ from 'lodash'; import { Lock } from 'semaphore-async-await'; -import * as Web3 from 'web3'; import { constants } from './constants'; import { CoverageManager } from './coverage_manager'; import { TraceInfoExistingContract, TraceInfoNewContract } from './types'; -interface MaybeFakeTxData extends Web3.TxData { +interface MaybeFakeTxData extends TxData { isFakeTransaction?: boolean; } @@ -58,7 +58,7 @@ export class CoverageSubprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:prefer-function-over-method - public handleRequest(payload: Web3.JSONRPCRequestPayload, next: NextCallback, end: ErrorCallback) { + public handleRequest(payload: JSONRPCRequestPayload, next: NextCallback, end: ErrorCallback) { switch (payload.method) { case 'eth_sendTransaction': const txData = payload.params[0]; @@ -110,8 +110,8 @@ export class CoverageSubprovider extends Subprovider { cb(); } private async _onCallExecutedAsync( - callData: Partial<Web3.CallData>, - blockNumber: Web3.BlockParam, + callData: Partial<CallData>, + blockNumber: BlockParam, err: Error | null, callResult: string, cb: Callback, @@ -125,7 +125,7 @@ export class CoverageSubprovider extends Subprovider { params: [txHash, { disableMemory: true, disableStack: true, disableStorage: true }], // TODO For now testrpc just ignores those parameters https://github.com/trufflesuite/ganache-cli/issues/489 }; const jsonRPCResponsePayload = await this.emitPayloadAsync(payload); - const trace: Web3.TransactionTrace = jsonRPCResponsePayload.result; + const trace: TransactionTrace = jsonRPCResponsePayload.result; const coveredPcs = _.map(trace.structLogs, log => log.pc); if (address === constants.NEW_CONTRACT) { const traceInfo: TraceInfoNewContract = { @@ -147,7 +147,7 @@ export class CoverageSubprovider extends Subprovider { this._coverageManager.appendTraceInfo(traceInfo); } } - private async _recordCallTraceAsync(callData: Partial<Web3.CallData>, blockNumber: Web3.BlockParam): Promise<void> { + private async _recordCallTraceAsync(callData: Partial<CallData>, blockNumber: BlockParam): Promise<void> { // We don't want other transactions to be exeucted during snashotting period, that's why we lock the // transaction execution for all transactions except our fake ones. await this._lock.acquire(); diff --git a/packages/subproviders/src/globals.d.ts b/packages/subproviders/src/globals.d.ts index 2c86346f5..ebc4efe86 100644 --- a/packages/subproviders/src/globals.d.ts +++ b/packages/subproviders/src/globals.d.ts @@ -73,11 +73,11 @@ declare module 'web3-provider-engine/subproviders/subprovider' { export = Subprovider; } declare module 'web3-provider-engine/subproviders/rpc' { - import * as Web3 from 'web3'; + import { JSONRPCRequestPayload } from '@0xproject/types'; class RpcSubprovider { constructor(options: { rpcUrl: string }); public handleRequest( - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: () => void, end: (err: Error | null, data?: any) => void, ): void; @@ -102,11 +102,11 @@ declare module 'web3-provider-engine/util/rpc-cache-utils' { export = ProviderEngineRpcUtils; } declare module 'web3-provider-engine/subproviders/fixture' { - import * as Web3 from 'web3'; + import { JSONRPCRequestPayload } from '@0xproject/types'; class FixtureSubprovider { constructor(staticResponses: any); public handleRequest( - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: () => void, end: (err: Error | null, data?: any) => void, ): void; diff --git a/packages/subproviders/src/index.ts b/packages/subproviders/src/index.ts index d88792fd0..9786347e6 100644 --- a/packages/subproviders/src/index.ts +++ b/packages/subproviders/src/index.ts @@ -1,5 +1,6 @@ import Eth from '@ledgerhq/hw-app-eth'; import TransportU2F from '@ledgerhq/hw-transport-u2f'; +export { ECSignature } from '@0xproject/types'; import { LedgerEthereumClient } from './types'; @@ -15,7 +16,6 @@ export { Callback, ErrorCallback, NextCallback, - ECSignature, LedgerWalletSubprovider, LedgerCommunicationClient, NonceSubproviderErrors, diff --git a/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts b/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts index dc570b152..595ec654d 100644 --- a/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts +++ b/packages/subproviders/src/subproviders/empty_wallet_subprovider.ts @@ -1,4 +1,4 @@ -import * as Web3 from 'web3'; +import { JSONRPCRequestPayload } from '@0xproject/types'; import { Callback, ErrorCallback } from '../types'; @@ -18,7 +18,7 @@ export class EmptyWalletSubprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:prefer-function-over-method - public handleRequest(payload: Web3.JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { + public handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { switch (payload.method) { case 'eth_accounts': end(null, []); diff --git a/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts b/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts index a6f978db1..966c37d8a 100644 --- a/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts +++ b/packages/subproviders/src/subproviders/fake_gas_estimate_subprovider.ts @@ -1,4 +1,4 @@ -import * as Web3 from 'web3'; +import { JSONRPCRequestPayload } from '@0xproject/types'; import { Callback, ErrorCallback } from '../types'; @@ -32,7 +32,7 @@ export class FakeGasEstimateSubprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:prefer-function-over-method - public handleRequest(payload: Web3.JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { + public handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { switch (payload.method) { case 'eth_estimateGas': end(null, this._constantGasAmount); diff --git a/packages/subproviders/src/subproviders/ganache.ts b/packages/subproviders/src/subproviders/ganache.ts index fc0b9c3d2..785de792d 100644 --- a/packages/subproviders/src/subproviders/ganache.ts +++ b/packages/subproviders/src/subproviders/ganache.ts @@ -1,3 +1,4 @@ +import { JSONRPCRequestPayload } from '@0xproject/types'; import * as Ganache from 'ganache-core'; import * as Web3 from 'web3'; @@ -28,7 +29,7 @@ export class GanacheSubprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:prefer-function-over-method - public handleRequest(payload: Web3.JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { + public handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { this._ganacheProvider.sendAsync(payload, (err: Error | null, result: any) => { end(err, result && result.result); }); diff --git a/packages/subproviders/src/subproviders/injected_web3.ts b/packages/subproviders/src/subproviders/injected_web3.ts index cd9b0b603..edecd8bf6 100644 --- a/packages/subproviders/src/subproviders/injected_web3.ts +++ b/packages/subproviders/src/subproviders/injected_web3.ts @@ -1,3 +1,4 @@ +import { JSONRPCRequestPayload } from '@0xproject/types'; import * as _ from 'lodash'; import * as Web3 from 'web3'; @@ -30,7 +31,7 @@ export class InjectedWeb3Subprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:prefer-function-over-method - public handleRequest(payload: Web3.JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { + public handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback) { switch (payload.method) { case 'web3_clientVersion': this._injectedWeb3.version.getNode(end); diff --git a/packages/subproviders/src/subproviders/ledger.ts b/packages/subproviders/src/subproviders/ledger.ts index 8bc70d8b6..95784a391 100644 --- a/packages/subproviders/src/subproviders/ledger.ts +++ b/packages/subproviders/src/subproviders/ledger.ts @@ -1,11 +1,11 @@ import { assert } from '@0xproject/assert'; +import { JSONRPCRequestPayload } from '@0xproject/types'; import { addressUtils } from '@0xproject/utils'; import EthereumTx = require('ethereumjs-tx'); import ethUtil = require('ethereumjs-util'); import HDNode = require('hdkey'); import * as _ from 'lodash'; import { Lock } from 'semaphore-async-await'; -import * as Web3 from 'web3'; import { Callback, @@ -208,7 +208,7 @@ export class LedgerSubprovider extends Subprovider { */ // tslint:disable-next-line:async-suffix public async handleRequest( - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: Callback, end: (err: Error | null, result?: any) => void, ) { diff --git a/packages/subproviders/src/subproviders/nonce_tracker.ts b/packages/subproviders/src/subproviders/nonce_tracker.ts index 249f16199..907330111 100644 --- a/packages/subproviders/src/subproviders/nonce_tracker.ts +++ b/packages/subproviders/src/subproviders/nonce_tracker.ts @@ -1,9 +1,8 @@ import * as _ from 'lodash'; -import { BlockParamLiteral } from '@0xproject/types'; +import { BlockParamLiteral, JSONRPCRequestPayload } from '@0xproject/types'; import EthereumTx = require('ethereumjs-tx'); import ethUtil = require('ethereumjs-util'); -import * as Web3 from 'web3'; import providerEngineUtils = require('web3-provider-engine/util/rpc-cache-utils'); import { Callback, ErrorCallback, NextCallback, NonceSubproviderErrors } from '../types'; @@ -19,7 +18,7 @@ const NONCE_TOO_LOW_ERROR_MESSAGE = 'Transaction nonce is too low'; */ export class NonceTrackerSubprovider extends Subprovider { private _nonceCache: { [address: string]: string } = {}; - private static _reconstructTransaction(payload: Web3.JSONRPCRequestPayload): EthereumTx { + private static _reconstructTransaction(payload: JSONRPCRequestPayload): EthereumTx { const raw = payload.params[0]; if (_.isUndefined(raw)) { throw new Error(NonceSubproviderErrors.EmptyParametersFound); @@ -28,7 +27,7 @@ export class NonceTrackerSubprovider extends Subprovider { const transaction = new EthereumTx(rawData); return transaction; } - private static _determineAddress(payload: Web3.JSONRPCRequestPayload): string { + private static _determineAddress(payload: JSONRPCRequestPayload): string { let address: string; switch (payload.method) { case 'eth_getTransactionCount': @@ -55,11 +54,7 @@ export class NonceTrackerSubprovider extends Subprovider { * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:async-suffix - public async handleRequest( - payload: Web3.JSONRPCRequestPayload, - next: NextCallback, - end: ErrorCallback, - ): Promise<void> { + public async handleRequest(payload: JSONRPCRequestPayload, next: NextCallback, end: ErrorCallback): Promise<void> { switch (payload.method) { case 'eth_getTransactionCount': const requestDefaultBlock = providerEngineUtils.blockTagForPayload(payload); @@ -92,7 +87,7 @@ export class NonceTrackerSubprovider extends Subprovider { return next(); } } - private _handleSuccessfulTransaction(payload: Web3.JSONRPCRequestPayload): void { + private _handleSuccessfulTransaction(payload: JSONRPCRequestPayload): void { const address = NonceTrackerSubprovider._determineAddress(payload); const transaction = NonceTrackerSubprovider._reconstructTransaction(payload); // Increment the nonce from the previous successfully submitted transaction @@ -105,7 +100,7 @@ export class NonceTrackerSubprovider extends Subprovider { const nextPrefixedHexNonce = `0x${nextHexNonce}`; this._nonceCache[address] = nextPrefixedHexNonce; } - private _handleSendTransactionError(payload: Web3.JSONRPCRequestPayload, err: Error): void { + private _handleSendTransactionError(payload: JSONRPCRequestPayload, err: Error): void { const address = NonceTrackerSubprovider._determineAddress(payload); if (this._nonceCache[address] && _.includes(err.message, NONCE_TOO_LOW_ERROR_MESSAGE)) { delete this._nonceCache[address]; diff --git a/packages/subproviders/src/subproviders/redundant_rpc.ts b/packages/subproviders/src/subproviders/redundant_rpc.ts index ace2ed3c8..f8ff0915d 100644 --- a/packages/subproviders/src/subproviders/redundant_rpc.ts +++ b/packages/subproviders/src/subproviders/redundant_rpc.ts @@ -1,6 +1,6 @@ +import { JSONRPCRequestPayload } from '@0xproject/types'; import { promisify } from '@0xproject/utils'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); import { Callback } from '../types'; @@ -16,7 +16,7 @@ export class RedundantRPCSubprovider extends Subprovider { private _rpcs: RpcSubprovider[]; private static async _firstSuccessAsync( rpcs: RpcSubprovider[], - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: Callback, ): Promise<any> { let lastErr: Error | undefined; @@ -55,7 +55,7 @@ export class RedundantRPCSubprovider extends Subprovider { */ // tslint:disable-next-line:async-suffix public async handleRequest( - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: Callback, end: (err: Error | null, data?: any) => void, ): Promise<void> { diff --git a/packages/subproviders/src/subproviders/subprovider.ts b/packages/subproviders/src/subproviders/subprovider.ts index 4fa351e11..26ce19305 100644 --- a/packages/subproviders/src/subproviders/subprovider.ts +++ b/packages/subproviders/src/subproviders/subprovider.ts @@ -1,3 +1,4 @@ +import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types'; import promisify = require('es6-promisify'); import * as Web3 from 'web3'; @@ -37,9 +38,7 @@ export class Subprovider { * @param payload JSON RPC payload * @returns JSON RPC response payload */ - public async emitPayloadAsync( - payload: Partial<JSONRPCRequestPayloadWithMethod>, - ): Promise<Web3.JSONRPCResponsePayload> { + public async emitPayloadAsync(payload: Partial<JSONRPCRequestPayloadWithMethod>): Promise<JSONRPCResponsePayload> { const finalPayload = Subprovider._createFinalPayload(payload); const response = await promisify(this._engine.sendAsync, this._engine)(finalPayload); return response; diff --git a/packages/subproviders/src/types.ts b/packages/subproviders/src/types.ts index 9bb9ff696..a1fec1882 100644 --- a/packages/subproviders/src/types.ts +++ b/packages/subproviders/src/types.ts @@ -1,8 +1,5 @@ -import { ECSignature } from '@0xproject/types'; +import { ECSignature, JSONRPCRequestPayload } from '@0xproject/types'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; - -export { ECSignature } from '@0xproject/types'; export interface LedgerCommunicationClient { close: () => Promise<void>; @@ -116,6 +113,6 @@ export type Callback = () => void; export type OnNextCompleted = (err: Error | null, result: any, cb: Callback) => void; export type NextCallback = (callback?: OnNextCompleted) => void; -export interface JSONRPCRequestPayloadWithMethod extends Web3.JSONRPCRequestPayload { +export interface JSONRPCRequestPayloadWithMethod extends JSONRPCRequestPayload { method: string; } diff --git a/packages/subproviders/test/integration/ledger_subprovider_test.ts b/packages/subproviders/test/integration/ledger_subprovider_test.ts index a94cfbe3a..969081ad5 100644 --- a/packages/subproviders/test/integration/ledger_subprovider_test.ts +++ b/packages/subproviders/test/integration/ledger_subprovider_test.ts @@ -1,3 +1,4 @@ +import { JSONRPCResponsePayload } from '@0xproject/types'; import Eth from '@ledgerhq/hw-app-eth'; // HACK: This depdency is optional and tslint skips optional depdencies // tslint:disable-next-line:no-implicit-dependencies @@ -97,7 +98,7 @@ describe('LedgerSubprovider', () => { params: [], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(10); done(); @@ -115,7 +116,7 @@ describe('LedgerSubprovider', () => { params: [signer, messageHex], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(132); expect(response.result.substr(0, 2)).to.be.equal('0x'); @@ -135,7 +136,7 @@ describe('LedgerSubprovider', () => { params: [messageHex, signer], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(132); expect(response.result.substr(0, 2)).to.be.equal('0x'); @@ -155,7 +156,7 @@ describe('LedgerSubprovider', () => { params: [tx], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.raw.length).to.be.equal(206); expect(response.result.raw.substr(0, 2)).to.be.equal('0x'); @@ -193,7 +194,7 @@ describe('LedgerSubprovider', () => { params: [tx], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); const result = response.result; expect(result.length).to.be.equal(66); diff --git a/packages/subproviders/test/unit/ledger_subprovider_test.ts b/packages/subproviders/test/unit/ledger_subprovider_test.ts index 4c0803a29..3cb487f02 100644 --- a/packages/subproviders/test/unit/ledger_subprovider_test.ts +++ b/packages/subproviders/test/unit/ledger_subprovider_test.ts @@ -1,3 +1,4 @@ +import { JSONRPCResponsePayload } from '@0xproject/types'; import * as chai from 'chai'; import * as ethUtils from 'ethereumjs-util'; import * as _ from 'lodash'; @@ -112,7 +113,7 @@ describe('LedgerSubprovider', () => { params: [], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(10); expect(response.result[0]).to.be.equal(FAKE_ADDRESS); @@ -128,7 +129,7 @@ describe('LedgerSubprovider', () => { params: ['0x0000000000000000000000000000000000000000', messageHex], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result).to.be.equal( '0xa6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae491480652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d001', @@ -145,7 +146,7 @@ describe('LedgerSubprovider', () => { params: [messageHex, '0x0000000000000000000000000000000000000000'], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result).to.be.equal( '0xa6cc284bff14b42bdf5e9286730c152be91719d478605ec46b3bebcd0ae491480652a1a7b742ceb0213d1e744316e285f41f878d8af0b8e632cbca4c279132d001', @@ -168,7 +169,7 @@ describe('LedgerSubprovider', () => { params: [tx], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.raw.length).to.be.equal(192); expect(response.result.raw.substr(0, 2)).to.be.equal('0x'); @@ -186,7 +187,7 @@ describe('LedgerSubprovider', () => { params: ['0x0000000000000000000000000000000000000000', nonHexMessage], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.not.be.a('null'); expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); done(); @@ -201,7 +202,7 @@ describe('LedgerSubprovider', () => { params: [nonHexMessage, '0x0000000000000000000000000000000000000000'], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.not.be.a('null'); expect(err.message).to.be.equal('Expected data to be of type HexString, encountered: hello world'); done(); @@ -219,7 +220,7 @@ describe('LedgerSubprovider', () => { params: [tx], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.not.be.a('null'); expect(err.message).to.be.equal(LedgerSubproviderErrors.SenderInvalidOrNotSupplied); done(); @@ -238,7 +239,7 @@ describe('LedgerSubprovider', () => { params: [tx], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.not.be.a('null'); expect(err.message).to.be.equal(LedgerSubproviderErrors.SenderInvalidOrNotSupplied); done(); diff --git a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts index c3170745c..a347ab765 100644 --- a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts +++ b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts @@ -1,3 +1,4 @@ +import { JSONRPCResponsePayload } from '@0xproject/types'; import * as chai from 'chai'; import * as _ from 'lodash'; import Web3 = require('web3'); @@ -26,7 +27,7 @@ describe('RedundantRpcSubprovider', () => { params: [], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(10); done(); @@ -46,7 +47,7 @@ describe('RedundantRpcSubprovider', () => { params: [], id: 1, }; - const callback = reportCallbackErrors(done)((err: Error, response: Web3.JSONRPCResponsePayload) => { + const callback = reportCallbackErrors(done)((err: Error, response: JSONRPCResponsePayload) => { expect(err).to.be.a('null'); expect(response.result.length).to.be.equal(10); done(); diff --git a/packages/tslint-config/tsconfig.json b/packages/tslint-config/tsconfig.json index 85c88035a..fd9b23316 100644 --- a/packages/tslint-config/tsconfig.json +++ b/packages/tslint-config/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig", "compilerOptions": { + "typeRoots": ["node_modules/@types"], "outDir": "lib" }, "include": ["./rules/**/*", "./monorepo_scripts/**/*"] diff --git a/packages/types/package.json b/packages/types/package.json index 1142d252a..16737f5ea 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -22,15 +22,14 @@ "devDependencies": { "@0xproject/monorepo-scripts": "^0.1.14", "@0xproject/tslint-config": "^0.4.12", + "@types/node": "^8.0.53", "copyfiles": "^1.2.0", "shx": "^0.2.2", "tslint": "5.8.0", "typescript": "2.7.1" }, "dependencies": { - "@0xproject/typescript-typings": "^0.0.1", - "bignumber.js": "~4.1.0", - "web3": "^0.20.0" + "bignumber.js": "~4.1.0" }, "publishConfig": { "access": "public" diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 2147a3edb..57b14e230 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -1,14 +1,195 @@ import { BigNumber } from 'bignumber.js'; -import * as Web3 from 'web3'; -export interface TxData { +export type ContractAbi = AbiDefinition[]; + +export type AbiDefinition = FunctionAbi | EventAbi; + +export type FunctionAbi = MethodAbi | ConstructorAbi | FallbackAbi; + +export type ConstructorStateMutability = 'nonpayable' | 'payable'; +export type StateMutability = 'pure' | 'view' | ConstructorStateMutability; + +export interface MethodAbi { + type: AbiType.Function; + name: string; + inputs: DataItem[]; + outputs: DataItem[]; + constant: boolean; + stateMutability: StateMutability; + payable: boolean; +} + +export interface ConstructorAbi { + type: AbiType.Constructor; + inputs: DataItem[]; + payable: boolean; + stateMutability: ConstructorStateMutability; +} + +export interface FallbackAbi { + type: AbiType.Fallback; + payable: boolean; +} + +export interface EventParameter extends DataItem { + indexed: boolean; +} + +export interface EventAbi { + type: AbiType.Event; + name: string; + inputs: EventParameter[]; + anonymous: boolean; +} + +export interface DataItem { + name: string; + type: string; + components: DataItem[]; +} + +export type OpCode = string; + +export interface StructLog { + depth: number; + error: string; + gas: number; + gasCost: number; + memory: string[]; + op: OpCode; + pc: number; + stack: string[]; + storage: { [location: string]: string }; +} + +export interface TransactionTrace { + gas: number; + returnValue: any; + structLogs: StructLog[]; +} + +export type Unit = + | 'kwei' + | 'ada' + | 'mwei' + | 'babbage' + | 'gwei' + | 'shannon' + | 'szabo' + | 'finney' + | 'ether' + | 'kether' + | 'grand' + | 'einstein' + | 'mether' + | 'gether' + | 'tether'; + +export interface JSONRPCRequestPayload { + params: any[]; + method: string; + id: number; + jsonrpc: string; +} + +export interface JSONRPCResponsePayload { + result: any; + id: number; + jsonrpc: string; +} + +export interface AbstractBlock { + number: number | null; + hash: string | null; + parentHash: string; + nonce: string | null; + sha3Uncles: string; + logsBloom: string | null; + transactionsRoot: string; + stateRoot: string; + miner: string; + difficulty: BigNumber; + totalDifficulty: BigNumber; + extraData: string; + size: number; + gasLimit: number; + gasUsed: number; + timestamp: number; + uncles: string[]; +} + +export interface BlockWithoutTransactionData extends AbstractBlock { + transactions: string[]; +} + +export interface BlockWithTransactionData extends AbstractBlock { + transactions: Transaction[]; +} + +export interface Transaction { + hash: string; + nonce: number; + blockHash: string | null; + blockNumber: number | null; + transactionIndex: number | null; + from: string; + to: string | null; + value: BigNumber; + gasPrice: BigNumber; + gas: number; + input: string; +} + +export interface CallTxDataBase { + to?: string; + value?: number | string | BigNumber; + gas?: number | string | BigNumber; + gasPrice?: number | string | BigNumber; data?: string; - from?: string; - gas?: number; - gasPrice?: BigNumber; nonce?: number; } +export interface TxData extends CallTxDataBase { + from: string; +} + +export interface CallData extends CallTxDataBase { + from?: string; +} + +export interface FilterObject { + fromBlock?: number | string; + toBlock?: number | string; + address?: string; + topics?: LogTopic[]; +} + +export type LogTopic = null | string | string[]; + +export interface DecodedLogEntry<A> extends LogEntry { + event: string; + args: A; +} + +export interface DecodedLogEntryEvent<A> extends DecodedLogEntry<A> { + removed: boolean; +} + +export interface LogEntryEvent extends LogEntry { + removed: boolean; +} + +export interface LogEntry { + logIndex: number | null; + transactionIndex: number | null; + transactionHash: string; + blockHash: string | null; + blockNumber: number | null; + address: string; + data: string; + topics: string[]; +} + export interface TxDataPayable extends TxData { value?: BigNumber; } @@ -20,11 +201,11 @@ export interface TransactionReceipt { transactionIndex: number; from: string; to: string; - status: null | 0 | 1; + status: null | string | 0 | 1; cumulativeGasUsed: number; gasUsed: number; contractAddress: string | null; - logs: Web3.LogEntry[]; + logs: LogEntry[]; } export enum AbiType { @@ -40,8 +221,8 @@ export interface DecodedLogArgs { [argName: string]: ContractEventArg; } -export interface LogWithDecodedArgs<ArgsType> extends Web3.DecodedLogEntry<ArgsType> {} -export type RawLog = Web3.LogEntry; +export interface LogWithDecodedArgs<ArgsType> extends DecodedLogEntry<ArgsType> {} +export type RawLog = LogEntry; export enum SolidityTypes { Address = 'address', Uint256 = 'uint256', @@ -50,7 +231,7 @@ export enum SolidityTypes { } export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt { - logs: Array<LogWithDecodedArgs<DecodedLogArgs> | Web3.LogEntry>; + logs: Array<LogWithDecodedArgs<DecodedLogArgs> | LogEntry>; } // Earliest is omitted by design. It is simply an alias for the `0` constant and diff --git a/packages/types/tsconfig.json b/packages/types/tsconfig.json index c56d255d5..5ec2db5e0 100644 --- a/packages/types/tsconfig.json +++ b/packages/types/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig", "compilerOptions": { + "typeRoots": ["node_modules/@types"], "outDir": "lib" }, "include": ["./src/**/*"] diff --git a/packages/typescript-typings/package.json b/packages/typescript-typings/package.json index 8fce84272..c38ebf1f7 100644 --- a/packages/typescript-typings/package.json +++ b/packages/typescript-typings/package.json @@ -20,6 +20,7 @@ }, "homepage": "https://github.com/0xProject/0x-monorepo/packages/typescript-typings#readme", "dependencies": { + "@0xproject/types": "^0.4.1", "bignumber.js": "~4.1.0" }, "devDependencies": { diff --git a/packages/typescript-typings/types/web3/index.d.ts b/packages/typescript-typings/types/web3/index.d.ts index cbe067b37..f4ebd41b9 100644 --- a/packages/typescript-typings/types/web3/index.d.ts +++ b/packages/typescript-typings/types/web3/index.d.ts @@ -1,5 +1,21 @@ declare module 'web3' { import * as BigNumber from 'bignumber.js'; + import { + AbiDefinition, + BlockWithTransactionData, + BlockWithoutTransactionData, + BlockParam, + CallData, + Unit, + TxData, + Transaction, + ContractAbi, + TransactionReceipt, + FilterObject, + LogEntryEvent, + JSONRPCRequestPayload, + JSONRPCResponsePayload, + } from '@0xproject/types'; type MixedData = string | number | object | any[] | BigNumber.BigNumber; @@ -22,10 +38,10 @@ declare module 'web3' { public fromAscii(ascii: string, padding?: number): string; public toDecimal(hex: string): number; public fromDecimal(value: number | string): string; - public fromWei(value: number | string, unit: Web3.Unit): string; - public fromWei(value: BigNumber.BigNumber, unit: Web3.Unit): BigNumber.BigNumber; - public toWei(amount: number | string, unit: Web3.Unit): string; - public toWei(amount: BigNumber.BigNumber, unit: Web3.Unit): BigNumber.BigNumber; + public fromWei(value: number | string, unit: Unit): string; + public fromWei(value: BigNumber.BigNumber, unit: Unit): BigNumber.BigNumber; + public toWei(amount: number | string, unit: Unit): string; + public toWei(amount: BigNumber.BigNumber, unit: Unit): BigNumber.BigNumber; public toBigNumber(value: number | string): BigNumber.BigNumber; public isAddress(address: string): boolean; public isChecksumAddress(address: string): boolean; @@ -36,71 +52,16 @@ declare module 'web3' { class HttpProvider implements Web3.Provider { constructor(url?: string, timeout?: number, username?: string, password?: string); public sendAsync( - payload: Web3.JSONRPCRequestPayload, - callback: (err: Error, result: Web3.JSONRPCResponsePayload) => void, + payload: JSONRPCRequestPayload, + callback: (err: Error, result: JSONRPCResponsePayload) => void, ): void; } } namespace Web3 { - type ContractAbi = AbiDefinition[]; - - type AbiDefinition = FunctionAbi | EventAbi; - - type FunctionAbi = MethodAbi | ConstructorAbi | FallbackAbi; - - enum AbiType { - Function = 'function', - Constructor = 'constructor', - Event = 'event', - Fallback = 'fallback', - } - - type ConstructorStateMutability = 'nonpayable' | 'payable'; - type StateMutability = 'pure' | 'view' | ConstructorStateMutability; - - interface MethodAbi { - type: AbiType.Function; - name: string; - inputs: DataItem[]; - outputs: DataItem[]; - constant: boolean; - stateMutability: StateMutability; - payable: boolean; - } - - interface ConstructorAbi { - type: AbiType.Constructor; - inputs: DataItem[]; - payable: boolean; - stateMutability: ConstructorStateMutability; - } - - interface FallbackAbi { - type: AbiType.Fallback; - payable: boolean; - } - - interface EventParameter extends DataItem { - indexed: boolean; - } - - interface EventAbi { - type: AbiType.Event; - name: string; - inputs: EventParameter[]; - anonymous: boolean; - } - - interface DataItem { - name: string; - type: string; - components: DataItem[]; - } - interface ContractInstance { address: string; - abi: Web3.ContractAbi; + abi: ContractAbi; [name: string]: any; } @@ -110,66 +71,12 @@ declare module 'web3' { 'new'(...args: any[]): A; } - interface FilterObject { - fromBlock?: number | string; - toBlock?: number | string; - address?: string; - topics?: LogTopic[]; - } - - type LogTopic = null | string | string[]; - - interface DecodedLogEntry<A> extends LogEntry { - event: string; - args: A; - } - - interface DecodedLogEntryEvent<A> extends DecodedLogEntry<A> { - removed: boolean; - } - - interface LogEntryEvent extends LogEntry { - removed: boolean; - } - interface FilterResult { get(callback: () => void): void; watch(callback: (err: Error, result: LogEntryEvent) => void): void; stopWatching(callback?: () => void): void; } - export interface JSONRPCRequestPayload { - params: any[]; - method: string; - id: number; - jsonrpc: string; - } - - export interface JSONRPCResponsePayload { - result: any; - id: number; - jsonrpc: string; - } - - export type OpCode = string; - - export interface StructLog { - depth: number; - error: string; - gas: number; - gasCost: number; - memory: string[]; - op: OpCode; - pc: number; - stack: string[]; - storage: { [location: string]: string }; - } - export interface TransactionTrace { - gas: number; - returnValue: any; - structLogs: StructLog[]; - } - interface Provider { sendAsync( payload: JSONRPCRequestPayload, @@ -189,7 +96,7 @@ declare module 'web3' { accounts: string[]; blockNumber: number; defaultAccount?: string; - defaultBlock: Web3.BlockParam; + defaultBlock: BlockParam; syncing: Web3.SyncingResult; compile: { solidity(sourceString: string, cb?: (err: Error, result: any) => void): object; @@ -202,55 +109,46 @@ declare module 'web3' { getSyncing(cd: (err: Error, syncing: Web3.SyncingResult) => void): void; isSyncing(cb: (err: Error, isSyncing: boolean, syncingState: Web3.SyncingState) => void): Web3.IsSyncing; - getBlock(hashStringOrBlockNumber: string | Web3.BlockParam): Web3.BlockWithoutTransactionData; + getBlock(hashStringOrBlockNumber: string | BlockParam): BlockWithoutTransactionData; getBlock( - hashStringOrBlockNumber: string | Web3.BlockParam, - callback: (err: Error, blockObj: Web3.BlockWithoutTransactionData) => void, + hashStringOrBlockNumber: string | BlockParam, + callback: (err: Error, blockObj: BlockWithoutTransactionData) => void, ): void; getBlock( - hashStringOrBlockNumber: string | Web3.BlockParam, + hashStringOrBlockNumber: string | BlockParam, returnTransactionObjects: true, - ): Web3.BlockWithTransactionData; + ): BlockWithTransactionData; getBlock( - hashStringOrBlockNumber: string | Web3.BlockParam, + hashStringOrBlockNumber: string | BlockParam, returnTransactionObjects: true, - callback: (err: Error, blockObj: Web3.BlockWithTransactionData) => void, + callback: (err: Error, blockObj: BlockWithTransactionData) => void, ): void; - getBlockTransactionCount(hashStringOrBlockNumber: string | Web3.BlockParam): number; + getBlockTransactionCount(hashStringOrBlockNumber: string | BlockParam): number; getBlockTransactionCount( - hashStringOrBlockNumber: string | Web3.BlockParam, + hashStringOrBlockNumber: string | BlockParam, callback: (err: Error, blockTransactionCount: number) => void, ): void; // TODO returnTransactionObjects + getUncle(hashStringOrBlockNumber: string | BlockParam, uncleNumber: number): BlockWithoutTransactionData; getUncle( - hashStringOrBlockNumber: string | Web3.BlockParam, - uncleNumber: number, - ): Web3.BlockWithoutTransactionData; - getUncle( - hashStringOrBlockNumber: string | Web3.BlockParam, + hashStringOrBlockNumber: string | BlockParam, uncleNumber: number, - callback: (err: Error, uncle: Web3.BlockWithoutTransactionData) => void, + callback: (err: Error, uncle: BlockWithoutTransactionData) => void, ): void; - getTransaction(transactionHash: string): Web3.Transaction; - getTransaction( - transactionHash: string, - callback: (err: Error, transaction: Web3.Transaction) => void, - ): void; + getTransaction(transactionHash: string): Transaction; + getTransaction(transactionHash: string, callback: (err: Error, transaction: Transaction) => void): void; + getTransactionFromBlock(hashStringOrBlockNumber: string | BlockParam, indexNumber: number): Transaction; getTransactionFromBlock( - hashStringOrBlockNumber: string | Web3.BlockParam, + hashStringOrBlockNumber: string | BlockParam, indexNumber: number, - ): Web3.Transaction; - getTransactionFromBlock( - hashStringOrBlockNumber: string | Web3.BlockParam, - indexNumber: number, - callback: (err: Error, transaction: Web3.Transaction) => void, + callback: (err: Error, transaction: Transaction) => void, ): void; - contract(abi: Web3.AbiDefinition[]): Web3.Contract<any>; + contract(abi: AbiDefinition[]): Web3.Contract<any>; // TODO block param getBalance(addressHexString: string): BigNumber.BigNumber; @@ -264,10 +162,10 @@ declare module 'web3' { getCode(addressHexString: string): string; getCode(addressHexString: string, callback: (err: Error, code: string) => void): void; - filter(value: string | Web3.FilterObject): Web3.FilterResult; + filter(value: string | FilterObject): Web3.FilterResult; - sendTransaction(txData: Web3.TxData): string; - sendTransaction(txData: Web3.TxData, callback: (err: Error, value: string) => void): void; + sendTransaction(txData: TxData): string; + sendTransaction(txData: TxData, callback: (err: Error, value: string) => void): void; sendRawTransaction(rawTxData: string): string; sendRawTransaction(rawTxData: string, callback: (err: Error, value: string) => void): void; @@ -275,18 +173,18 @@ declare module 'web3' { sign(address: string, data: string): string; sign(address: string, data: string, callback: (err: Error, signature: string) => void): void; - getTransactionReceipt(txHash: string): Web3.TransactionReceipt | null; + getTransactionReceipt(txHash: string): TransactionReceipt | null; getTransactionReceipt( txHash: string, - callback: (err: Error, receipt: Web3.TransactionReceipt | null) => void, + callback: (err: Error, receipt: TransactionReceipt | null) => void, ): void; // TODO block param - call(callData: Web3.CallData): string; - call(callData: Web3.CallData, callback: (err: Error, result: string) => void): void; + call(callData: CallData): string; + call(callData: CallData, callback: (err: Error, result: string) => void): void; - estimateGas(callData: Web3.CallData): number; - estimateGas(callData: Web3.CallData, callback: (err: Error, gas: number) => void): void; + estimateGas(callData: CallData): number; + estimateGas(callData: CallData, callback: (err: Error, gas: number) => void): void; // TODO defaultBlock getTransactionCount(address: string): number; @@ -321,25 +219,6 @@ declare module 'web3' { getPeerCount(cd: (err: Error, peerCount: number) => void): void; } - type BlockParam = number | 'earliest' | 'latest' | 'pending'; - - type Unit = - | 'kwei' - | 'ada' - | 'mwei' - | 'babbage' - | 'gwei' - | 'shannon' - | 'szabo' - | 'finney' - | 'ether' - | 'kether' - | 'grand' - | 'einstein' - | 'mether' - | 'gether' - | 'tether'; - interface SyncingState { startingBlock: number; currentBlock: number; @@ -351,88 +230,6 @@ declare module 'web3' { addCallback(cb: (err: Error, isSyncing: boolean, syncingState: SyncingState) => void): void; stopWatching(): void; } - - interface AbstractBlock { - number: number | null; - hash: string | null; - parentHash: string; - nonce: string | null; - sha3Uncles: string; - logsBloom: string | null; - transactionsRoot: string; - stateRoot: string; - miner: string; - difficulty: BigNumber.BigNumber; - totalDifficulty: BigNumber.BigNumber; - extraData: string; - size: number; - gasLimit: number; - gasUsed: number; - timestamp: number; - uncles: string[]; - } - interface BlockWithoutTransactionData extends AbstractBlock { - transactions: string[]; - } - interface BlockWithTransactionData extends AbstractBlock { - transactions: Transaction[]; - } - - interface Transaction { - hash: string; - nonce: number; - blockHash: string | null; - blockNumber: number | null; - transactionIndex: number | null; - from: string; - to: string | null; - value: BigNumber.BigNumber; - gasPrice: BigNumber.BigNumber; - gas: number; - input: string; - } - - interface CallTxDataBase { - to?: string; - value?: number | string | BigNumber.BigNumber; - gas?: number | string | BigNumber.BigNumber; - gasPrice?: number | string | BigNumber.BigNumber; - data?: string; - nonce?: number; - } - - interface TxData extends CallTxDataBase { - from: string; - } - - interface CallData extends CallTxDataBase { - from?: string; - } - - interface TransactionReceipt { - blockHash: string; - blockNumber: number; - transactionHash: string; - transactionIndex: number; - from: string; - to: string; - status: null | string | 0 | 1; - cumulativeGasUsed: number; - gasUsed: number; - contractAddress: string | null; - logs: LogEntry[]; - } - - interface LogEntry { - logIndex: number | null; - transactionIndex: number | null; - transactionHash: string; - blockHash: string | null; - blockNumber: number | null; - address: string; - data: string; - topics: string[]; - } } /* tslint:disable */ export = Web3; diff --git a/packages/utils/src/abi_decoder.ts b/packages/utils/src/abi_decoder.ts index 2b496eb17..d49906cfb 100644 --- a/packages/utils/src/abi_decoder.ts +++ b/packages/utils/src/abi_decoder.ts @@ -1,13 +1,22 @@ -import { AbiType, DecodedLogArgs, LogWithDecodedArgs, RawLog, SolidityTypes } from '@0xproject/types'; +import { + AbiDefinition, + AbiType, + DecodedLogArgs, + EventAbi, + EventParameter, + LogEntry, + LogWithDecodedArgs, + RawLog, + SolidityTypes, +} from '@0xproject/types'; import * as ethersContracts from 'ethers-contracts'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import { BigNumber } from './configured_bignumber'; export class AbiDecoder { - private _savedABIs: Web3.AbiDefinition[] = []; - private _methodIds: { [signatureHash: string]: Web3.EventAbi } = {}; + private _savedABIs: AbiDefinition[] = []; + private _methodIds: { [signatureHash: string]: EventAbi } = {}; private static _padZeros(address: string) { let formatted = address; if (_.startsWith(formatted, '0x')) { @@ -17,11 +26,11 @@ export class AbiDecoder { formatted = _.padStart(formatted, 40, '0'); return `0x${formatted}`; } - constructor(abiArrays: Web3.AbiDefinition[][]) { + constructor(abiArrays: AbiDefinition[][]) { _.forEach(abiArrays, this._addABI.bind(this)); } // This method can only decode logs from the 0x & ERC20 smart contracts - public tryToDecodeLogOrNoop<ArgsType>(log: Web3.LogEntry): LogWithDecodedArgs<ArgsType> | RawLog { + public tryToDecodeLogOrNoop<ArgsType>(log: LogEntry): LogWithDecodedArgs<ArgsType> | RawLog { const methodId = log.topics[0]; const event = this._methodIds[methodId]; if (_.isUndefined(event)) { @@ -37,7 +46,7 @@ export class AbiDecoder { const decodedData = ethersInterface.events[event.name].parse(log.data); let failedToDecode = false; - _.forEach(event.inputs, (param: Web3.EventParameter, i: number) => { + _.forEach(event.inputs, (param: EventParameter, i: number) => { // Indexed parameters are stored in topics. Non-indexed ones in decodedData let value: BigNumber | string | number = param.indexed ? log.topics[topicsIndex++] : decodedData[i]; if (_.isUndefined(value)) { @@ -64,12 +73,12 @@ export class AbiDecoder { }; } } - private _addABI(abiArray: Web3.AbiDefinition[]): void { + private _addABI(abiArray: AbiDefinition[]): void { if (_.isUndefined(abiArray)) { return; } const ethersInterface = new ethersContracts.Interface(abiArray); - _.map(abiArray, (abi: Web3.AbiDefinition) => { + _.map(abiArray, (abi: AbiDefinition) => { if (abi.type === AbiType.Event) { const topic = ethersInterface.events[abi.name].topic; this._methodIds[topic] = abi; diff --git a/packages/web3-wrapper/src/index.ts b/packages/web3-wrapper/src/index.ts index 2ce2580ee..87c69b269 100644 --- a/packages/web3-wrapper/src/index.ts +++ b/packages/web3-wrapper/src/index.ts @@ -1,4 +1,16 @@ -import { RawLogEntry, TransactionReceipt, TxData } from '@0xproject/types'; +import { + BlockParam, + BlockWithoutTransactionData, + CallData, + ContractAbi, + FilterObject, + JSONRPCRequestPayload, + JSONRPCResponsePayload, + LogEntry, + RawLogEntry, + TransactionReceipt, + TxData, +} from '@0xproject/types'; import { BigNumber, promisify } from '@0xproject/utils'; import * as _ from 'lodash'; import * as Web3 from 'web3'; @@ -157,8 +169,8 @@ export class Web3Wrapper { * @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral) * @returns The requested block without transaction data */ - public async getBlockAsync(blockParam: string | Web3.BlockParam): Promise<Web3.BlockWithoutTransactionData> { - const block = await promisify<Web3.BlockWithoutTransactionData>(this._web3.eth.getBlock)(blockParam); + public async getBlockAsync(blockParam: string | BlockParam): Promise<BlockWithoutTransactionData> { + const block = await promisify<BlockWithoutTransactionData>(this._web3.eth.getBlock)(blockParam); return block; } /** @@ -166,7 +178,7 @@ export class Web3Wrapper { * @param blockParam The block you wish to fetch (blockHash, blockNumber or blockLiteral) * @returns The block's timestamp */ - public async getBlockTimestampAsync(blockParam: string | Web3.BlockParam): Promise<number> { + public async getBlockTimestampAsync(blockParam: string | BlockParam): Promise<number> { const { timestamp } = await this.getBlockAsync(blockParam); return timestamp; } @@ -214,7 +226,7 @@ export class Web3Wrapper { * @param filter Parameters by which to filter which logs to retrieve * @returns The corresponding log entries */ - public async getLogsAsync(filter: Web3.FilterObject): Promise<Web3.LogEntry[]> { + public async getLogsAsync(filter: FilterObject): Promise<LogEntry[]> { let fromBlock = filter.fromBlock; if (_.isNumber(fromBlock)) { fromBlock = this._web3.toHex(fromBlock); @@ -243,7 +255,7 @@ export class Web3Wrapper { * @param abi Smart contract ABI * @returns Web3 contract factory which can create Web3 Contract instances from the supplied ABI */ - public getContractFromAbi(abi: Web3.ContractAbi): Web3.Contract<any> { + public getContractFromAbi(abi: ContractAbi): Web3.Contract<any> { const web3Contract = this._web3.eth.contract(abi); return web3Contract; } @@ -252,7 +264,7 @@ export class Web3Wrapper { * @param txData Transaction data * @returns Estimated gas cost */ - public async estimateGasAsync(txData: Partial<Web3.TxData>): Promise<number> { + public async estimateGasAsync(txData: Partial<TxData>): Promise<number> { const gas = await promisify<number>(this._web3.eth.estimateGas)(txData); return gas; } @@ -262,7 +274,7 @@ export class Web3Wrapper { * @param defaultBlock Block height at which to make the call. Defaults to `latest` * @returns The raw call result */ - public async callAsync(callData: Web3.CallData, defaultBlock?: Web3.BlockParam): Promise<string> { + public async callAsync(callData: CallData, defaultBlock?: BlockParam): Promise<string> { const rawCallResult = await promisify<string>(this._web3.eth.call)(callData, defaultBlock); return rawCallResult; } @@ -271,13 +283,13 @@ export class Web3Wrapper { * @param txData Transaction data * @returns Transaction hash */ - public async sendTransactionAsync(txData: Web3.TxData): Promise<string> { + public async sendTransactionAsync(txData: TxData): Promise<string> { const txHash = await promisify<string>(this._web3.eth.sendTransaction)(txData); return txHash; } - private async _sendRawPayloadAsync<A>(payload: Partial<Web3.JSONRPCRequestPayload>): Promise<A> { + private async _sendRawPayloadAsync<A>(payload: Partial<JSONRPCRequestPayload>): Promise<A> { const sendAsync = this._web3.currentProvider.sendAsync.bind(this._web3.currentProvider); - const response = await promisify<Web3.JSONRPCResponsePayload>(sendAsync)(payload); + const response = await promisify<JSONRPCResponsePayload>(sendAsync)(payload); const result = response.result; return result; } @@ -295,7 +307,7 @@ export class Web3Wrapper { return status; } } - private _formatLog(rawLog: RawLogEntry): Web3.LogEntry { + private _formatLog(rawLog: RawLogEntry): LogEntry { const formattedLog = { ...rawLog, logIndex: this._hexToDecimal(rawLog.logIndex), diff --git a/packages/website/ts/containers/web3_wrapper_documentation.ts b/packages/website/ts/containers/web3_wrapper_documentation.ts index 0a0911b80..289006f10 100644 --- a/packages/website/ts/containers/web3_wrapper_documentation.ts +++ b/packages/website/ts/containers/web3_wrapper_documentation.ts @@ -48,26 +48,25 @@ const docsInfoConfig: DocsInfoConfig = { typeConfigs: { // Note: This needs to be kept in sync with the types exported in index.ts. Unfortunately there is // currently no way to extract the re-exported types from index.ts via TypeDoc :( - publicTypes: ['TxData', 'TransactionReceipt', 'RawLogEntry'], + publicTypes: [ + 'TxData', + 'TransactionReceipt', + 'RawLogEntry', + 'ContractAbi', + 'BlockParam', + 'FilterObject', + 'LogEntry', + 'BlockWithoutTransactionData', + 'CallData', + 'LogEntryEvent', + ], typeNameToExternalLink: { Web3: 'https://github.com/ethereum/wiki/wiki/JavaScript-API', Provider: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L150', - BigNumber: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L127', - LogEntryEvent: 'http://mikemcl.github.io/bignumber.js', - CallData: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L348', - BlockWithoutTransactionData: - 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L314', - LogEntry: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L366', - FilterObject: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L109', - ['Web3.BlockParam']: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L278', - ['Web3.ContractAbi']: 'https://github.com/0xProject/web3-typescript-typings/blob/f5bcb96/index.d.ts#L47', + BigNumber: 'http://mikemcl.github.io/bignumber.js', }, typeNameToPrefix: { Provider: 'Web3', - CallData: 'Web3', - BlockWithoutTransactionData: 'Web3', - LogEntry: 'Web3', - FilterObject: 'Web3', }, typeNameToDocSection: { Web3Wrapper: docSections.web3Wrapper, diff --git a/packages/website/ts/globals.d.ts b/packages/website/ts/globals.d.ts index ef276519c..3791b3269 100644 --- a/packages/website/ts/globals.d.ts +++ b/packages/website/ts/globals.d.ts @@ -115,11 +115,11 @@ declare module 'web3-provider-engine/subproviders/subprovider' { export = Subprovider; } declare module 'web3-provider-engine/subproviders/rpc' { - import * as Web3 from 'web3'; + import { JSONRPCRequestPayload } from '@0xproject/types'; class RpcSubprovider { constructor(options: { rpcUrl: string }); public handleRequest( - payload: Web3.JSONRPCRequestPayload, + payload: JSONRPCRequestPayload, next: () => void, end: (err: Error | null, data?: any) => void, ): void; |