diff options
Diffstat (limited to 'packages')
117 files changed, 1763 insertions, 804 deletions
diff --git a/packages/0x.js/CHANGELOG.json b/packages/0x.js/CHANGELOG.json index fd248ff44..6d5dc0dd2 100644 --- a/packages/0x.js/CHANGELOG.json +++ b/packages/0x.js/CHANGELOG.json @@ -1,5 +1,14 @@ [ { + "version": "0.36.0", + "changes": [ + { + "note": "Moved Web3.Provider to `@0xproject/types:Provider`", + "pr": 501 + } + ] + }, + { "version": "0.35.0", "changes": [ { diff --git a/packages/0x.js/README.md b/packages/0x.js/README.md index 5b17dac8b..46848cbdd 100644 --- a/packages/0x.js/README.md +++ b/packages/0x.js/README.md @@ -1,5 +1,9 @@ ## 0x.js +A TypeScript/Javascript library for interacting with the 0x protocol. + +### Read the [Documentation](0xproject.com/docs/0xjs). + ## Installation 0x.js ships as both a [UMD](https://github.com/umdjs/umd) module and a [CommonJS](https://en.wikipedia.org/wiki/CommonJS) package. @@ -38,10 +42,66 @@ Download the UMD module from our [releases page](https://github.com/0xProject/0x <script type="text/javascript" src="0x.js"></script> ``` -## Documentation +## Contributing + +We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. + +Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. + +### Install dependencies + +If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: + +```bash +yarn config set workspaces-experimental true +``` + +Then install dependencies + +```bash +yarn install +``` + +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + +### Lint -Extensive documentation of 0x.js can be found on [our website][docs-url]. +```bash +yarn lint +``` + +### Run Tests -[website-url]: https://0xproject.com/ -[whitepaper-url]: https://0xproject.com/pdfs/0x_white_paper.pdf -[docs-url]: https://0xproject.com/docs/0xjs +```bash +yarn test +``` diff --git a/packages/0x.js/src/0x.ts b/packages/0x.js/src/0x.ts index 774b9ac12..94d97c23e 100644 --- a/packages/0x.js/src/0x.ts +++ b/packages/0x.js/src/0x.ts @@ -1,5 +1,5 @@ import { schemas, SchemaValidator } from '@0xproject/json-schemas'; -import { ECSignature, Order, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types'; +import { ECSignature, Order, Provider, SignedOrder, TransactionReceiptWithDecodedLogs } from '@0xproject/types'; import { AbiDecoder, BigNumber, intervalUtils } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as ethUtil from 'ethereumjs-util'; @@ -15,7 +15,7 @@ import { OrderStateWatcher } from './order_watcher/order_state_watcher'; import { zeroExConfigSchema } from './schemas/zero_ex_config_schema'; import { zeroExPrivateNetworkConfigSchema } from './schemas/zero_ex_private_network_config_schema'; import { zeroExPublicNetworkConfigSchema } from './schemas/zero_ex_public_network_config_schema'; -import { OrderStateWatcherConfig, Web3Provider, ZeroExConfig, ZeroExError } from './types'; +import { OrderStateWatcherConfig, ZeroExConfig, ZeroExError } from './types'; import { assert } from './utils/assert'; import { constants } from './utils/constants'; import { decorators } from './utils/decorators'; @@ -115,10 +115,8 @@ export class ZeroEx { public static toUnitAmount(amount: BigNumber, decimals: number): BigNumber { assert.isValidBaseUnitAmount('amount', amount); assert.isNumber('decimals', decimals); - - const aUnit = new BigNumber(10).pow(decimals); - const unit = amount.div(aUnit); - return unit; + const unitAmount = Web3Wrapper.toUnitAmount(amount, decimals); + return unitAmount; } /** * A baseUnit is defined as the smallest denomination of a token. An amount expressed in baseUnits @@ -131,13 +129,7 @@ export class ZeroEx { public static toBaseUnitAmount(amount: BigNumber, decimals: number): BigNumber { assert.isBigNumber('amount', amount); assert.isNumber('decimals', decimals); - - const unit = new BigNumber(10).pow(decimals); - const baseUnitAmount = amount.times(unit); - const hasDecimals = baseUnitAmount.decimalPlaces() !== 0; - if (hasDecimals) { - throw new Error(`Invalid unit amount: ${amount.toString()} - Too many decimal places`); - } + const baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amount, decimals); return baseUnitAmount; } /** @@ -153,12 +145,12 @@ export class ZeroEx { } /** * Instantiates a new ZeroEx instance that provides the public interface to the 0x.js library. - * @param provider The Web3.js Provider instance you would like the 0x.js library to use for interacting with + * @param provider The Provider instance you would like the 0x.js library to use for interacting with * the Ethereum network. * @param config The configuration object. Look up the type for the description. * @return An instance of the 0x.js ZeroEx class. */ - constructor(provider: Web3Provider, config: ZeroExConfig) { + constructor(provider: Provider, config: ZeroExConfig) { assert.isWeb3Provider('provider', provider); assert.doesConformToSchema('config', config, zeroExConfigSchema, [ zeroExPrivateNetworkConfigSchema, @@ -199,7 +191,7 @@ export class ZeroEx { * @param provider The Web3Provider you would like the 0x.js library to use from now on. * @param networkId The id of the network your provider is connected to */ - public setProvider(provider: Web3Provider, networkId: number): void { + public setProvider(provider: Provider, networkId: number): void { this._web3Wrapper.setProvider(provider); (this.exchange as any)._invalidateContractInstances(); (this.exchange as any)._setNetworkId(networkId); @@ -225,7 +217,7 @@ export class ZeroEx { * This method currently supports TestRPC, Geth and Parity above and below V1.6.6 * @param orderHash Hex encoded orderHash to sign. * @param signerAddress The hex encoded Ethereum address you wish to sign it with. This address - * must be available via the Web3.Provider supplied to 0x.js. + * must be available via the Provider supplied to 0x.js. * @param shouldAddPersonalMessagePrefix Some signers add the personal message prefix `\x19Ethereum Signed Message` * themselves (e.g Parity Signer, Ledger, TestRPC) and others expect it to already be done by the client * (e.g Metamask). Depending on which signer this request is going to, decide on whether to add the prefix diff --git a/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts b/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts index f52dba2f1..fd39de34b 100644 --- a/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/ether_token_wrapper.ts @@ -191,7 +191,12 @@ export class EtherTokenWrapper extends ContractWrapper { artifacts.EtherTokenArtifact, etherTokenAddress, ); - const contractInstance = new EtherTokenContract(this._web3Wrapper, abi, address); + const contractInstance = new EtherTokenContract( + abi, + address, + this._web3Wrapper.getProvider(), + this._web3Wrapper.getContractDefaults(), + ); etherTokenContract = contractInstance; this._etherTokenContractsByAddress[etherTokenAddress] = etherTokenContract; return etherTokenContract; diff --git a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts index 53f32f111..378ae8111 100644 --- a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts @@ -170,7 +170,7 @@ export class ExchangeWrapper extends ContractWrapper { * @param shouldThrowOnInsufficientBalanceOrAllowance Whether or not you wish for the contract call to throw * if upon execution the tokens cannot be transferred. * @param takerAddress The user Ethereum address who would like to fill this order. - * Must be available via the supplied Web3.Provider + * Must be available via the supplied Provider * passed to 0x.js. * @param orderTransactionOpts Optional arguments this method accepts. * @return Transaction hash. @@ -235,7 +235,7 @@ export class ExchangeWrapper extends ContractWrapper { * If set to false, the call will continue to fill subsequent * signedOrders even when some cannot be filled. * @param takerAddress The user Ethereum address who would like to fill these - * orders. Must be available via the supplied Web3.Provider + * orders. Must be available via the supplied Provider * passed to 0x.js. * @param orderTransactionOpts Optional arguments this method accepts. * @return Transaction hash. @@ -335,7 +335,7 @@ export class ExchangeWrapper extends ContractWrapper { * cannot be filled. * @param takerAddress The user Ethereum address who would like to fill * these orders. Must be available via the supplied - * Web3.Provider passed to 0x.js. + * Provider passed to 0x.js. * @param orderTransactionOpts Optional arguments this method accepts. * @return Transaction hash. */ @@ -416,7 +416,7 @@ export class ExchangeWrapper extends ContractWrapper { * signedOrder you wish to fill. * @param fillTakerTokenAmount The total amount of the takerTokens you would like to fill. * @param takerAddress The user Ethereum address who would like to fill this order. - * Must be available via the supplied Web3.Provider passed to 0x.js. + * Must be available via the supplied Provider passed to 0x.js. * @param orderTransactionOpts Optional arguments this method accepts. * @return Transaction hash. */ @@ -470,7 +470,7 @@ export class ExchangeWrapper extends ContractWrapper { * filled (each to the specified fillAmount) or aborted. * @param orderFillRequests An array of objects that conform to the OrderFillRequest interface. * @param takerAddress The user Ethereum address who would like to fill there orders. - * Must be available via the supplied Web3.Provider passed to 0x.js. + * Must be available via the supplied Provider passed to 0x.js. * @param orderTransactionOpts Optional arguments this method accepts. * @return Transaction hash. */ @@ -765,7 +765,7 @@ export class ExchangeWrapper extends ContractWrapper { * signedOrder you wish to fill. * @param fillTakerTokenAmount The total amount of the takerTokens you would like to fill. * @param takerAddress The user Ethereum address who would like to fill this order. - * Must be available via the supplied Web3.Provider passed to 0x.js. + * Must be available via the supplied Provider passed to 0x.js. */ public async validateFillOrderThrowIfInvalidAsync( signedOrder: SignedOrder, @@ -812,7 +812,7 @@ export class ExchangeWrapper extends ContractWrapper { * signedOrder you wish to fill. * @param fillTakerTokenAmount The total amount of the takerTokens you would like to fill. * @param takerAddress The user Ethereum address who would like to fill this order. - * Must be available via the supplied Web3.Provider passed to 0x.js. + * Must be available via the supplied Provider passed to 0x.js. */ public async validateFillOrKillOrderThrowIfInvalidAsync( signedOrder: SignedOrder, @@ -920,7 +920,12 @@ export class ExchangeWrapper extends ContractWrapper { artifacts.ExchangeArtifact, this._contractAddressIfExists, ); - const contractInstance = new ExchangeContract(this._web3Wrapper, abi, address); + const contractInstance = new ExchangeContract( + abi, + address, + this._web3Wrapper.getProvider(), + this._web3Wrapper.getContractDefaults(), + ); this._exchangeContractIfExists = contractInstance; return this._exchangeContractIfExists; } diff --git a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts index e1806c6f2..c4a193264 100644 --- a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts @@ -121,7 +121,12 @@ export class TokenRegistryWrapper extends ContractWrapper { artifacts.TokenRegistryArtifact, this._contractAddressIfExists, ); - const contractInstance = new TokenRegistryContract(this._web3Wrapper, abi, address); + const contractInstance = new TokenRegistryContract( + abi, + address, + this._web3Wrapper.getProvider(), + this._web3Wrapper.getContractDefaults(), + ); this._tokenRegistryContractIfExists = contractInstance; return this._tokenRegistryContractIfExists; } diff --git a/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts index 211c7dfb4..be558b5be 100644 --- a/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_transfer_proxy_wrapper.ts @@ -63,7 +63,12 @@ export class TokenTransferProxyWrapper extends ContractWrapper { artifacts.TokenTransferProxyArtifact, this._contractAddressIfExists, ); - const contractInstance = new TokenTransferProxyContract(this._web3Wrapper, abi, address); + const contractInstance = new TokenTransferProxyContract( + abi, + address, + this._web3Wrapper.getProvider(), + this._web3Wrapper.getContractDefaults(), + ); this._tokenTransferProxyContractIfExists = contractInstance; return this._tokenTransferProxyContractIfExists; } diff --git a/packages/0x.js/src/contract_wrappers/token_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_wrapper.ts index 5224d451c..194cfb5aa 100644 --- a/packages/0x.js/src/contract_wrappers/token_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_wrapper.ts @@ -421,7 +421,12 @@ export class TokenWrapper extends ContractWrapper { artifacts.TokenArtifact, normalizedTokenAddress, ); - const contractInstance = new TokenContract(this._web3Wrapper, abi, address); + const contractInstance = new TokenContract( + abi, + address, + this._web3Wrapper.getProvider(), + this._web3Wrapper.getContractDefaults(), + ); tokenContract = contractInstance; this._tokenContractsByAddress[normalizedTokenAddress] = tokenContract; return tokenContract; diff --git a/packages/0x.js/src/globals.d.ts b/packages/0x.js/src/globals.d.ts index b9b691ba1..94e63a32d 100644 --- a/packages/0x.js/src/globals.d.ts +++ b/packages/0x.js/src/globals.d.ts @@ -1,10 +1,3 @@ -declare module 'web3_beta'; - -// semver-sort declarations -declare module 'semver-sort' { - const desc: (versions: string[]) => string[]; -} - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts index e353a1d3d..3b973bd54 100644 --- a/packages/0x.js/src/index.ts +++ b/packages/0x.js/src/index.ts @@ -11,7 +11,6 @@ export { OrderCancellationRequest, OrderFillRequest, ContractEventArgs, - Web3Provider, ZeroExConfig, MethodOpts, OrderTransactionOpts, @@ -32,6 +31,7 @@ export { ContractEventArg, LogWithDecodedArgs, Order, + Provider, SignedOrder, ECSignature, TransactionReceipt, diff --git a/packages/0x.js/src/types.ts b/packages/0x.js/src/types.ts index 1f128d656..d1c643a57 100644 --- a/packages/0x.js/src/types.ts +++ b/packages/0x.js/src/types.ts @@ -154,14 +154,6 @@ export interface OrderFillRequest { export type AsyncMethod = (...args: any[]) => Promise<any>; export type SyncMethod = (...args: any[]) => any; -/** - * We re-export the `Web3.Provider` type specified in the Web3 Typescript typings - * since it is the type of the `provider` argument to the `ZeroEx` constructor. - * It is however a `Web3` library type, not a native `0x.js` type. To learn more - * about providers, visit https://0xproject.com/wiki#Web3-Provider-Explained - */ -export type Web3Provider = Web3.Provider; - /* * orderExpirationCheckingIntervalMs: How often to check for expired orders. Default: 50 * eventPollingIntervalMs: How often to poll the Ethereum node for new events. Default: 200 diff --git a/packages/0x.js/test/ether_token_wrapper_test.ts b/packages/0x.js/test/ether_token_wrapper_test.ts index 6237ccf23..644101dc7 100644 --- a/packages/0x.js/test/ether_token_wrapper_test.ts +++ b/packages/0x.js/test/ether_token_wrapper_test.ts @@ -1,5 +1,6 @@ import { BlockchainLifecycle, devConstants, web3Factory } from '@0xproject/dev-utils'; import { BigNumber } from '@0xproject/utils'; +import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as chai from 'chai'; import 'mocha'; import * as Web3 from 'web3'; @@ -59,7 +60,7 @@ describe('EtherTokenWrapper', () => { userAddresses = await zeroEx.getAvailableAddressesAsync(); addressWithETH = userAddresses[0]; wethContractAddress = zeroEx.etherToken.getContractAddressIfExists() as string; - depositWeiAmount = (zeroEx as any)._web3Wrapper.toWei(new BigNumber(5)); + depositWeiAmount = Web3Wrapper.toWei(new BigNumber(5)); decimalPlaces = 7; addressWithoutFunds = userAddresses[1]; }); @@ -105,7 +106,7 @@ describe('EtherTokenWrapper', () => { it('should throw if user has insufficient ETH balance for deposit', async () => { const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH); - const extraETHBalance = (zeroEx as any)._web3Wrapper.toWei(5, 'ether'); + const extraETHBalance = Web3Wrapper.toWei(new BigNumber(5)); const overETHBalanceinWei = preETHBalance.add(extraETHBalance); return expect( diff --git a/packages/0x.js/test/utils/fill_scenarios.ts b/packages/0x.js/test/utils/fill_scenarios.ts index 8b1308298..7d0e8c501 100644 --- a/packages/0x.js/test/utils/fill_scenarios.ts +++ b/packages/0x.js/test/utils/fill_scenarios.ts @@ -36,7 +36,12 @@ export class FillScenarios { for (const token of this._tokens) { if (token.symbol !== 'ZRX' && token.symbol !== 'WETH') { const defaults = {}; - const dummyToken = new DummyTokenContract(web3Wrapper, artifacts.DummyTokenArtifact.abi, token.address); + const dummyToken = new DummyTokenContract( + artifacts.DummyTokenArtifact.abi, + token.address, + web3Wrapper.getProvider(), + web3Wrapper.getContractDefaults(), + ); const tokenSupply = ZeroEx.toBaseUnitAmount(INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS, token.decimals); const txHash = await dummyToken.setBalance.sendTransactionAsync(this._coinbase, tokenSupply, { from: this._coinbase, diff --git a/packages/abi-gen/README.md b/packages/abi-gen/README.md index 899b4845e..301bd709f 100644 --- a/packages/abi-gen/README.md +++ b/packages/abi-gen/README.md @@ -57,3 +57,61 @@ See the [type definition](https://github.com/0xProject/0x-monorepo/tree/developm ## Output files Output files will be generated within an output folder with names converted to camel case and taken from abi file names. If you already have some files in that folder they will be overwritten. + +## Contributing + +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. + +Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. + +### Install dependencies + +If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: + +```bash +yarn config set workspaces-experimental true +``` + +Then install dependencies + +```bash +yarn install +``` + +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + +### Lint + +```bash +yarn lint +``` diff --git a/packages/abi-gen/src/globals.d.ts b/packages/abi-gen/src/globals.d.ts index d267a4106..94e63a32d 100644 --- a/packages/abi-gen/src/globals.d.ts +++ b/packages/abi-gen/src/globals.d.ts @@ -1,8 +1,3 @@ -declare function toSnakeCase(str: string): string; -declare module 'to-snake-case' { - export = toSnakeCase; -} - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/assert/README.md b/packages/assert/README.md index 7f80e7e5d..598fee613 100644 --- a/packages/assert/README.md +++ b/packages/assert/README.md @@ -26,11 +26,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -46,10 +46,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/assert/src/index.ts b/packages/assert/src/index.ts index 171909c93..938daab92 100644 --- a/packages/assert/src/index.ts +++ b/packages/assert/src/index.ts @@ -61,7 +61,7 @@ export const assert = { }, isWeb3Provider(variableName: string, value: any): void { const isWeb3Provider = _.isFunction(value.send) || _.isFunction(value.sendAsync); - this.assert(isWeb3Provider, this.typeAssertionMessage(variableName, 'Web3.Provider', value)); + this.assert(isWeb3Provider, this.typeAssertionMessage(variableName, 'Provider', value)); }, doesConformToSchema(variableName: string, value: any, schema: Schema, subSchemas?: Schema[]): void { const schemaValidator = new SchemaValidator(); diff --git a/packages/base-contract/CHANGELOG.json b/packages/base-contract/CHANGELOG.json index bb7cf261f..da957ec83 100644 --- a/packages/base-contract/CHANGELOG.json +++ b/packages/base-contract/CHANGELOG.json @@ -1,5 +1,14 @@ [ { + "version": "0.2.0", + "changes": [ + { + "note": "Contract wrappers now accept Provider and defaults instead of Web3Wrapper", + "pr": 501 + } + ] + }, + { "version": "0.1.0", "changes": [ { diff --git a/packages/base-contract/src/index.ts b/packages/base-contract/src/index.ts index c8cbd7886..bba686f8b 100644 --- a/packages/base-contract/src/index.ts +++ b/packages/base-contract/src/index.ts @@ -1,4 +1,4 @@ -import { ContractAbi, DataItem, TxData, TxDataPayable } from '@0xproject/types'; +import { ContractAbi, DataItem, Provider, TxData, TxDataPayable } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as ethersContracts from 'ethers-contracts'; @@ -49,8 +49,8 @@ export class BaseContract { } return txDataWithDefaults; } - constructor(web3Wrapper: Web3Wrapper, abi: ContractAbi, address: string) { - this._web3Wrapper = web3Wrapper; + constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) { + this._web3Wrapper = new Web3Wrapper(provider, defaults); this.abi = abi; this.address = address; this._ethersInterface = new ethersContracts.Interface(abi); diff --git a/packages/connect/README.md b/packages/connect/README.md index 7087214d6..a57fefa59 100644 --- a/packages/connect/README.md +++ b/packages/connect/README.md @@ -23,11 +23,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -43,10 +43,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/connect/src/globals.d.ts b/packages/connect/src/globals.d.ts index dd659d094..783b92913 100644 --- a/packages/connect/src/globals.d.ts +++ b/packages/connect/src/globals.d.ts @@ -1,5 +1,3 @@ -declare module 'async-child-process'; - declare module '*.json' { const value: any; export default value; diff --git a/packages/contract_templates/contract.handlebars b/packages/contract_templates/contract.handlebars index da2639f78..3e3f87f10 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 { BlockParam, BlockParamLiteral, CallData, ContractAbi, DataItem, MethodAbi, TxData, TxDataPayable } from '@0xproject/types'; +import { BlockParam, BlockParamLiteral, CallData, ContractAbi, DataItem, MethodAbi, Provider, TxData, TxDataPayable } from '@0xproject/types'; import { BigNumber, classUtils, promisify } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as ethersContracts from 'ethers-contracts'; @@ -39,8 +39,8 @@ export class {{contractName}}Contract extends BaseContract { {{> tx contractName=../contractName}} {{/this.constant}} {{/each}} - constructor(web3Wrapper: Web3Wrapper, abi: ContractAbi, address: string) { - super(web3Wrapper, abi, address); + constructor(abi: ContractAbi, address: string, provider: Provider, defaults?: Partial<TxData>) { + super(abi, address, provider, defaults); classUtils.bindAll(this, ['_ethersInterface', 'address', 'abi', '_web3Wrapper']); } } // tslint:disable:max-file-line-count diff --git a/packages/contracts/README.md b/packages/contracts/README.md index 7628b057b..286ef019c 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -34,11 +34,25 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch diff --git a/packages/contracts/test/ether_token.ts b/packages/contracts/test/ether_token.ts index 6c7354c2b..4023abad0 100644 --- a/packages/contracts/test/ether_token.ts +++ b/packages/contracts/test/ether_token.ts @@ -9,7 +9,7 @@ import { ContractName } from '../util/types'; import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -26,7 +26,7 @@ describe('EtherToken', () => { const etherToken = await deployer.deployAsync(ContractName.EtherToken); etherTokenAddress = etherToken.address; - zeroEx = new ZeroEx(web3.currentProvider, { + zeroEx = new ZeroEx(provider, { gasPrice, networkId: constants.TESTRPC_NETWORK_ID, }); @@ -51,7 +51,7 @@ describe('EtherToken', () => { const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); - const ethToDeposit = new BigNumber(web3.toWei(1, 'ether')); + const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1))); const txHash = await zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account); const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); @@ -76,7 +76,7 @@ describe('EtherToken', () => { }); it('should convert ether tokens to ether with sufficient balance', async () => { - const ethToDeposit = new BigNumber(web3.toWei(1, 'ether')); + const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1))); await zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account); const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); diff --git a/packages/contracts/test/exchange/core.ts b/packages/contracts/test/exchange/core.ts index e276d11b3..689b11062 100644 --- a/packages/contracts/test/exchange/core.ts +++ b/packages/contracts/test/exchange/core.ts @@ -22,7 +22,7 @@ import { OrderFactory } from '../../util/order_factory'; import { BalancesByOwner, ContractName, ExchangeContractErrs } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -59,22 +59,22 @@ describe('Exchange', () => { deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS), deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS), ]); - rep = new DummyTokenContract(web3Wrapper, repInstance.abi, repInstance.address); - dgd = new DummyTokenContract(web3Wrapper, dgdInstance.abi, dgdInstance.address); - zrx = new DummyTokenContract(web3Wrapper, zrxInstance.abi, zrxInstance.address); + rep = new DummyTokenContract(repInstance.abi, repInstance.address, provider); + dgd = new DummyTokenContract(dgdInstance.abi, dgdInstance.address, provider); + zrx = new DummyTokenContract(zrxInstance.abi, zrxInstance.address, provider); const tokenTransferProxyInstance = await deployer.deployAsync(ContractName.TokenTransferProxy); tokenTransferProxy = new TokenTransferProxyContract( - web3Wrapper, tokenTransferProxyInstance.abi, tokenTransferProxyInstance.address, + provider, ); const exchangeInstance = await deployer.deployAsync(ContractName.Exchange, [ zrx.address, tokenTransferProxy.address, ]); - exchange = new ExchangeContract(web3Wrapper, exchangeInstance.abi, exchangeInstance.address); + exchange = new ExchangeContract(exchangeInstance.abi, exchangeInstance.address, provider); await tokenTransferProxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, { from: accounts[0] }); - zeroEx = new ZeroEx(web3.currentProvider, { + zeroEx = new ZeroEx(provider, { exchangeContractAddress: exchange.address, networkId: constants.TESTRPC_NETWORK_ID, }); diff --git a/packages/contracts/test/exchange/helpers.ts b/packages/contracts/test/exchange/helpers.ts index 080cbe5fd..8fc30c0b5 100644 --- a/packages/contracts/test/exchange/helpers.ts +++ b/packages/contracts/test/exchange/helpers.ts @@ -17,7 +17,7 @@ import { OrderFactory } from '../../util/order_factory'; import { ContractName } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -46,9 +46,9 @@ describe('Exchange', () => { zrx.address, tokenTransferProxy.address, ]); - const exchange = new ExchangeContract(web3Wrapper, exchangeInstance.abi, exchangeInstance.address); + const exchange = new ExchangeContract(exchangeInstance.abi, exchangeInstance.address, provider); await tokenTransferProxy.addAuthorizedAddress(exchange.address, { from: accounts[0] }); - const zeroEx = new ZeroEx(web3.currentProvider, { networkId: constants.TESTRPC_NETWORK_ID }); + const zeroEx = new ZeroEx(provider, { networkId: constants.TESTRPC_NETWORK_ID }); exchangeWrapper = new ExchangeWrapper(exchange, zeroEx); const defaultOrderParams = { exchangeContractAddress: exchange.address, diff --git a/packages/contracts/test/exchange/wrapper.ts b/packages/contracts/test/exchange/wrapper.ts index 0d3e18711..c658dca79 100644 --- a/packages/contracts/test/exchange/wrapper.ts +++ b/packages/contracts/test/exchange/wrapper.ts @@ -22,7 +22,7 @@ import { OrderFactory } from '../../util/order_factory'; import { BalancesByOwner, ContractName } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -59,28 +59,24 @@ describe('Exchange', () => { deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS), deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS), ]); - rep = new DummyTokenContract(web3Wrapper, repInstance.abi, repInstance.address); - dgd = new DummyTokenContract(web3Wrapper, dgdInstance.abi, dgdInstance.address); - zrx = new DummyTokenContract(web3Wrapper, zrxInstance.abi, zrxInstance.address); + rep = new DummyTokenContract(repInstance.abi, repInstance.address, provider); + dgd = new DummyTokenContract(dgdInstance.abi, dgdInstance.address, provider); + zrx = new DummyTokenContract(zrxInstance.abi, zrxInstance.address, provider); const tokenRegistryInstance = await deployer.deployAsync(ContractName.TokenRegistry); - tokenRegistry = new TokenRegistryContract( - web3Wrapper, - tokenRegistryInstance.abi, - tokenRegistryInstance.address, - ); + tokenRegistry = new TokenRegistryContract(tokenRegistryInstance.abi, tokenRegistryInstance.address, provider); const tokenTransferProxyInstance = await deployer.deployAsync(ContractName.TokenTransferProxy); tokenTransferProxy = new TokenTransferProxyContract( - web3Wrapper, tokenTransferProxyInstance.abi, tokenTransferProxyInstance.address, + provider, ); const exchangeInstance = await deployer.deployAsync(ContractName.Exchange, [ zrx.address, tokenTransferProxy.address, ]); - exchange = new ExchangeContract(web3Wrapper, exchangeInstance.abi, exchangeInstance.address); + exchange = new ExchangeContract(exchangeInstance.abi, exchangeInstance.address, provider); await tokenTransferProxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, { from: accounts[0] }); - const zeroEx = new ZeroEx(web3.currentProvider, { networkId: constants.TESTRPC_NETWORK_ID }); + const zeroEx = new ZeroEx(provider, { networkId: constants.TESTRPC_NETWORK_ID }); exWrapper = new ExchangeWrapper(exchange, zeroEx); const defaultOrderParams = { diff --git a/packages/contracts/test/multi_sig_with_time_lock.ts b/packages/contracts/test/multi_sig_with_time_lock.ts index d35efe9da..ea74d4c7f 100644 --- a/packages/contracts/test/multi_sig_with_time_lock.ts +++ b/packages/contracts/test/multi_sig_with_time_lock.ts @@ -15,13 +15,13 @@ import { ContractName, SubmissionContractEventArgs } from '../util/types'; import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; const MULTI_SIG_ABI = artifacts.MultiSigWalletWithTimeLockArtifact.networks[constants.TESTRPC_NETWORK_ID].abi; chaiSetup.configure(); const expect = chai.expect; const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); -const zeroEx = new ZeroEx(web3.currentProvider, { networkId: constants.TESTRPC_NETWORK_ID }); +const zeroEx = new ZeroEx(provider, { networkId: constants.TESTRPC_NETWORK_ID }); const abiDecoder = new AbiDecoder([MULTI_SIG_ABI]); describe('MultiSigWalletWithTimeLock', () => { @@ -53,9 +53,9 @@ describe('MultiSigWalletWithTimeLock', () => { 0, ]); multiSig = new MultiSigWalletWithTimeLockContract( - web3Wrapper, multiSigInstance.abi, multiSigInstance.address, + provider, ); multiSigWrapper = new MultiSigWrapper((multiSig as any) as MultiSigWalletContract); @@ -150,9 +150,9 @@ describe('MultiSigWalletWithTimeLock', () => { SECONDS_TIME_LOCKED, ]); multiSig = new MultiSigWalletWithTimeLockContract( - web3Wrapper, multiSigInstance.abi, multiSigInstance.address, + provider, ); multiSigWrapper = new MultiSigWrapper((multiSig as any) as MultiSigWalletContract); diff --git a/packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts b/packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts index 6d20a67f3..2f928ede2 100644 --- a/packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts +++ b/packages/contracts/test/multi_sig_with_time_lock_except_remove_auth_addr.ts @@ -16,7 +16,7 @@ import { ContractName, SubmissionContractEventArgs, TransactionDataParams } from import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; const PROXY_ABI = artifacts.TokenTransferProxyArtifact.networks[constants.TESTRPC_NETWORK_ID].abi; const MUTISIG_WALLET_WITH_TIME_LOCK_EXCEPT_REMOVE_AUTHORIZED_ADDRESS_ABI = artifacts.MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressArtifact.networks[constants.TESTRPC_NETWORK_ID] @@ -28,7 +28,7 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); const abiDecoder = new AbiDecoder([MUTISIG_WALLET_WITH_TIME_LOCK_EXCEPT_REMOVE_AUTHORIZED_ADDRESS_ABI]); describe('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', () => { - const zeroEx = new ZeroEx(web3.currentProvider, { networkId: constants.TESTRPC_NETWORK_ID }); + const zeroEx = new ZeroEx(provider, { networkId: constants.TESTRPC_NETWORK_ID }); let owners: string[]; const requiredApprovals = 2; const SECONDS_TIME_LOCKED = 1000000; @@ -49,9 +49,9 @@ describe('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', () => { const initialOwner = accounts[0]; const tokenTransferProxyInstance = await deployer.deployAsync(ContractName.TokenTransferProxy); tokenTransferProxy = new TokenTransferProxyContract( - web3Wrapper, tokenTransferProxyInstance.abi, tokenTransferProxyInstance.address, + provider, ); await tokenTransferProxy.addAuthorizedAddress.sendTransactionAsync(authorizedAddress, { from: initialOwner, @@ -61,9 +61,9 @@ describe('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', () => { [owners, requiredApprovals, SECONDS_TIME_LOCKED, tokenTransferProxy.address], ); multiSig = new MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddressContract( - web3Wrapper, multiSigInstance.abi, multiSigInstance.address, + provider, ); await tokenTransferProxy.transferOwnership.sendTransactionAsync(multiSig.address, { from: initialOwner, diff --git a/packages/contracts/test/token_registry.ts b/packages/contracts/test/token_registry.ts index 9dcc77b82..12fc52dbc 100644 --- a/packages/contracts/test/token_registry.ts +++ b/packages/contracts/test/token_registry.ts @@ -14,7 +14,7 @@ import { ContractName } from '../util/types'; import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -30,7 +30,7 @@ describe('TokenRegistry', () => { owner = accounts[0]; notOwner = accounts[1]; const tokenRegInstance = await deployer.deployAsync(ContractName.TokenRegistry); - tokenReg = new TokenRegistryContract(web3Wrapper, tokenRegInstance.abi, tokenRegInstance.address); + tokenReg = new TokenRegistryContract(tokenRegInstance.abi, tokenRegInstance.address, provider); tokenRegWrapper = new TokenRegWrapper(tokenReg); }); beforeEach(async () => { diff --git a/packages/contracts/test/token_transfer_proxy/auth.ts b/packages/contracts/test/token_transfer_proxy/auth.ts index a1ccc6ff7..885ff3bc1 100644 --- a/packages/contracts/test/token_transfer_proxy/auth.ts +++ b/packages/contracts/test/token_transfer_proxy/auth.ts @@ -8,7 +8,7 @@ import { constants } from '../../util/constants'; import { ContractName } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -25,9 +25,9 @@ describe('TokenTransferProxy', () => { notOwner = accounts[1]; const tokenTransferProxyInstance = await deployer.deployAsync(ContractName.TokenTransferProxy); tokenTransferProxy = new TokenTransferProxyContract( - web3Wrapper, tokenTransferProxyInstance.abi, tokenTransferProxyInstance.address, + provider, ); }); beforeEach(async () => { diff --git a/packages/contracts/test/token_transfer_proxy/transfer_from.ts b/packages/contracts/test/token_transfer_proxy/transfer_from.ts index 415d068be..dff1a0cfb 100644 --- a/packages/contracts/test/token_transfer_proxy/transfer_from.ts +++ b/packages/contracts/test/token_transfer_proxy/transfer_from.ts @@ -11,7 +11,7 @@ import { constants } from '../../util/constants'; import { ContractName } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -33,12 +33,12 @@ describe('TokenTransferProxy', () => { owner = notAuthorized = accounts[0]; const tokenTransferProxyInstance = await deployer.deployAsync(ContractName.TokenTransferProxy); tokenTransferProxy = new TokenTransferProxyContract( - web3Wrapper, tokenTransferProxyInstance.abi, tokenTransferProxyInstance.address, + provider, ); const repInstance = await deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS); - rep = new DummyTokenContract(web3Wrapper, repInstance.abi, repInstance.address); + rep = new DummyTokenContract(repInstance.abi, repInstance.address, provider); dmyBalances = new Balances([rep], [accounts[0], accounts[1]]); await Promise.all([ diff --git a/packages/contracts/test/tutorials/arbitrage.ts b/packages/contracts/test/tutorials/arbitrage.ts index b2bbaf420..ad83bbca3 100644 --- a/packages/contracts/test/tutorials/arbitrage.ts +++ b/packages/contracts/test/tutorials/arbitrage.ts @@ -17,7 +17,7 @@ import { OrderFactory } from '../../util/order_factory'; import { BalancesByOwner, ContractName, ExchangeContractErrs } from '../../util/types'; import { chaiSetup } from '../utils/chai_setup'; import { deployer } from '../utils/deployer'; -import { web3, web3Wrapper } from '../utils/web3_wrapper'; +import { provider, web3Wrapper } from '../utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -69,18 +69,18 @@ describe('Arbitrage', () => { edTakerFee, edFeeRebate, ]); - etherDelta = new EtherDeltaContract(web3Wrapper, etherDeltaInstance.abi, etherDeltaInstance.address); + etherDelta = new EtherDeltaContract(etherDeltaInstance.abi, etherDeltaInstance.address, provider); const tokenTransferProxy = await deployer.deployAsync(ContractName.TokenTransferProxy); const exchangeInstance = await deployer.deployAsync(ContractName.Exchange, [ zrx.address, tokenTransferProxy.address, ]); await tokenTransferProxy.addAuthorizedAddress(exchangeInstance.address, { from: accounts[0] }); - zeroEx = new ZeroEx(web3.currentProvider, { + zeroEx = new ZeroEx(provider, { exchangeContractAddress: exchangeInstance.address, networkId: constants.TESTRPC_NETWORK_ID, }); - const exchange = new ExchangeContract(web3Wrapper, exchangeInstance.abi, exchangeInstance.address); + const exchange = new ExchangeContract(exchangeInstance.abi, exchangeInstance.address, provider); exWrapper = new ExchangeWrapper(exchange, zeroEx); makerTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(1), 18); @@ -102,7 +102,7 @@ describe('Arbitrage', () => { etherDelta.address, tokenTransferProxy.address, ]); - arbitrage = new ArbitrageContract(web3Wrapper, arbitrageInstance.abi, arbitrageInstance.address); + arbitrage = new ArbitrageContract(arbitrageInstance.abi, arbitrageInstance.address, provider); // Enable arbitrage and withdrawals of tokens await arbitrage.setAllowances.sendTransactionAsync(weth.address, { from: coinbase }); await arbitrage.setAllowances.sendTransactionAsync(zrx.address, { from: coinbase }); diff --git a/packages/contracts/test/unlimited_allowance_token.ts b/packages/contracts/test/unlimited_allowance_token.ts index c1c518adc..618bda72d 100644 --- a/packages/contracts/test/unlimited_allowance_token.ts +++ b/packages/contracts/test/unlimited_allowance_token.ts @@ -11,7 +11,7 @@ import { ContractName } from '../util/types'; import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -23,7 +23,7 @@ describe('UnlimitedAllowanceToken', () => { const config = { networkId: constants.TESTRPC_NETWORK_ID, }; - const zeroEx = new ZeroEx(web3.currentProvider, config); + const zeroEx = new ZeroEx(provider, config); const MAX_MINT_VALUE = new BigNumber(100000000000000000000); let tokenAddress: string; @@ -34,7 +34,7 @@ describe('UnlimitedAllowanceToken', () => { owner = accounts[0]; spender = accounts[1]; const tokenInstance = await deployer.deployAsync(ContractName.DummyToken, constants.DUMMY_TOKEN_ARGS); - token = new DummyTokenContract(web3Wrapper, tokenInstance.abi, tokenInstance.address); + token = new DummyTokenContract(tokenInstance.abi, tokenInstance.address, provider); await token.mint.sendTransactionAsync(MAX_MINT_VALUE, { from: owner }); tokenAddress = token.address; }); diff --git a/packages/contracts/test/utils/deployer.ts b/packages/contracts/test/utils/deployer.ts index 1baa47f09..45f79a2a4 100644 --- a/packages/contracts/test/utils/deployer.ts +++ b/packages/contracts/test/utils/deployer.ts @@ -7,9 +7,8 @@ import { constants } from '../../util/constants'; import { web3 } from './web3_wrapper'; const deployerOpts = { - web3Provider: web3.currentProvider, + provider: web3.currentProvider, artifactsDir: path.resolve('src', 'artifacts'), - jsonrpcUrl: devConstants.RPC_URL, networkId: constants.TESTRPC_NETWORK_ID, defaults: { gas: devConstants.GAS_ESTIMATE, diff --git a/packages/contracts/test/utils/web3_wrapper.ts b/packages/contracts/test/utils/web3_wrapper.ts index 35a8095a6..1a711dad2 100644 --- a/packages/contracts/test/utils/web3_wrapper.ts +++ b/packages/contracts/test/utils/web3_wrapper.ts @@ -3,4 +3,5 @@ import { Web3Wrapper } from '@0xproject/web3-wrapper'; const web3ProviderConfig = { shouldUseInProcessGanache: true }; export const web3 = web3Factory.create(web3ProviderConfig); -export const web3Wrapper = new Web3Wrapper(web3.currentProvider); +export const provider = web3.currentProvider; +export const web3Wrapper = new Web3Wrapper(provider); diff --git a/packages/contracts/test/zrx_token.ts b/packages/contracts/test/zrx_token.ts index a4cc3c2fc..b01615b39 100644 --- a/packages/contracts/test/zrx_token.ts +++ b/packages/contracts/test/zrx_token.ts @@ -11,7 +11,7 @@ import { ContractName } from '../util/types'; import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3, web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); const expect = chai.expect; @@ -31,11 +31,11 @@ describe('ZRXToken', () => { const accounts = await web3Wrapper.getAvailableAddressesAsync(); owner = accounts[0]; spender = accounts[1]; - zeroEx = new ZeroEx(web3.currentProvider, { + zeroEx = new ZeroEx(provider, { networkId: constants.TESTRPC_NETWORK_ID, }); const zrxInstance = await deployer.deployAsync(ContractName.ZRXToken); - zrx = new ZRXTokenContract(web3Wrapper, zrxInstance.abi, zrxInstance.address); + zrx = new ZRXTokenContract(zrxInstance.abi, zrxInstance.address, provider); zrxAddress = zrx.address; MAX_UINT = zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; }); diff --git a/packages/deployer/CHANGELOG.json b/packages/deployer/CHANGELOG.json index 72f35a93d..f9691466b 100644 --- a/packages/deployer/CHANGELOG.json +++ b/packages/deployer/CHANGELOG.json @@ -1,5 +1,14 @@ [ { + "version": "0.4.0", + "changes": [ + { + "note": "Changed the config key `web3Provider` to `provider` to be consistent with other tools", + "pr": 501 + } + ] + }, + { "version": "0.3.5", "changes": [ { diff --git a/packages/deployer/README.md b/packages/deployer/README.md index 812e8c31b..d8b049bdf 100644 --- a/packages/deployer/README.md +++ b/packages/deployer/README.md @@ -41,11 +41,11 @@ var Compiler = require('@0xproject/deployer').Compiler; ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -61,16 +61,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/deployer/src/deployer.ts b/packages/deployer/src/deployer.ts index 7ee45fed5..84392997c 100644 --- a/packages/deployer/src/deployer.ts +++ b/packages/deployer/src/deployer.ts @@ -1,4 +1,4 @@ -import { AbiType, ConstructorAbi, ContractAbi, TxData } from '@0xproject/types'; +import { AbiType, ConstructorAbi, ContractAbi, Provider, TxData } from '@0xproject/types'; import { logUtils } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; @@ -38,15 +38,15 @@ export class Deployer { this._artifactsDir = opts.artifactsDir; this._networkId = opts.networkId; this._defaults = opts.defaults; - let web3Provider: Web3.Provider; - if (_.isUndefined((opts as ProviderDeployerOptions).web3Provider)) { + let web3Provider: Provider; + if (_.isUndefined((opts as ProviderDeployerOptions).provider)) { const jsonrpcUrl = (opts as UrlDeployerOptions).jsonrpcUrl; if (_.isUndefined(jsonrpcUrl)) { throw new Error(`Deployer options don't contain web3Provider nor jsonrpcUrl. Please pass one of them`); } web3Provider = new Web3.providers.HttpProvider(jsonrpcUrl); } else { - web3Provider = (opts as ProviderDeployerOptions).web3Provider; + web3Provider = (opts as ProviderDeployerOptions).provider; } this.web3Wrapper = new Web3Wrapper(web3Provider, this._defaults); } diff --git a/packages/deployer/src/utils/types.ts b/packages/deployer/src/utils/types.ts index 7cb3958cb..7d131f5ce 100644 --- a/packages/deployer/src/utils/types.ts +++ b/packages/deployer/src/utils/types.ts @@ -1,4 +1,4 @@ -import { ContractAbi, TxData } from '@0xproject/types'; +import { ContractAbi, Provider, TxData } from '@0xproject/types'; import * as Web3 from 'web3'; import * as yargs from 'yargs'; @@ -65,7 +65,7 @@ export interface BaseDeployerOptions { } export interface ProviderDeployerOptions extends BaseDeployerOptions { - web3Provider: Web3.Provider; + provider: Provider; } export interface UrlDeployerOptions extends BaseDeployerOptions { diff --git a/packages/dev-utils/README.md b/packages/dev-utils/README.md index d7e580d9f..2b183f1c7 100644 --- a/packages/dev-utils/README.md +++ b/packages/dev-utils/README.md @@ -26,3 +26,67 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol "typeRoots": ["node_modules/@0xproject/typescript-typings/types", "node_modules/@types"], } ``` + +## Contributing + +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. + +Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. + +### Install dependencies + +If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: + +```bash +yarn config set workspaces-experimental true +``` + +Then install dependencies + +```bash +yarn install +``` + +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + +### Lint + +```bash +yarn lint +``` + +### Run Tests + +```bash +yarn test +``` diff --git a/packages/dev-utils/src/globals.d.ts b/packages/dev-utils/src/globals.d.ts index 4fee73568..94e63a32d 100644 --- a/packages/dev-utils/src/globals.d.ts +++ b/packages/dev-utils/src/globals.d.ts @@ -1,5 +1,3 @@ -declare module 'web3-provider-engine/subproviders/rpc'; - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/dev-utils/src/web3_factory.ts b/packages/dev-utils/src/web3_factory.ts index 6435f0f9a..f45c36930 100644 --- a/packages/dev-utils/src/web3_factory.ts +++ b/packages/dev-utils/src/web3_factory.ts @@ -7,6 +7,7 @@ import ProviderEngine = require('web3-provider-engine'); import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); import { EmptyWalletSubprovider, FakeGasEstimateSubprovider, GanacheSubprovider } from '@0xproject/subproviders'; +import { Provider } from '@0xproject/types'; import * as fs from 'fs'; import * as _ from 'lodash'; import * as process from 'process'; @@ -34,7 +35,7 @@ export const web3Factory = { web3.setProvider(provider); return web3; }, - getRpcProvider(config: Web3Config = {}): Web3.Provider { + getRpcProvider(config: Web3Config = {}): Provider { const provider = new ProviderEngine(); const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage); if (isCoverageEnabled) { diff --git a/packages/json-schemas/README.md b/packages/json-schemas/README.md index 980d17416..e8cece63b 100644 --- a/packages/json-schemas/README.md +++ b/packages/json-schemas/README.md @@ -32,11 +32,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -52,16 +52,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/metacoin/test/metacoin_test.ts b/packages/metacoin/test/metacoin_test.ts index f2b396ac2..73537d342 100644 --- a/packages/metacoin/test/metacoin_test.ts +++ b/packages/metacoin/test/metacoin_test.ts @@ -8,7 +8,7 @@ import { MetacoinContract, TransferContractEventArgs } from '../src/contract_wra import { chaiSetup } from './utils/chai_setup'; import { deployer } from './utils/deployer'; -import { web3Wrapper } from './utils/web3_wrapper'; +import { provider, web3Wrapper } from './utils/web3_wrapper'; chaiSetup.configure(); const { expect } = chai; @@ -21,7 +21,7 @@ describe('Metacoin', () => { before(async () => { const metacoinInstance = await deployer.deployAsync('Metacoin'); web3Wrapper.abiDecoder.addABI(metacoinInstance.abi); - metacoin = new MetacoinContract(web3Wrapper, metacoinInstance.abi, metacoinInstance.address); + metacoin = new MetacoinContract(metacoinInstance.abi, metacoinInstance.address, provider); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); diff --git a/packages/metacoin/test/utils/deployer.ts b/packages/metacoin/test/utils/deployer.ts index 7916c8541..5a631fa0a 100644 --- a/packages/metacoin/test/utils/deployer.ts +++ b/packages/metacoin/test/utils/deployer.ts @@ -6,7 +6,7 @@ import { config } from './config'; import { web3Wrapper } from './web3_wrapper'; const deployerOpts = { - web3Provider: web3Wrapper.getProvider(), + provider: web3Wrapper.getProvider(), artifactsDir: config.artifactsDir, networkId: config.networkId, defaults: { diff --git a/packages/metacoin/test/utils/web3_wrapper.ts b/packages/metacoin/test/utils/web3_wrapper.ts index 23bd62b93..b4bb61f09 100644 --- a/packages/metacoin/test/utils/web3_wrapper.ts +++ b/packages/metacoin/test/utils/web3_wrapper.ts @@ -8,12 +8,12 @@ import ProviderEngine = require('web3-provider-engine'); import { config } from './config'; import { coverage } from './coverage'; -export const web3Provider = new ProviderEngine(); +export const provider = new ProviderEngine(); const isCoverageEnabled = env.parseBoolean(EnvVars.SolidityCoverage); if (isCoverageEnabled) { - web3Provider.addProvider(coverage.getCoverageSubproviderSingleton()); + provider.addProvider(coverage.getCoverageSubproviderSingleton()); } -web3Provider.addProvider( +provider.addProvider( new GanacheSubprovider({ logger: { log: (arg: any) => { @@ -25,6 +25,6 @@ web3Provider.addProvider( mnemonic: config.mnemonic, }), ); -web3Provider.start(); +provider.start(); -export const web3Wrapper = new Web3Wrapper(web3Provider); +export const web3Wrapper = new Web3Wrapper(provider); diff --git a/packages/monorepo-scripts/README.md b/packages/monorepo-scripts/README.md index dbdfdf135..a740ba28a 100644 --- a/packages/monorepo-scripts/README.md +++ b/packages/monorepo-scripts/README.md @@ -16,11 +16,11 @@ This will list out any dependencies that differ in versions between packages. ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -36,11 +36,25 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch @@ -57,3 +71,9 @@ yarn clean ```bash yarn lint ``` + +### Run Tests + +```bash +yarn test +``` diff --git a/packages/monorepo-scripts/src/find_unused_dependencies.ts b/packages/monorepo-scripts/src/find_unused_dependencies.ts index 374cba2e3..bfc38044c 100644 --- a/packages/monorepo-scripts/src/find_unused_dependencies.ts +++ b/packages/monorepo-scripts/src/find_unused_dependencies.ts @@ -1,6 +1,6 @@ #!/usr/bin/env node -import * as depcheck from 'depcheck'; +import * as depcheckAsync from 'depcheck'; import * as fs from 'fs'; import lernaGetPackages = require('lerna-get-packages'); import * as _ from 'lodash'; @@ -23,9 +23,9 @@ const IGNORE_PACKAGES = ['@0xproject/deployer']; utils.log(`Checking ${lernaPackage.package.name} for unused deps. This might take a while...`); const configs = {}; - const result = await depcheckAsync(lernaPackage.location, configs); - if (!_.isEmpty(result.dependencies)) { - _.each(result.dependencies, dep => { + const { dependencies } = await depcheckAsync(lernaPackage.location, configs); + if (!_.isEmpty(dependencies)) { + _.each(dependencies, dep => { utils.log(dep); }); } @@ -35,11 +35,3 @@ const IGNORE_PACKAGES = ['@0xproject/deployer']; utils.log(err); process.exit(1); }); - -async function depcheckAsync(path: string, opts: any): Promise<depcheck.Results> { - return new Promise<depcheck.Results>((resolve, reject) => { - depcheck(path, opts, (unused: any) => { - resolve(unused); - }); - }); -} diff --git a/packages/react-docs-example/README.md b/packages/react-docs-example/README.md index 7b2547b20..ff821dba8 100644 --- a/packages/react-docs-example/README.md +++ b/packages/react-docs-example/README.md @@ -20,7 +20,19 @@ Then install dependencies yarn install ``` -#### Start the dev server +### Initial setup + +The **first** time you work with this package, you must build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Note: If you move this package out of the monorepo, it will work without this step. Make sure you copy it out on the `master` branch since the `development` version might rely on not-yet published changes to other packages. + +### Run dev server + +The the `react-docs-example` root directory, run: ```bash yarn dev @@ -42,6 +54,12 @@ yarn deploy_example yarn build ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/react-docs/README.md b/packages/react-docs/README.md index 9be370f10..5a46b84f0 100644 --- a/packages/react-docs/README.md +++ b/packages/react-docs/README.md @@ -51,11 +51,11 @@ Feel free to contribute to these improvements! ## Contributing -We strongly encourage the community to help us make improvements. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -71,10 +71,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/react-docs/src/globals.d.ts b/packages/react-docs/src/globals.d.ts index c7cd53854..94e63a32d 100644 --- a/packages/react-docs/src/globals.d.ts +++ b/packages/react-docs/src/globals.d.ts @@ -1,11 +1,3 @@ -declare module 'react-tooltip'; - -// compare-version declarations -declare function compareVersions(firstVersion: string, secondVersion: string): number; -declare module 'compare-versions' { - export = compareVersions; -} - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/react-shared/README.md b/packages/react-shared/README.md index 9165cf78d..0b4188180 100644 --- a/packages/react-shared/README.md +++ b/packages/react-shared/README.md @@ -18,11 +18,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -38,18 +38,38 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -### Lint +or continuously rebuild on change: ```bash -yarn lint +yarn build:watch +``` + +### Clean + +```bash +yarn clean ``` -### Run Tests +### Lint ```bash -yarn test +yarn lint ``` diff --git a/packages/react-shared/src/globals.d.ts b/packages/react-shared/src/globals.d.ts index 525563e23..94e63a32d 100644 --- a/packages/react-shared/src/globals.d.ts +++ b/packages/react-shared/src/globals.d.ts @@ -1,11 +1,3 @@ -declare module 'react-highlight'; - -// is-mobile declarations -declare function isMobile(): boolean; -declare module 'is-mobile' { - export = isMobile; -} - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/sol-cov/README.md b/packages/sol-cov/README.md index 5591b9731..8cc7dca6c 100644 --- a/packages/sol-cov/README.md +++ b/packages/sol-cov/README.md @@ -24,11 +24,11 @@ var CoverageSubprovider = require('@0xproject/sol-cov').CoverageSubprovider; ## Contributing -We strongly encourage the community to help us make improvements. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -42,8 +42,46 @@ Then install dependencies yarn install ``` +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash yarn lint ``` + +### Run Tests + +```bash +yarn test +``` diff --git a/packages/sol-cov/src/globals.d.ts b/packages/sol-cov/src/globals.d.ts index 368e908b4..e799b3529 100644 --- a/packages/sol-cov/src/globals.d.ts +++ b/packages/sol-cov/src/globals.d.ts @@ -5,318 +5,3 @@ declare module '*.json' { export default json; /* tslint:enable */ } - -declare module 'solidity-parser-antlr' { - export interface BaseASTNode { - range: [number, number]; - } - export interface SourceUnit extends BaseASTNode {} - export interface PragmaDirective extends BaseASTNode {} - export interface PragmaName extends BaseASTNode {} - export interface PragmaValue extends BaseASTNode {} - export interface Version extends BaseASTNode {} - export interface VersionOperator extends BaseASTNode {} - export interface VersionConstraint extends BaseASTNode {} - export interface ImportDeclaration extends BaseASTNode {} - export interface ImportDirective extends BaseASTNode {} - export interface ContractDefinition extends BaseASTNode {} - export interface InheritanceSpecifier extends BaseASTNode {} - export interface ContractPart extends BaseASTNode {} - export interface StateVariableDeclaration extends BaseASTNode { - variables: VariableDeclaration[]; - } - export interface UsingForDeclaration extends BaseASTNode {} - export interface StructDefinition extends BaseASTNode {} - export interface ModifierDefinition extends BaseASTNode { - name: string; - } - export interface ModifierInvocation extends BaseASTNode { - name: string; - } - export interface FunctionDefinition extends BaseASTNode { - name: string; - } - export interface ReturnParameters extends BaseASTNode {} - export interface ModifierList extends BaseASTNode {} - export interface EventDefinition extends BaseASTNode {} - export interface EnumValue extends BaseASTNode {} - export interface EnumDefinition extends BaseASTNode {} - export interface ParameterList extends BaseASTNode {} - export interface Parameter extends BaseASTNode {} - export interface EventParameterList extends BaseASTNode {} - export interface EventParameter extends BaseASTNode {} - export interface FunctionTypeParameterList extends BaseASTNode {} - export interface FunctionTypeParameter extends BaseASTNode {} - export interface VariableDeclaration extends BaseASTNode { - visibility: 'public' | 'private'; - isStateVar: boolean; - } - export interface TypeName extends BaseASTNode {} - export interface UserDefinedTypeName extends BaseASTNode {} - export interface Mapping extends BaseASTNode {} - export interface FunctionTypeName extends BaseASTNode {} - export interface StorageLocation extends BaseASTNode {} - export interface StateMutability extends BaseASTNode {} - export interface Block extends BaseASTNode {} - export interface Statement extends BaseASTNode {} - export interface ExpressionStatement extends BaseASTNode { - expression: ASTNode; - } - export interface IfStatement extends BaseASTNode { - trueBody: ASTNode; - falseBody: ASTNode; - } - export interface WhileStatement extends BaseASTNode {} - export interface SimpleStatement extends BaseASTNode {} - export interface ForStatement extends BaseASTNode {} - export interface InlineAssemblyStatement extends BaseASTNode {} - export interface DoWhileStatement extends BaseASTNode {} - export interface ContinueStatement extends BaseASTNode {} - export interface BreakStatement extends BaseASTNode {} - export interface ReturnStatement extends BaseASTNode {} - export interface ThrowStatement extends BaseASTNode {} - export interface VariableDeclarationStatement extends BaseASTNode {} - export interface IdentifierList extends BaseASTNode {} - export interface ElementaryTypeName extends BaseASTNode {} - export interface Expression extends BaseASTNode {} - export interface PrimaryExpression extends BaseASTNode {} - export interface ExpressionList extends BaseASTNode {} - export interface NameValueList extends BaseASTNode {} - export interface NameValue extends BaseASTNode {} - export interface FunctionCallArguments extends BaseASTNode {} - export interface AssemblyBlock extends BaseASTNode {} - export interface AssemblyItem extends BaseASTNode {} - export interface AssemblyExpression extends BaseASTNode {} - export interface AssemblyCall extends BaseASTNode {} - export interface AssemblyLocalDefinition extends BaseASTNode {} - export interface AssemblyAssignment extends BaseASTNode {} - export interface AssemblyIdentifierOrList extends BaseASTNode {} - export interface AssemblyIdentifierList extends BaseASTNode {} - export interface AssemblyStackAssignment extends BaseASTNode {} - export interface LabelDefinition extends BaseASTNode {} - export interface AssemblySwitch extends BaseASTNode {} - export interface AssemblyCase extends BaseASTNode {} - export interface AssemblyFunctionDefinition extends BaseASTNode {} - export interface AssemblyFunctionReturns extends BaseASTNode {} - export interface AssemblyFor extends BaseASTNode {} - export interface AssemblyIf extends BaseASTNode {} - export interface AssemblyLiteral extends BaseASTNode {} - export interface SubAssembly extends BaseASTNode {} - export interface TupleExpression extends BaseASTNode {} - export interface ElementaryTypeNameExpression extends BaseASTNode {} - export interface NumberLiteral extends BaseASTNode {} - export interface Identifier extends BaseASTNode {} - export type BinOp = - | '+' - | '-' - | '*' - | '/' - | '**' - | '%' - | '<<' - | '>>' - | '&&' - | '||' - | '&' - | '|' - | '^' - | '<' - | '>' - | '<=' - | '>=' - | '==' - | '!=' - | '=' - | '|=' - | '^=' - | '&=' - | '<<=' - | '>>=' - | '+=' - | '-=' - | '*=' - | '/=' - | '%='; - export interface BinaryOperation extends BaseASTNode { - left: ASTNode; - right: ASTNode; - operator: BinOp; - } - export interface Conditional extends BaseASTNode { - trueExpression: ASTNode; - falseExpression: ASTNode; - } - - export type ASTNode = - | SourceUnit - | PragmaDirective - | PragmaName - | PragmaValue - | Version - | VersionOperator - | VersionConstraint - | ImportDeclaration - | ImportDirective - | ContractDefinition - | InheritanceSpecifier - | ContractPart - | StateVariableDeclaration - | UsingForDeclaration - | StructDefinition - | ModifierDefinition - | ModifierInvocation - | FunctionDefinition - | ReturnParameters - | ModifierList - | EventDefinition - | EnumValue - | EnumDefinition - | ParameterList - | Parameter - | EventParameterList - | EventParameter - | FunctionTypeParameterList - | FunctionTypeParameter - | VariableDeclaration - | TypeName - | UserDefinedTypeName - | Mapping - | FunctionTypeName - | StorageLocation - | StateMutability - | Block - | Statement - | ExpressionStatement - | IfStatement - | WhileStatement - | SimpleStatement - | ForStatement - | InlineAssemblyStatement - | DoWhileStatement - | ContinueStatement - | BreakStatement - | ReturnStatement - | ThrowStatement - | VariableDeclarationStatement - | IdentifierList - | ElementaryTypeName - | Expression - | PrimaryExpression - | ExpressionList - | NameValueList - | NameValue - | FunctionCallArguments - | AssemblyBlock - | AssemblyItem - | AssemblyExpression - | AssemblyCall - | AssemblyLocalDefinition - | AssemblyAssignment - | AssemblyIdentifierOrList - | AssemblyIdentifierList - | AssemblyStackAssignment - | LabelDefinition - | AssemblySwitch - | AssemblyCase - | AssemblyFunctionDefinition - | AssemblyFunctionReturns - | AssemblyFor - | AssemblyIf - | AssemblyLiteral - | SubAssembly - | TupleExpression - | ElementaryTypeNameExpression - | NumberLiteral - | Identifier - | BinaryOperation - | Conditional; - export interface Visitor { - SourceUnit?: (node: SourceUnit) => void; - PragmaDirective?: (node: PragmaDirective) => void; - PragmaName?: (node: PragmaName) => void; - PragmaValue?: (node: PragmaValue) => void; - Version?: (node: Version) => void; - VersionOperator?: (node: VersionOperator) => void; - VersionConstraint?: (node: VersionConstraint) => void; - ImportDeclaration?: (node: ImportDeclaration) => void; - ImportDirective?: (node: ImportDirective) => void; - ContractDefinition?: (node: ContractDefinition) => void; - InheritanceSpecifier?: (node: InheritanceSpecifier) => void; - ContractPart?: (node: ContractPart) => void; - StateVariableDeclaration?: (node: StateVariableDeclaration) => void; - UsingForDeclaration?: (node: UsingForDeclaration) => void; - StructDefinition?: (node: StructDefinition) => void; - ModifierDefinition?: (node: ModifierDefinition) => void; - ModifierInvocation?: (node: ModifierInvocation) => void; - FunctionDefinition?: (node: FunctionDefinition) => void; - ReturnParameters?: (node: ReturnParameters) => void; - ModifierList?: (node: ModifierList) => void; - EventDefinition?: (node: EventDefinition) => void; - EnumValue?: (node: EnumValue) => void; - EnumDefinition?: (node: EnumDefinition) => void; - ParameterList?: (node: ParameterList) => void; - Parameter?: (node: Parameter) => void; - EventParameterList?: (node: EventParameterList) => void; - EventParameter?: (node: EventParameter) => void; - FunctionTypeParameterList?: (node: FunctionTypeParameterList) => void; - FunctionTypeParameter?: (node: FunctionTypeParameter) => void; - VariableDeclaration?: (node: VariableDeclaration) => void; - TypeName?: (node: TypeName) => void; - UserDefinedTypeName?: (node: UserDefinedTypeName) => void; - Mapping?: (node: Mapping) => void; - FunctionTypeName?: (node: FunctionTypeName) => void; - StorageLocation?: (node: StorageLocation) => void; - StateMutability?: (node: StateMutability) => void; - Block?: (node: Block) => void; - Statement?: (node: Statement) => void; - ExpressionStatement?: (node: ExpressionStatement) => void; - IfStatement?: (node: IfStatement) => void; - WhileStatement?: (node: WhileStatement) => void; - SimpleStatement?: (node: SimpleStatement) => void; - ForStatement?: (node: ForStatement) => void; - InlineAssemblyStatement?: (node: InlineAssemblyStatement) => void; - DoWhileStatement?: (node: DoWhileStatement) => void; - ContinueStatement?: (node: ContinueStatement) => void; - BreakStatement?: (node: BreakStatement) => void; - ReturnStatement?: (node: ReturnStatement) => void; - ThrowStatement?: (node: ThrowStatement) => void; - VariableDeclarationStatement?: (node: VariableDeclarationStatement) => void; - IdentifierList?: (node: IdentifierList) => void; - ElementaryTypeName?: (node: ElementaryTypeName) => void; - Expression?: (node: Expression) => void; - PrimaryExpression?: (node: PrimaryExpression) => void; - ExpressionList?: (node: ExpressionList) => void; - NameValueList?: (node: NameValueList) => void; - NameValue?: (node: NameValue) => void; - FunctionCallArguments?: (node: FunctionCallArguments) => void; - AssemblyBlock?: (node: AssemblyBlock) => void; - AssemblyItem?: (node: AssemblyItem) => void; - AssemblyExpression?: (node: AssemblyExpression) => void; - AssemblyCall?: (node: AssemblyCall) => void; - AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => void; - AssemblyAssignment?: (node: AssemblyAssignment) => void; - AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => void; - AssemblyIdentifierList?: (node: AssemblyIdentifierList) => void; - AssemblyStackAssignment?: (node: AssemblyStackAssignment) => void; - LabelDefinition?: (node: LabelDefinition) => void; - AssemblySwitch?: (node: AssemblySwitch) => void; - AssemblyCase?: (node: AssemblyCase) => void; - AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => void; - AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => void; - AssemblyFor?: (node: AssemblyFor) => void; - AssemblyIf?: (node: AssemblyIf) => void; - AssemblyLiteral?: (node: AssemblyLiteral) => void; - SubAssembly?: (node: SubAssembly) => void; - TupleExpression?: (node: TupleExpression) => void; - ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => void; - NumberLiteral?: (node: NumberLiteral) => void; - Identifier?: (node: Identifier) => void; - BinaryOperation?: (node: BinaryOperation) => void; - Conditional?: (node: Conditional) => void; - } - export interface ParserOpts { - range?: boolean; - } - export function parse(sourceCode: string, parserOpts: ParserOpts): ASTNode; - export function visit(ast: ASTNode, visitor: Visitor): void; -} diff --git a/packages/sra-report/README.md b/packages/sra-report/README.md index 299d575d8..806ac3bf4 100644 --- a/packages/sra-report/README.md +++ b/packages/sra-report/README.md @@ -87,11 +87,11 @@ In order to provide a custom environment to the tool, perform the following step ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -107,10 +107,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/sra-report/src/globals.d.ts b/packages/sra-report/src/globals.d.ts index 03b3205c0..783b92913 100644 --- a/packages/sra-report/src/globals.d.ts +++ b/packages/sra-report/src/globals.d.ts @@ -1,28 +1,3 @@ -declare module 'newman' { - export interface NewmanRunSummary { - run: NewmanRun; - } - export interface NewmanRun { - executions: NewmanRunExecution[]; - } - export interface NewmanRunExecution { - item: NewmanRunExecutionItem; - assertions: NewmanRunExecutionAssertion[]; - } - export interface NewmanRunExecutionItem { - name: string; - } - export interface NewmanRunExecutionAssertion { - assertion: string; - error: NewmanRunExecutionAssertionError; - } - export interface NewmanRunExecutionAssertionError { - message: string; - } - // tslint:disable-next-line:completed-docs - export function run(options: any, callback?: (err: Error | null, summary: NewmanRunSummary) => void): void; -} - declare module '*.json' { const value: any; export default value; diff --git a/packages/subproviders/README.md b/packages/subproviders/README.md index ac92b89d2..2936be545 100644 --- a/packages/subproviders/README.md +++ b/packages/subproviders/README.md @@ -22,11 +22,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -34,17 +34,33 @@ If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: yarn config set workspaces-experimental true ``` +Then install dependencies + ```bash yarn install ``` ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch diff --git a/packages/subproviders/src/globals.d.ts b/packages/subproviders/src/globals.d.ts index 580c5aaa5..c5ad26876 100644 --- a/packages/subproviders/src/globals.d.ts +++ b/packages/subproviders/src/globals.d.ts @@ -51,42 +51,6 @@ declare module '@ledgerhq/hw-transport-node-hid' { } } -// web3-provider-engine declarations -declare module 'web3-provider-engine/subproviders/subprovider' { - class Subprovider {} - export = Subprovider; -} -declare module 'web3-provider-engine/subproviders/rpc' { - import { JSONRPCRequestPayload } from '@0xproject/types'; - class RpcSubprovider { - constructor(options: { rpcUrl: string }); - public handleRequest( - payload: JSONRPCRequestPayload, - next: () => void, - end: (err: Error | null, data?: any) => void, - ): void; - } - export = RpcSubprovider; -} -declare module 'web3-provider-engine/util/rpc-cache-utils' { - class ProviderEngineRpcUtils { - public static blockTagForPayload(payload: any): string | null; - } - export = ProviderEngineRpcUtils; -} -declare module 'web3-provider-engine/subproviders/fixture' { - import { JSONRPCRequestPayload } from '@0xproject/types'; - class FixtureSubprovider { - constructor(staticResponses: any); - public handleRequest( - payload: JSONRPCRequestPayload, - next: () => void, - end: (err: Error | null, data?: any) => void, - ): void; - } - export = FixtureSubprovider; -} - // hdkey declarations declare module 'hdkey' { class HDNode { @@ -104,19 +68,3 @@ declare module '*.json' { export default json; /* tslint:enable */ } - -// ganache-core declarations -declare module 'ganache-core' { - import * as Web3 from 'web3'; - export interface GanacheOpts { - verbose: boolean; - logger: { - log(msg: string): void; - }; - port: number; - networkId: number; - mnemonic: string; - } - // tslint:disable-next-line:completed-docs - export function provider(opts: GanacheOpts): Web3.Provider; -} diff --git a/packages/subproviders/src/subproviders/ganache.ts b/packages/subproviders/src/subproviders/ganache.ts index 785de792d..8008d1b4b 100644 --- a/packages/subproviders/src/subproviders/ganache.ts +++ b/packages/subproviders/src/subproviders/ganache.ts @@ -1,6 +1,5 @@ -import { JSONRPCRequestPayload } from '@0xproject/types'; +import { JSONRPCRequestPayload, Provider } from '@0xproject/types'; import * as Ganache from 'ganache-core'; -import * as Web3 from 'web3'; import { Callback, ErrorCallback } from '../types'; @@ -11,7 +10,7 @@ import { Subprovider } from './subprovider'; * It intercepts all JSON RPC requests and relays them to an in-process ganache instance. */ export class GanacheSubprovider extends Subprovider { - private _ganacheProvider: Web3.Provider; + private _ganacheProvider: Provider; /** * Instantiates a GanacheSubprovider * @param opts The desired opts with which to instantiate the Ganache provider diff --git a/packages/subproviders/src/subproviders/injected_web3.ts b/packages/subproviders/src/subproviders/injected_web3.ts index edecd8bf6..1d7b2ddfe 100644 --- a/packages/subproviders/src/subproviders/injected_web3.ts +++ b/packages/subproviders/src/subproviders/injected_web3.ts @@ -1,4 +1,4 @@ -import { JSONRPCRequestPayload } from '@0xproject/types'; +import { JSONRPCRequestPayload, Provider } from '@0xproject/types'; import * as _ from 'lodash'; import * as Web3 from 'web3'; @@ -18,7 +18,7 @@ export class InjectedWeb3Subprovider extends Subprovider { * Instantiates a new InjectedWeb3Subprovider * @param provider Web3 provider that should handle all user account related requests */ - constructor(provider: Web3.Provider) { + constructor(provider: Provider) { super(); this._injectedWeb3 = new Web3(provider); } diff --git a/packages/testnet-faucets/README.md b/packages/testnet-faucets/README.md index 2f6ae347f..93f97e1b7 100644 --- a/packages/testnet-faucets/README.md +++ b/packages/testnet-faucets/README.md @@ -4,15 +4,15 @@ This faucet dispenses 0.1 test ether to one recipient per second and 0.1 test ZR ## Installation -This is a private package and therefore is not published to npm. In order to build and run this package locally, see the [Install Dependencies](#Install-Dependencies) section and onwards below. +This is a private package and therefore is not published to npm. In order to build and run this package locally, see the contributing instructions below. ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -26,6 +26,44 @@ Then install dependencies yarn install ``` +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + +### Lint + +```bash +yarn lint +``` + ### Start Set the following environment variables: @@ -125,9 +163,3 @@ docker run -d \ -e INFURA_API_KEY=$INFURA_API_KEY \ testnet-faucets ``` - -### Lint - -```bash -yarn lint -``` diff --git a/packages/testnet-faucets/src/ts/global.d.ts b/packages/testnet-faucets/src/ts/global.d.ts index 65e9fb632..94e63a32d 100644 --- a/packages/testnet-faucets/src/ts/global.d.ts +++ b/packages/testnet-faucets/src/ts/global.d.ts @@ -1,8 +1,3 @@ -declare module 'rollbar'; -declare module 'web3-provider-engine/subproviders/rpc'; -declare module 'web3-provider-engine/subproviders/nonce-tracker'; -declare module 'web3-provider-engine/subproviders/hooked-wallet'; - declare module '*.json' { const json: any; /* tslint:disable */ diff --git a/packages/tslint-config/README.md b/packages/tslint-config/README.md index b517f2d95..d90b3cf73 100644 --- a/packages/tslint-config/README.md +++ b/packages/tslint-config/README.md @@ -20,11 +20,11 @@ Add the following to your `tslint.json` file ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -40,16 +40,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/types/CHANGELOG.json b/packages/types/CHANGELOG.json index f207b7293..2e4c5f091 100644 --- a/packages/types/CHANGELOG.json +++ b/packages/types/CHANGELOG.json @@ -1,5 +1,14 @@ [ { + "version": "0.6.0", + "changes": [ + { + "note": "Add Provider type", + "pr": 501 + } + ] + }, + { "version": "0.5.0", "changes": [ { diff --git a/packages/types/README.md b/packages/types/README.md index b971eaee7..665701ea4 100644 --- a/packages/types/README.md +++ b/packages/types/README.md @@ -24,13 +24,13 @@ import { TransactionReceipt, TxData, TxDataPayable } from '@0xproject/types'; ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies -If you don't have yarn workspaces e`nabled (Yarn < v1.0) - enable them: +If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: ```bash yarn config set workspaces-experimental true @@ -44,16 +44,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 419611695..442fbb2d6 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -1,5 +1,9 @@ import { BigNumber } from 'bignumber.js'; +export interface Provider { + sendAsync(payload: JSONRPCRequestPayload, callback: (err: Error, result: JSONRPCResponsePayload) => void): void; +} + export type ContractAbi = AbiDefinition[]; export type AbiDefinition = FunctionAbi | EventAbi; diff --git a/packages/typescript-typings/CHANGELOG.json b/packages/typescript-typings/CHANGELOG.json index 22ad5f1ad..294d9ee9f 100644 --- a/packages/typescript-typings/CHANGELOG.json +++ b/packages/typescript-typings/CHANGELOG.json @@ -1,5 +1,14 @@ [ { + "version": "0.1.0", + "changes": [ + { + "note": "Add types for more packages", + "pr": 501 + } + ] + }, + { "timestamp": 1522673609, "version": "0.0.3", "changes": [ diff --git a/packages/typescript-typings/README.md b/packages/typescript-typings/README.md index 9a74739f3..968b2e87c 100644 --- a/packages/typescript-typings/README.md +++ b/packages/typescript-typings/README.md @@ -20,11 +20,11 @@ This will allow the TS compiler to first look into that repo and then fallback t ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -38,6 +38,38 @@ Then install dependencies yarn install ``` +### Build + +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + +```bash +yarn build +``` + +or continuously rebuild on change: + +```bash +yarn build:watch +``` + +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/typescript-typings/types/async-child-process/index.d.ts b/packages/typescript-typings/types/async-child-process/index.d.ts new file mode 100644 index 000000000..f8ed46378 --- /dev/null +++ b/packages/typescript-typings/types/async-child-process/index.d.ts @@ -0,0 +1 @@ +declare module 'async-child-process'; diff --git a/packages/typescript-typings/types/blockies/index.d.ts b/packages/typescript-typings/types/blockies/index.d.ts new file mode 100644 index 000000000..d4068e50f --- /dev/null +++ b/packages/typescript-typings/types/blockies/index.d.ts @@ -0,0 +1,11 @@ +// blockies declarations +declare interface BlockiesIcon { + toDataURL(): string; +} +declare interface BlockiesConfig { + seed: string; +} +declare function blockies(config: BlockiesConfig): BlockiesIcon; +declare module 'blockies' { + export = blockies; +} diff --git a/packages/typescript-typings/types/compare-versions/index.d.ts b/packages/typescript-typings/types/compare-versions/index.d.ts new file mode 100644 index 000000000..b19e1f94b --- /dev/null +++ b/packages/typescript-typings/types/compare-versions/index.d.ts @@ -0,0 +1,5 @@ +// compare-version declarations +declare function compareVersions(firstVersion: string, secondVersion: string): number; +declare module 'compare-versions' { + export = compareVersions; +} diff --git a/packages/typescript-typings/types/es6-promisify/index.d.ts b/packages/typescript-typings/types/es6-promisify/index.d.ts new file mode 100644 index 000000000..f9c202fb0 --- /dev/null +++ b/packages/typescript-typings/types/es6-promisify/index.d.ts @@ -0,0 +1 @@ +declare module 'es6-promisify'; diff --git a/packages/typescript-typings/types/find-versions/index.d.ts b/packages/typescript-typings/types/find-versions/index.d.ts new file mode 100644 index 000000000..e7c1c6461 --- /dev/null +++ b/packages/typescript-typings/types/find-versions/index.d.ts @@ -0,0 +1,4 @@ +declare function findVersions(version: string): string[]; +declare module 'find-versions' { + export = findVersions; +} diff --git a/packages/typescript-typings/types/ganache-core/index.d.ts b/packages/typescript-typings/types/ganache-core/index.d.ts new file mode 100644 index 000000000..feeb5721e --- /dev/null +++ b/packages/typescript-typings/types/ganache-core/index.d.ts @@ -0,0 +1,14 @@ +declare module 'ganache-core' { + import { Provider } from '@0xproject/types'; + export interface GanacheOpts { + verbose?: boolean; + logger?: { + log(msg: string): void; + }; + port?: number; + network_id?: number; + mnemonic?: string; + } + // tslint:disable-next-line:completed-docs + export function provider(opts: GanacheOpts): Provider; +} diff --git a/packages/typescript-typings/types/is-mobile/index.d.ts b/packages/typescript-typings/types/is-mobile/index.d.ts new file mode 100644 index 000000000..0b3b57854 --- /dev/null +++ b/packages/typescript-typings/types/is-mobile/index.d.ts @@ -0,0 +1,4 @@ +declare function isMobile(): boolean; +declare module 'is-mobile' { + export = isMobile; +} diff --git a/packages/typescript-typings/types/keccak/index.d.ts b/packages/typescript-typings/types/keccak/index.d.ts new file mode 100644 index 000000000..0465f8faf --- /dev/null +++ b/packages/typescript-typings/types/keccak/index.d.ts @@ -0,0 +1 @@ +declare module 'keccak'; diff --git a/packages/typescript-typings/types/lerna-get-packages/index.d.ts b/packages/typescript-typings/types/lerna-get-packages/index.d.ts new file mode 100644 index 000000000..0650a542c --- /dev/null +++ b/packages/typescript-typings/types/lerna-get-packages/index.d.ts @@ -0,0 +1,16 @@ +declare interface LernaPackage { + location: string; + package: { + private?: boolean; + version: string; + name: string; + main?: string; + config?: { + additionalTsTypings?: string[]; + }; + }; +} +declare function lernaGetPackages(path: string): LernaPackage[]; +declare module 'lerna-get-packages' { + export = lernaGetPackages; +} diff --git a/packages/typescript-typings/types/newman/index.d.ts b/packages/typescript-typings/types/newman/index.d.ts new file mode 100644 index 000000000..bea9ac160 --- /dev/null +++ b/packages/typescript-typings/types/newman/index.d.ts @@ -0,0 +1,24 @@ +declare module 'newman' { + export interface NewmanRunSummary { + run: NewmanRun; + } + export interface NewmanRun { + executions: NewmanRunExecution[]; + } + export interface NewmanRunExecution { + item: NewmanRunExecutionItem; + assertions: NewmanRunExecutionAssertion[]; + } + export interface NewmanRunExecutionItem { + name: string; + } + export interface NewmanRunExecutionAssertion { + assertion: string; + error: NewmanRunExecutionAssertionError; + } + export interface NewmanRunExecutionAssertionError { + message: string; + } + // tslint:disable-next-line:completed-docs + export function run(options: any, callback?: (err: Error | null, summary: NewmanRunSummary) => void): void; +} diff --git a/packages/typescript-typings/types/promisify-child-process/index.d.ts b/packages/typescript-typings/types/promisify-child-process/index.d.ts new file mode 100644 index 000000000..55c041735 --- /dev/null +++ b/packages/typescript-typings/types/promisify-child-process/index.d.ts @@ -0,0 +1 @@ +declare module 'promisify-child-process'; diff --git a/packages/typescript-typings/types/publish-release/index.d.ts b/packages/typescript-typings/types/publish-release/index.d.ts new file mode 100644 index 000000000..680cc45c9 --- /dev/null +++ b/packages/typescript-typings/types/publish-release/index.d.ts @@ -0,0 +1 @@ +declare module 'publish-release'; diff --git a/packages/typescript-typings/types/react-highlight/index.d.ts b/packages/typescript-typings/types/react-highlight/index.d.ts new file mode 100644 index 000000000..875721533 --- /dev/null +++ b/packages/typescript-typings/types/react-highlight/index.d.ts @@ -0,0 +1 @@ +declare module 'react-highlight'; diff --git a/packages/typescript-typings/types/react-tooltip/index.d.ts b/packages/typescript-typings/types/react-tooltip/index.d.ts new file mode 100644 index 000000000..98cb6d592 --- /dev/null +++ b/packages/typescript-typings/types/react-tooltip/index.d.ts @@ -0,0 +1 @@ +declare module 'react-tooltip'; diff --git a/packages/typescript-typings/types/request-promise-native/index.d.ts b/packages/typescript-typings/types/request-promise-native/index.d.ts new file mode 100644 index 000000000..a86e99624 --- /dev/null +++ b/packages/typescript-typings/types/request-promise-native/index.d.ts @@ -0,0 +1 @@ +declare module 'request-promise-native'; diff --git a/packages/typescript-typings/types/rollbar/index.d.ts b/packages/typescript-typings/types/rollbar/index.d.ts new file mode 100644 index 000000000..c9bec447d --- /dev/null +++ b/packages/typescript-typings/types/rollbar/index.d.ts @@ -0,0 +1 @@ +declare module 'rollbar'; diff --git a/packages/typescript-typings/types/semver-diff/index.d.ts b/packages/typescript-typings/types/semver-diff/index.d.ts new file mode 100644 index 000000000..e4a14eeb2 --- /dev/null +++ b/packages/typescript-typings/types/semver-diff/index.d.ts @@ -0,0 +1 @@ +declare module 'semver-diff'; diff --git a/packages/typescript-typings/types/semver-sort/index.d.ts b/packages/typescript-typings/types/semver-sort/index.d.ts new file mode 100644 index 000000000..47310756a --- /dev/null +++ b/packages/typescript-typings/types/semver-sort/index.d.ts @@ -0,0 +1,3 @@ +declare module 'semver-sort' { + const desc: (versions: string[]) => string[]; +} diff --git a/packages/typescript-typings/types/solidity-parser-antlr/index.d.ts b/packages/typescript-typings/types/solidity-parser-antlr/index.d.ts new file mode 100644 index 000000000..cc1246a0e --- /dev/null +++ b/packages/typescript-typings/types/solidity-parser-antlr/index.d.ts @@ -0,0 +1,314 @@ +declare module 'solidity-parser-antlr' { + export interface BaseASTNode { + range: [number, number]; + } + export interface SourceUnit extends BaseASTNode {} + export interface PragmaDirective extends BaseASTNode {} + export interface PragmaName extends BaseASTNode {} + export interface PragmaValue extends BaseASTNode {} + export interface Version extends BaseASTNode {} + export interface VersionOperator extends BaseASTNode {} + export interface VersionConstraint extends BaseASTNode {} + export interface ImportDeclaration extends BaseASTNode {} + export interface ImportDirective extends BaseASTNode {} + export interface ContractDefinition extends BaseASTNode {} + export interface InheritanceSpecifier extends BaseASTNode {} + export interface ContractPart extends BaseASTNode {} + export interface StateVariableDeclaration extends BaseASTNode { + variables: VariableDeclaration[]; + } + export interface UsingForDeclaration extends BaseASTNode {} + export interface StructDefinition extends BaseASTNode {} + export interface ModifierDefinition extends BaseASTNode { + name: string; + } + export interface ModifierInvocation extends BaseASTNode { + name: string; + } + export interface FunctionDefinition extends BaseASTNode { + name: string; + } + export interface ReturnParameters extends BaseASTNode {} + export interface ModifierList extends BaseASTNode {} + export interface EventDefinition extends BaseASTNode {} + export interface EnumValue extends BaseASTNode {} + export interface EnumDefinition extends BaseASTNode {} + export interface ParameterList extends BaseASTNode {} + export interface Parameter extends BaseASTNode {} + export interface EventParameterList extends BaseASTNode {} + export interface EventParameter extends BaseASTNode {} + export interface FunctionTypeParameterList extends BaseASTNode {} + export interface FunctionTypeParameter extends BaseASTNode {} + export interface VariableDeclaration extends BaseASTNode { + visibility: 'public' | 'private'; + isStateVar: boolean; + } + export interface TypeName extends BaseASTNode {} + export interface UserDefinedTypeName extends BaseASTNode {} + export interface Mapping extends BaseASTNode {} + export interface FunctionTypeName extends BaseASTNode {} + export interface StorageLocation extends BaseASTNode {} + export interface StateMutability extends BaseASTNode {} + export interface Block extends BaseASTNode {} + export interface Statement extends BaseASTNode {} + export interface ExpressionStatement extends BaseASTNode { + expression: ASTNode; + } + export interface IfStatement extends BaseASTNode { + trueBody: ASTNode; + falseBody: ASTNode; + } + export interface WhileStatement extends BaseASTNode {} + export interface SimpleStatement extends BaseASTNode {} + export interface ForStatement extends BaseASTNode {} + export interface InlineAssemblyStatement extends BaseASTNode {} + export interface DoWhileStatement extends BaseASTNode {} + export interface ContinueStatement extends BaseASTNode {} + export interface BreakStatement extends BaseASTNode {} + export interface ReturnStatement extends BaseASTNode {} + export interface ThrowStatement extends BaseASTNode {} + export interface VariableDeclarationStatement extends BaseASTNode {} + export interface IdentifierList extends BaseASTNode {} + export interface ElementaryTypeName extends BaseASTNode {} + export interface Expression extends BaseASTNode {} + export interface PrimaryExpression extends BaseASTNode {} + export interface ExpressionList extends BaseASTNode {} + export interface NameValueList extends BaseASTNode {} + export interface NameValue extends BaseASTNode {} + export interface FunctionCallArguments extends BaseASTNode {} + export interface AssemblyBlock extends BaseASTNode {} + export interface AssemblyItem extends BaseASTNode {} + export interface AssemblyExpression extends BaseASTNode {} + export interface AssemblyCall extends BaseASTNode {} + export interface AssemblyLocalDefinition extends BaseASTNode {} + export interface AssemblyAssignment extends BaseASTNode {} + export interface AssemblyIdentifierOrList extends BaseASTNode {} + export interface AssemblyIdentifierList extends BaseASTNode {} + export interface AssemblyStackAssignment extends BaseASTNode {} + export interface LabelDefinition extends BaseASTNode {} + export interface AssemblySwitch extends BaseASTNode {} + export interface AssemblyCase extends BaseASTNode {} + export interface AssemblyFunctionDefinition extends BaseASTNode {} + export interface AssemblyFunctionReturns extends BaseASTNode {} + export interface AssemblyFor extends BaseASTNode {} + export interface AssemblyIf extends BaseASTNode {} + export interface AssemblyLiteral extends BaseASTNode {} + export interface SubAssembly extends BaseASTNode {} + export interface TupleExpression extends BaseASTNode {} + export interface ElementaryTypeNameExpression extends BaseASTNode {} + export interface NumberLiteral extends BaseASTNode {} + export interface Identifier extends BaseASTNode {} + export type BinOp = + | '+' + | '-' + | '*' + | '/' + | '**' + | '%' + | '<<' + | '>>' + | '&&' + | '||' + | '&' + | '|' + | '^' + | '<' + | '>' + | '<=' + | '>=' + | '==' + | '!=' + | '=' + | '|=' + | '^=' + | '&=' + | '<<=' + | '>>=' + | '+=' + | '-=' + | '*=' + | '/=' + | '%='; + export interface BinaryOperation extends BaseASTNode { + left: ASTNode; + right: ASTNode; + operator: BinOp; + } + export interface Conditional extends BaseASTNode { + trueExpression: ASTNode; + falseExpression: ASTNode; + } + + export type ASTNode = + | SourceUnit + | PragmaDirective + | PragmaName + | PragmaValue + | Version + | VersionOperator + | VersionConstraint + | ImportDeclaration + | ImportDirective + | ContractDefinition + | InheritanceSpecifier + | ContractPart + | StateVariableDeclaration + | UsingForDeclaration + | StructDefinition + | ModifierDefinition + | ModifierInvocation + | FunctionDefinition + | ReturnParameters + | ModifierList + | EventDefinition + | EnumValue + | EnumDefinition + | ParameterList + | Parameter + | EventParameterList + | EventParameter + | FunctionTypeParameterList + | FunctionTypeParameter + | VariableDeclaration + | TypeName + | UserDefinedTypeName + | Mapping + | FunctionTypeName + | StorageLocation + | StateMutability + | Block + | Statement + | ExpressionStatement + | IfStatement + | WhileStatement + | SimpleStatement + | ForStatement + | InlineAssemblyStatement + | DoWhileStatement + | ContinueStatement + | BreakStatement + | ReturnStatement + | ThrowStatement + | VariableDeclarationStatement + | IdentifierList + | ElementaryTypeName + | Expression + | PrimaryExpression + | ExpressionList + | NameValueList + | NameValue + | FunctionCallArguments + | AssemblyBlock + | AssemblyItem + | AssemblyExpression + | AssemblyCall + | AssemblyLocalDefinition + | AssemblyAssignment + | AssemblyIdentifierOrList + | AssemblyIdentifierList + | AssemblyStackAssignment + | LabelDefinition + | AssemblySwitch + | AssemblyCase + | AssemblyFunctionDefinition + | AssemblyFunctionReturns + | AssemblyFor + | AssemblyIf + | AssemblyLiteral + | SubAssembly + | TupleExpression + | ElementaryTypeNameExpression + | NumberLiteral + | Identifier + | BinaryOperation + | Conditional; + export interface Visitor { + SourceUnit?: (node: SourceUnit) => void; + PragmaDirective?: (node: PragmaDirective) => void; + PragmaName?: (node: PragmaName) => void; + PragmaValue?: (node: PragmaValue) => void; + Version?: (node: Version) => void; + VersionOperator?: (node: VersionOperator) => void; + VersionConstraint?: (node: VersionConstraint) => void; + ImportDeclaration?: (node: ImportDeclaration) => void; + ImportDirective?: (node: ImportDirective) => void; + ContractDefinition?: (node: ContractDefinition) => void; + InheritanceSpecifier?: (node: InheritanceSpecifier) => void; + ContractPart?: (node: ContractPart) => void; + StateVariableDeclaration?: (node: StateVariableDeclaration) => void; + UsingForDeclaration?: (node: UsingForDeclaration) => void; + StructDefinition?: (node: StructDefinition) => void; + ModifierDefinition?: (node: ModifierDefinition) => void; + ModifierInvocation?: (node: ModifierInvocation) => void; + FunctionDefinition?: (node: FunctionDefinition) => void; + ReturnParameters?: (node: ReturnParameters) => void; + ModifierList?: (node: ModifierList) => void; + EventDefinition?: (node: EventDefinition) => void; + EnumValue?: (node: EnumValue) => void; + EnumDefinition?: (node: EnumDefinition) => void; + ParameterList?: (node: ParameterList) => void; + Parameter?: (node: Parameter) => void; + EventParameterList?: (node: EventParameterList) => void; + EventParameter?: (node: EventParameter) => void; + FunctionTypeParameterList?: (node: FunctionTypeParameterList) => void; + FunctionTypeParameter?: (node: FunctionTypeParameter) => void; + VariableDeclaration?: (node: VariableDeclaration) => void; + TypeName?: (node: TypeName) => void; + UserDefinedTypeName?: (node: UserDefinedTypeName) => void; + Mapping?: (node: Mapping) => void; + FunctionTypeName?: (node: FunctionTypeName) => void; + StorageLocation?: (node: StorageLocation) => void; + StateMutability?: (node: StateMutability) => void; + Block?: (node: Block) => void; + Statement?: (node: Statement) => void; + ExpressionStatement?: (node: ExpressionStatement) => void; + IfStatement?: (node: IfStatement) => void; + WhileStatement?: (node: WhileStatement) => void; + SimpleStatement?: (node: SimpleStatement) => void; + ForStatement?: (node: ForStatement) => void; + InlineAssemblyStatement?: (node: InlineAssemblyStatement) => void; + DoWhileStatement?: (node: DoWhileStatement) => void; + ContinueStatement?: (node: ContinueStatement) => void; + BreakStatement?: (node: BreakStatement) => void; + ReturnStatement?: (node: ReturnStatement) => void; + ThrowStatement?: (node: ThrowStatement) => void; + VariableDeclarationStatement?: (node: VariableDeclarationStatement) => void; + IdentifierList?: (node: IdentifierList) => void; + ElementaryTypeName?: (node: ElementaryTypeName) => void; + Expression?: (node: Expression) => void; + PrimaryExpression?: (node: PrimaryExpression) => void; + ExpressionList?: (node: ExpressionList) => void; + NameValueList?: (node: NameValueList) => void; + NameValue?: (node: NameValue) => void; + FunctionCallArguments?: (node: FunctionCallArguments) => void; + AssemblyBlock?: (node: AssemblyBlock) => void; + AssemblyItem?: (node: AssemblyItem) => void; + AssemblyExpression?: (node: AssemblyExpression) => void; + AssemblyCall?: (node: AssemblyCall) => void; + AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => void; + AssemblyAssignment?: (node: AssemblyAssignment) => void; + AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => void; + AssemblyIdentifierList?: (node: AssemblyIdentifierList) => void; + AssemblyStackAssignment?: (node: AssemblyStackAssignment) => void; + LabelDefinition?: (node: LabelDefinition) => void; + AssemblySwitch?: (node: AssemblySwitch) => void; + AssemblyCase?: (node: AssemblyCase) => void; + AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => void; + AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => void; + AssemblyFor?: (node: AssemblyFor) => void; + AssemblyIf?: (node: AssemblyIf) => void; + AssemblyLiteral?: (node: AssemblyLiteral) => void; + SubAssembly?: (node: SubAssembly) => void; + TupleExpression?: (node: TupleExpression) => void; + ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => void; + NumberLiteral?: (node: NumberLiteral) => void; + Identifier?: (node: Identifier) => void; + BinaryOperation?: (node: BinaryOperation) => void; + Conditional?: (node: Conditional) => void; + } + export interface ParserOpts { + range?: boolean; + } + export function parse(sourceCode: string, parserOpts: ParserOpts): ASTNode; + export function visit(ast: ASTNode, visitor: Visitor): void; +} diff --git a/packages/typescript-typings/types/to-snake-case/index.d.ts b/packages/typescript-typings/types/to-snake-case/index.d.ts new file mode 100644 index 000000000..39df3f852 --- /dev/null +++ b/packages/typescript-typings/types/to-snake-case/index.d.ts @@ -0,0 +1,4 @@ +declare function toSnakeCase(str: string): string; +declare module 'to-snake-case' { + export = toSnakeCase; +} diff --git a/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts b/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts index f2b002233..af82557cb 100644 --- a/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts +++ b/packages/typescript-typings/types/truffle-hdwalet-provider/index.d.ts @@ -1,7 +1,6 @@ declare module 'truffle-hdwallet-provider' { - import { JSONRPCRequestPayload, JSONRPCResponsePayload } from '@0xproject/types'; - import * as Web3 from 'web3'; - class HDWalletProvider implements Web3.Provider { + import { JSONRPCRequestPayload, JSONRPCResponsePayload, Provider } from '@0xproject/types'; + class HDWalletProvider implements Provider { constructor(mnemonic: string, rpcUrl: string); public sendAsync( payload: JSONRPCRequestPayload, diff --git a/packages/typescript-typings/types/web3-provider-engine/index.d.ts b/packages/typescript-typings/types/web3-provider-engine/index.d.ts index f30b06873..15a8d0005 100644 --- a/packages/typescript-typings/types/web3-provider-engine/index.d.ts +++ b/packages/typescript-typings/types/web3-provider-engine/index.d.ts @@ -9,3 +9,42 @@ declare module 'web3-provider-engine' { } export = Web3ProviderEngine; } + +declare module 'web3-provider-engine/subproviders/nonce-tracker'; +declare module 'web3-provider-engine/subproviders/hooked-wallet'; +declare module 'web3-provider-engine/subproviders/filters'; +// web3-provider-engine declarations +declare module 'web3-provider-engine/subproviders/subprovider' { + class Subprovider {} + export = Subprovider; +} +declare module 'web3-provider-engine/subproviders/rpc' { + import { JSONRPCRequestPayload } from '@0xproject/types'; + class RpcSubprovider { + constructor(options: { rpcUrl: string }); + public handleRequest( + payload: JSONRPCRequestPayload, + next: () => void, + end: (err: Error | null, data?: any) => void, + ): void; + } + export = RpcSubprovider; +} +declare module 'web3-provider-engine/util/rpc-cache-utils' { + class ProviderEngineRpcUtils { + public static blockTagForPayload(payload: any): string | null; + } + export = ProviderEngineRpcUtils; +} +declare module 'web3-provider-engine/subproviders/fixture' { + import { JSONRPCRequestPayload } from '@0xproject/types'; + class FixtureSubprovider { + constructor(staticResponses: any); + public handleRequest( + payload: JSONRPCRequestPayload, + next: () => void, + end: (err: Error | null, data?: any) => void, + ): void; + } + export = FixtureSubprovider; +} diff --git a/packages/typescript-typings/types/web3/index.d.ts b/packages/typescript-typings/types/web3/index.d.ts index f4ebd41b9..15e7575a8 100644 --- a/packages/typescript-typings/types/web3/index.d.ts +++ b/packages/typescript-typings/types/web3/index.d.ts @@ -6,6 +6,7 @@ declare module 'web3' { BlockWithoutTransactionData, BlockParam, CallData, + Provider, Unit, TxData, Transaction, @@ -21,17 +22,17 @@ declare module 'web3' { class Web3 { public static providers: typeof providers; - public currentProvider: Web3.Provider; + public currentProvider: Provider; public eth: Web3.EthApi; public personal: Web3.PersonalApi | undefined; public version: Web3.VersionApi; public net: Web3.NetApi; - public constructor(provider?: Web3.Provider); + public constructor(provider?: Provider); public isConnected(): boolean; - public setProvider(provider: Web3.Provider): void; + public setProvider(provider: Provider): void; public reset(keepIsSyncing: boolean): void; public toHex(data: MixedData): string; public toAscii(hex: string): string; @@ -49,7 +50,7 @@ declare module 'web3' { } namespace providers { - class HttpProvider implements Web3.Provider { + class HttpProvider implements Provider { constructor(url?: string, timeout?: number, username?: string, password?: string); public sendAsync( payload: JSONRPCRequestPayload, @@ -77,13 +78,6 @@ declare module 'web3' { stopWatching(callback?: () => void): void; } - interface Provider { - sendAsync( - payload: JSONRPCRequestPayload, - callback: (err: Error, result: JSONRPCResponsePayload) => void, - ): void; - } - interface Sha3Options { encoding: 'hex'; } diff --git a/packages/typescript-typings/types/xml-js/index.d.ts b/packages/typescript-typings/types/xml-js/index.d.ts new file mode 100644 index 000000000..8e4873aeb --- /dev/null +++ b/packages/typescript-typings/types/xml-js/index.d.ts @@ -0,0 +1,7 @@ +declare interface XML2JSONOpts { + compact?: boolean; + spaces?: number; +} +declare module 'xml-js' { + const xml2json: (xml: string, opts: XML2JSONOpts) => string; +} diff --git a/packages/utils/README.md b/packages/utils/README.md index fde0780a9..914404937 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -24,11 +24,11 @@ import { addressUtils, bigNumberConfigs, classUtils, intervalUtils, promisify } ## Contributing -We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -44,16 +44,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/web3-wrapper/CHANGELOG.json b/packages/web3-wrapper/CHANGELOG.json index bdf09f81e..14e45dacb 100644 --- a/packages/web3-wrapper/CHANGELOG.json +++ b/packages/web3-wrapper/CHANGELOG.json @@ -1,5 +1,18 @@ [ { + "version": "0.6.0", + "changes": [ + { + "note": "Make `isAddress` and `toWei` static", + "pr": 501 + }, + { + "note": "Add static methods `toUnitAmount` and `toBaseUnitAmount`", + "pr": 501 + } + ] + }, + { "version": "0.5.0", "changes": [ { diff --git a/packages/web3-wrapper/README.md b/packages/web3-wrapper/README.md index e7491acb0..1ff85420a 100644 --- a/packages/web3-wrapper/README.md +++ b/packages/web3-wrapper/README.md @@ -20,11 +20,11 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol ## Contributing -We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository. +We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository. Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started. -### Install Dependencies +### Install dependencies If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them: @@ -40,16 +40,36 @@ yarn install ### Build +If this is your **first** time building this package, you must first build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: + +```bash +yarn lerna:rebuild +``` + +Or continuously rebuild on change: + +```bash +yarn dev +``` + +You can also build this specific package by running the following from within its directory: + ```bash yarn build ``` -or +or continuously rebuild on change: ```bash yarn build:watch ``` +### Clean + +```bash +yarn clean +``` + ### Lint ```bash diff --git a/packages/web3-wrapper/coverage/.gitkeep b/packages/web3-wrapper/coverage/.gitkeep new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/packages/web3-wrapper/coverage/.gitkeep diff --git a/packages/web3-wrapper/package.json b/packages/web3-wrapper/package.json index 20fa39b07..910d4725e 100644 --- a/packages/web3-wrapper/package.json +++ b/packages/web3-wrapper/package.json @@ -2,13 +2,18 @@ "name": "@0xproject/web3-wrapper", "version": "0.5.0", "description": "Wraps around web3 and gives a nicer interface", - "main": "lib/index.js", - "types": "lib/index.d.ts", + "main": "lib/src/index.js", + "types": "lib/src/index.d.ts", "scripts": { "build:watch": "tsc -w", "build": "tsc && copyfiles -u 2 './lib/monorepo_scripts/**/*' ./scripts", "clean": "shx rm -rf lib scripts", "lint": "tslint --project . 'src/**/*.ts'", + "test": "run-s clean build run_mocha", + "test:circleci": "yarn test:coverage", + "run_mocha": "mocha lib/test/**/*_test.js --bail --exit", + "test:coverage": "nyc npm run test --all && yarn coverage:report:lcov", + "coverage:report:lcov": "nyc report --reporter=text-lcov > coverage/lcov.info", "manual:postpublish": "yarn build; node ./scripts/postpublish.js", "docs:stage": "yarn build && node ./scripts/stage_docs.js", "docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_FILES", @@ -41,6 +46,13 @@ "copyfiles": "^1.2.0", "npm-run-all": "^4.1.2", "shx": "^0.2.2", + "chai": "^4.0.1", + "mocha": "^4.0.1", + "nyc": "^11.0.1", + "ganache-core": "0xProject/ganache-core", + "chai-as-promised": "^7.1.0", + "chai-bignumber": "^2.0.1", + "dirty-chai": "^2.0.1", "tslint": "5.8.0", "typedoc": "0xProject/typedoc", "typescript": "2.7.1" diff --git a/packages/web3-wrapper/src/web3_wrapper.ts b/packages/web3-wrapper/src/web3_wrapper.ts index d75f39ed5..5e6ff3239 100644 --- a/packages/web3-wrapper/src/web3_wrapper.ts +++ b/packages/web3-wrapper/src/web3_wrapper.ts @@ -7,12 +7,13 @@ import { JSONRPCRequestPayload, JSONRPCResponsePayload, LogEntry, + Provider, RawLogEntry, TransactionReceipt, TransactionReceiptWithDecodedLogs, TxData, } from '@0xproject/types'; -import { AbiDecoder, BigNumber, intervalUtils, promisify } from '@0xproject/utils'; +import { AbiDecoder, addressUtils, BigNumber, intervalUtils, promisify } from '@0xproject/utils'; import * as _ from 'lodash'; import * as Web3 from 'web3'; @@ -31,13 +32,61 @@ export class Web3Wrapper { private _defaults: Partial<TxData>; private _jsonRpcRequestId: number; /** + * Check if an address is a valid Ethereum address + * @param address Address to check + * @returns Whether the address is a valid Ethereum address + */ + public static isAddress(address: string): boolean { + return addressUtils.isAddress(address); + } + /** + * A unit amount is defined as the amount of a token above the specified decimal places (integer part). + * E.g: If a currency has 18 decimal places, 1e18 or one quintillion of the currency is equivalent + * to 1 unit. + * @param amount The amount in baseUnits that you would like converted to units. + * @param decimals The number of decimal places the unit amount has. + * @return The amount in units. + */ + public static toUnitAmount(amount: BigNumber, decimals: number): BigNumber { + const aUnit = new BigNumber(10).pow(decimals); + const unit = amount.div(aUnit); + return unit; + } + /** + * A baseUnit is defined as the smallest denomination of a token. An amount expressed in baseUnits + * is the amount expressed in the smallest denomination. + * E.g: 1 unit of a token with 18 decimal places is expressed in baseUnits as 1000000000000000000 + * @param amount The amount of units that you would like converted to baseUnits. + * @param decimals The number of decimal places the unit amount has. + * @return The amount in baseUnits. + */ + public static toBaseUnitAmount(amount: BigNumber, decimals: number): BigNumber { + const unit = new BigNumber(10).pow(decimals); + const baseUnitAmount = amount.times(unit); + const hasDecimals = baseUnitAmount.decimalPlaces() !== 0; + if (hasDecimals) { + throw new Error(`Invalid unit amount: ${amount.toString()} - Too many decimal places`); + } + return baseUnitAmount; + } + /** + * Convert an Ether amount from ETH to Wei + * @param ethAmount Amount of Ether to convert to wei + * @returns Amount in wei + */ + public static toWei(ethAmount: BigNumber): BigNumber { + const ETH_DECIMALS = 18; + const balanceWei = Web3Wrapper.toBaseUnitAmount(ethAmount, ETH_DECIMALS); + return balanceWei; + } + /** * Instantiates a new Web3Wrapper. * @param provider The Web3 provider instance you would like the Web3Wrapper to use for interacting with * the backing Ethereum node. * @param defaults Override TxData defaults sent with RPC requests to the backing Ethereum node. * @return An instance of the Web3Wrapper class. */ - constructor(provider: Web3.Provider, defaults?: Partial<TxData>) { + constructor(provider: Provider, defaults?: Partial<TxData>) { if (_.isUndefined((provider as any).sendAsync)) { // Web3@1.0 provider doesn't support synchronous http requests, // so it only has an async `send` method, instead of a `send` and `sendAsync` in web3@0.x.x` @@ -61,25 +110,17 @@ export class Web3Wrapper { * Retrieve the Web3 provider * @return Web3 provider instance */ - public getProvider(): Web3.Provider { + public getProvider(): Provider { return this._web3.currentProvider; } /** * Update the used Web3 provider * @param provider The new Web3 provider to be set */ - public setProvider(provider: Web3.Provider) { + public setProvider(provider: Provider) { this._web3.setProvider(provider); } /** - * Check if an address is a valid Ethereum address - * @param address Address to check - * @returns Whether the address is a valid Ethereum address - */ - public isAddress(address: string): boolean { - return this._web3.isAddress(address); - } - /** * Check whether an address is available through the backing provider. This can be * useful if you want to know whether a user can sign messages or transactions from * a given Ethereum address. @@ -96,7 +137,7 @@ export class Web3Wrapper { * @returns Ethereum node's version string */ public async getNodeVersionAsync(): Promise<string> { - const nodeVersion = await promisify<string>(this._web3.version.getNode)(); + const nodeVersion = await this._sendRawPayloadAsync<string>({ method: 'web3_clientVersion' }); return nodeVersion; } /** @@ -104,7 +145,7 @@ export class Web3Wrapper { * @returns The network id */ public async getNetworkIdAsync(): Promise<number> { - const networkIdStr = await promisify<string>(this._web3.version.getNetwork)(); + const networkIdStr = await this._sendRawPayloadAsync<string>({ method: 'net_version' }); const networkId = _.parseInt(networkIdStr); return networkId; } @@ -121,15 +162,6 @@ export class Web3Wrapper { return transactionReceipt; } /** - * Convert an Ether amount from ETH to Wei - * @param ethAmount Amount of Ether to convert to wei - * @returns Amount in wei - */ - public toWei(ethAmount: BigNumber): BigNumber { - const balanceWei = this._web3.toWei(ethAmount, 'ether'); - return balanceWei; - } - /** * Retrieves an accounts Ether balance in wei * @param owner Account whose balance you wish to check * @returns Balance in wei diff --git a/packages/web3-wrapper/test/utils/chai_setup.ts b/packages/web3-wrapper/test/utils/chai_setup.ts new file mode 100644 index 000000000..078edd309 --- /dev/null +++ b/packages/web3-wrapper/test/utils/chai_setup.ts @@ -0,0 +1,13 @@ +import * as chai from 'chai'; +import chaiAsPromised = require('chai-as-promised'); +import ChaiBigNumber = require('chai-bignumber'); +import * as dirtyChai from 'dirty-chai'; + +export const chaiSetup = { + configure() { + chai.config.includeStack = true; + chai.use(ChaiBigNumber()); + chai.use(dirtyChai); + chai.use(chaiAsPromised); + }, +}; diff --git a/packages/web3-wrapper/test/web3_wrapper_test.ts b/packages/web3-wrapper/test/web3_wrapper_test.ts new file mode 100644 index 000000000..2bf3badaa --- /dev/null +++ b/packages/web3-wrapper/test/web3_wrapper_test.ts @@ -0,0 +1,39 @@ +import * as chai from 'chai'; +import * as Ganache from 'ganache-core'; +import 'mocha'; + +import { Web3Wrapper } from '../src'; + +import { chaiSetup } from './utils/chai_setup'; +chaiSetup.configure(); + +const { expect } = chai; + +describe('Web3Wrapper tests', () => { + const NETWORK_ID = 50; + const provider = Ganache.provider({ network_id: NETWORK_ID }); + const web3Wrapper = new Web3Wrapper(provider); + describe('#isAddress', () => { + it('correctly checks if a string is a valid ethereum address', () => { + expect(Web3Wrapper.isAddress('0x0')).to.be.false(); + expect(Web3Wrapper.isAddress('0xdeadbeef')).to.be.false(); + expect(Web3Wrapper.isAddress('42')).to.be.false(); + expect(Web3Wrapper.isAddress('weth.thetoken.eth')).to.be.false(); + expect(Web3Wrapper.isAddress('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2')).to.be.true(); + expect(Web3Wrapper.isAddress('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')).to.be.true(); + }); + }); + describe('#getNodeVersionAsync', () => { + it('gets the node version', async () => { + const nodeVersion = await web3Wrapper.getNodeVersionAsync(); + const NODE_VERSION = 'EthereumJS TestRPC/v2.1.0/ethereum-js'; + expect(nodeVersion).to.be.equal(NODE_VERSION); + }); + }); + describe('#getNetworkIdAsync', () => { + it('gets the network id', async () => { + const networkId = await web3Wrapper.getNetworkIdAsync(); + expect(networkId).to.be.equal(NETWORK_ID); + }); + }); +}); diff --git a/packages/web3-wrapper/tsconfig.json b/packages/web3-wrapper/tsconfig.json index c56d255d5..8b4cd47a2 100644 --- a/packages/web3-wrapper/tsconfig.json +++ b/packages/web3-wrapper/tsconfig.json @@ -3,5 +3,5 @@ "compilerOptions": { "outDir": "lib" }, - "include": ["./src/**/*"] + "include": ["src/**/*", "test/**/*"] } diff --git a/packages/website/README.md b/packages/website/README.md index 042df52de..d93d18935 100644 --- a/packages/website/README.md +++ b/packages/website/README.md @@ -28,20 +28,24 @@ Add the following to your `/etc/hosts` file: yarn install ``` -### Run dev server +### Initial setup + +The **first** time you work with this package, you must build **all** packages within the monorepo. This is because packages that depend on other packages located inside this monorepo are symlinked when run from **within** the monorepo. This allows you to make changes across multiple packages without first publishing dependent packages to NPM. To build all packages, run the following from the monorepo root directory: ```bash -yarn run dev +yarn lerna:rebuild ``` -Visit [0xproject.localhost:3572](http://0xproject.localhost:3572) in your browser. +### Run dev server -### Build +The the `website` root directory, run: ```bash -yarn build +yarn dev ``` +Visit [0xproject.localhost:3572](http://0xproject.localhost:3572) in your browser. + ### Clean ```bash diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 72cb94c02..fd34ab82d 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -23,6 +23,7 @@ import { LedgerWalletSubprovider, RedundantRPCSubprovider, } from '@0xproject/subproviders'; +import { Provider } from '@0xproject/types'; import { BigNumber, intervalUtils, logUtils, promisify } from '@0xproject/utils'; import { Web3Wrapper } from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; @@ -73,11 +74,11 @@ export class Blockchain { private _web3Wrapper?: Web3Wrapper; private _blockchainWatcher?: BlockchainWatcher; private _userAddressIfExists: string; - private _cachedProvider: Web3.Provider; + private _cachedProvider: Provider; private _cachedProviderNetworkId: number; private _ledgerSubprovider: LedgerWalletSubprovider; private _defaultGasPrice: BigNumber; - private static _getNameGivenProvider(provider: Web3.Provider): string { + private static _getNameGivenProvider(provider: Provider): string { const providerType = utils.getProviderType(provider); const providerNameIfExists = providerToName[providerType]; if (_.isUndefined(providerNameIfExists)) { @@ -377,7 +378,7 @@ export class Blockchain { } public isValidAddress(address: string): boolean { const lowercaseAddress = address.toLowerCase(); - return this._web3Wrapper.isAddress(lowercaseAddress); + return Web3Wrapper.isAddress(lowercaseAddress); } public async pollTokenBalanceAsync(token: Token) { utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); diff --git a/packages/website/ts/components/portal.tsx b/packages/website/ts/components/portal.tsx index ceb0ecc72..b79f5e288 100644 --- a/packages/website/ts/components/portal.tsx +++ b/packages/website/ts/components/portal.tsx @@ -15,6 +15,7 @@ import { EthWrappers } from 'ts/components/eth_wrappers'; import { FillOrder } from 'ts/components/fill_order'; import { Footer } from 'ts/components/footer'; import { PortalMenu } from 'ts/components/portal_menu'; +import { RelayerIndex } from 'ts/components/relayer_index/relayer_index'; import { TokenBalances } from 'ts/components/token_balances'; import { TopBar } from 'ts/components/top_bar/top_bar'; import { TradeHistory } from 'ts/components/trade_history/trade_history'; @@ -155,6 +156,7 @@ export class Portal extends React.Component<PortalAllProps, PortalAllState> { const updateShouldBlockchainErrDialogBeOpen = this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen.bind( this.props.dispatcher, ); + const isDevelopment = configs.ENVIRONMENT === Environments.DEVELOPMENT; const portalStyle: React.CSSProperties = { minHeight: '100vh', display: 'flex', @@ -204,12 +206,18 @@ export class Portal extends React.Component<PortalAllProps, PortalAllState> { <div className="py2" style={{ backgroundColor: colors.grey50 }}> {this.props.blockchainIsLoaded ? ( <Switch> - {configs.ENVIRONMENT === Environments.DEVELOPMENT && ( + {isDevelopment && ( <Route path={`${WebsitePaths.Portal}/wallet`} render={this._renderWallet.bind(this)} /> )} + {isDevelopment && ( + <Route + path={`${WebsitePaths.Portal}/relayers`} + render={this._renderRelayers.bind(this)} + /> + )} <Route path={`${WebsitePaths.Portal}/weth`} render={this._renderEthWrapper.bind(this)} @@ -313,6 +321,15 @@ export class Portal extends React.Component<PortalAllProps, PortalAllState> { </div> ); } + private _renderRelayers() { + return ( + <div className="flex flex-center"> + <div className="mx-auto" style={{ width: 800 }}> + <RelayerIndex networkId={this.props.networkId} /> + </div> + </div> + ); + } private _renderEthWrapper() { return ( <EthWrappers diff --git a/packages/website/ts/components/portal_menu.tsx b/packages/website/ts/components/portal_menu.tsx index 9ab611556..2b4d7eea2 100644 --- a/packages/website/ts/components/portal_menu.tsx +++ b/packages/website/ts/components/portal_menu.tsx @@ -59,14 +59,24 @@ export class PortalMenu extends React.Component<PortalMenuProps, PortalMenuState {this._renderMenuItemWithIcon('Wrap ETH', 'zmdi-circle-o')} </MenuItem> {configs.ENVIRONMENT === Environments.DEVELOPMENT && ( - <MenuItem - style={this.props.menuItemStyle} - className="py2" - to={`${WebsitePaths.Portal}/wallet`} - onClick={this.props.onClick.bind(this)} - > - {this._renderMenuItemWithIcon('Wallet', 'zmdi-balance-wallet')} - </MenuItem> + <div> + <MenuItem + style={this.props.menuItemStyle} + className="py2" + to={`${WebsitePaths.Portal}/wallet`} + onClick={this.props.onClick.bind(this)} + > + {this._renderMenuItemWithIcon('Wallet', 'zmdi-balance-wallet')} + </MenuItem> + <MenuItem + style={this.props.menuItemStyle} + className="py2" + to={`${WebsitePaths.Portal}/relayers`} + onClick={this.props.onClick.bind(this)} + > + {this._renderMenuItemWithIcon('Relayers', 'zmdi-input-antenna')} + </MenuItem> + </div> )} </div> ); diff --git a/packages/website/ts/components/relayer_index/relayer_grid_tile.tsx b/packages/website/ts/components/relayer_index/relayer_grid_tile.tsx new file mode 100644 index 000000000..530576828 --- /dev/null +++ b/packages/website/ts/components/relayer_index/relayer_grid_tile.tsx @@ -0,0 +1,84 @@ +import { colors, Styles } from '@0xproject/react-shared'; +import * as _ from 'lodash'; +import { GridTile } from 'material-ui/GridList'; +import * as React from 'react'; + +import { TopTokens } from 'ts/components/relayer_index/relayer_top_tokens'; +import { TokenIcon } from 'ts/components/ui/token_icon'; +import { RelayerInfo, Token } from 'ts/types'; + +export interface RelayerGridTileProps { + relayerInfo: RelayerInfo; + networkId: number; +} + +const styles: Styles = { + root: { + backgroundColor: colors.white, + borderBottomRightRadius: 10, + borderBottomLeftRadius: 10, + borderTopRightRadius: 10, + borderTopLeftRadius: 10, + boxShadow: `0px 4px 6px ${colors.walletBoxShadow}`, + overflow: 'hidden', + boxSizing: 'border-box', + }, + innerDiv: { + padding: 6, + height: '100%', + boxSizing: 'border-box', + }, + header: { + height: '50%', + width: '100%', + objectFit: 'cover', + borderBottomRightRadius: 4, + borderBottomLeftRadius: 4, + borderTopRightRadius: 4, + borderTopLeftRadius: 4, + }, + body: { + paddingLeft: 6, + paddingRight: 6, + height: '50%', + width: '100%', + boxSizing: 'border-box', + }, + marketShareBar: { + height: 14, + width: '100%', + backgroundColor: colors.mediumBlue, + }, + subLabel: { + fontSize: 12, + color: colors.lightGrey, + }, + relayerNameLabel: { + fontSize: 16, + fontWeight: 'bold', + color: colors.black, + }, +}; + +export const RelayerGridTile: React.StatelessComponent<RelayerGridTileProps> = (props: RelayerGridTileProps) => { + return ( + <GridTile style={styles.root}> + <div style={styles.innerDiv}> + <img src={props.relayerInfo.headerUrl} style={styles.header} /> + <div style={styles.body}> + <div className="py1" style={styles.relayerNameLabel}> + {props.relayerInfo.name} + </div> + <div style={styles.marketShareBar} /> + <div className="py1" style={styles.subLabel}> + Market share + </div> + <TopTokens tokens={props.relayerInfo.topTokens} networkId={props.networkId} /> + <div className="py1" style={styles.subLabel}> + Top tokens + </div> + </div> + </div> + </GridTile> + ); +}; diff --git a/packages/website/ts/components/relayer_index/relayer_index.tsx b/packages/website/ts/components/relayer_index/relayer_index.tsx new file mode 100644 index 000000000..db3cf07b5 --- /dev/null +++ b/packages/website/ts/components/relayer_index/relayer_index.tsx @@ -0,0 +1,118 @@ +import { colors, Styles } from '@0xproject/react-shared'; +import { GridList } from 'material-ui/GridList'; +import * as React from 'react'; + +import { RelayerGridTile } from 'ts/components/relayer_index/relayer_grid_tile'; +import { RelayerInfo } from 'ts/types'; + +export interface RelayerIndexProps { + networkId: number; +} + +const styles: Styles = { + root: { + width: '100%', + }, + item: { + backgroundColor: colors.white, + borderBottomRightRadius: 10, + borderBottomLeftRadius: 10, + borderTopRightRadius: 10, + borderTopLeftRadius: 10, + boxShadow: `0px 4px 6px ${colors.walletBoxShadow}`, + overflow: 'hidden', + padding: 4, + }, +}; + +// TODO: replace fake data with real, remote data +const topTokens = [ + { + address: '0x1dad4783cf3fe3085c1426157ab175a6119a04ba', + decimals: 18, + iconUrl: '/images/token_icons/makerdao.png', + isRegistered: true, + isTracked: true, + name: 'Maker DAO', + symbol: 'MKR', + }, + { + address: '0x323b5d4c32345ced77393b3530b1eed0f346429d', + decimals: 18, + iconUrl: '/images/token_icons/melon.png', + isRegistered: true, + isTracked: true, + name: 'Melon Token', + symbol: 'MLN', + }, + { + address: '0xb18845c260f680d5b9d84649638813e342e4f8c9', + decimals: 18, + iconUrl: '/images/token_icons/augur.png', + isRegistered: true, + isTracked: true, + name: 'Augur Reputation Token', + symbol: 'REP', + }, +]; + +const relayerInfos: RelayerInfo[] = [ + { + id: '1', + headerUrl: '/images/og_image.png', + name: 'Radar Relay', + marketShare: 0.5, + topTokens, + }, + { + id: '2', + headerUrl: '/images/og_image.png', + name: 'Paradex', + marketShare: 0.5, + topTokens, + }, + { + id: '3', + headerUrl: '/images/og_image.png', + name: 'yo', + marketShare: 0.5, + topTokens, + }, + { + id: '4', + headerUrl: '/images/og_image.png', + name: 'test', + marketShare: 0.5, + topTokens, + }, + { + id: '5', + headerUrl: '/images/og_image.png', + name: 'blahg', + marketShare: 0.5, + topTokens, + }, + { + id: '6', + headerUrl: '/images/og_image.png', + name: 'hello', + marketShare: 0.5, + topTokens, + }, +]; + +const CELL_HEIGHT = 260; +const NUMBER_OF_COLUMNS = 4; +const GRID_PADDING = 16; + +export const RelayerIndex: React.StatelessComponent<RelayerIndexProps> = (props: RelayerIndexProps) => { + return ( + <div style={styles.root}> + <GridList cellHeight={CELL_HEIGHT} cols={NUMBER_OF_COLUMNS} padding={GRID_PADDING} style={styles.gridList}> + {relayerInfos.map((relayerInfo: RelayerInfo) => ( + <RelayerGridTile key={relayerInfo.id} relayerInfo={relayerInfo} networkId={props.networkId} /> + ))} + </GridList> + </div> + ); +}; diff --git a/packages/website/ts/components/relayer_index/relayer_top_tokens.tsx b/packages/website/ts/components/relayer_index/relayer_top_tokens.tsx new file mode 100644 index 000000000..233590b78 --- /dev/null +++ b/packages/website/ts/components/relayer_index/relayer_top_tokens.tsx @@ -0,0 +1,46 @@ +import { colors, EtherscanLinkSuffixes, Styles, utils as sharedUtils } from '@0xproject/react-shared'; +import * as _ from 'lodash'; +import * as React from 'react'; + +import { TokenIcon } from 'ts/components/ui/token_icon'; +import { Token } from 'ts/types'; + +export interface TopTokensProps { + tokens: Token[]; + networkId: number; +} + +const styles: Styles = { + tokenLabel: { + textDecoration: 'none', + color: colors.mediumBlue, + }, + followingTokenLabel: { + paddingLeft: 16, + }, +}; + +export const TopTokens: React.StatelessComponent<TopTokensProps> = (props: TopTokensProps) => { + return ( + <div className="flex"> + {_.map(props.tokens, (token: Token, index: number) => { + const firstItemStyle = { ...styles.tokenLabel, ...styles.followingTokenLabel }; + const style = index !== 0 ? firstItemStyle : styles.tokenLabel; + return ( + <a + key={token.address} + href={tokenLinkFromToken(token, props.networkId)} + target="_blank" + style={style} + > + {token.symbol} + </a> + ); + })} + </div> + ); +}; + +function tokenLinkFromToken(token: Token, networkId: number) { + return sharedUtils.getEtherScanLinkIfExists(token.address, networkId, EtherscanLinkSuffixes.Address); +} diff --git a/packages/website/ts/components/wallet/wallet.tsx b/packages/website/ts/components/wallet/wallet.tsx index 39c95d31c..d3dc8e3dd 100644 --- a/packages/website/ts/components/wallet/wallet.tsx +++ b/packages/website/ts/components/wallet/wallet.tsx @@ -71,7 +71,7 @@ interface AccessoryItemConfig { } const styles: Styles = { - wallet: { + root: { width: 346, backgroundColor: colors.white, borderBottomRightRadius: 10, @@ -121,6 +121,10 @@ const ZRX_TOKEN_SYMBOL = 'ZRX'; const ETHER_SYMBOL = 'ETH'; const ICON_DIMENSION = 24; const TOKEN_AMOUNT_DISPLAY_PRECISION = 3; +const HEADER_ITEM_KEY = 'HEADER'; +const FOOTER_ITEM_KEY = 'FOOTER'; +const DISCONNECTED_ITEM_KEY = 'DISCONNECTED'; +const ETHER_ITEM_KEY = 'ETHER'; export class Wallet extends React.Component<WalletProps, WalletState> { private _isUnmounted: boolean; @@ -174,7 +178,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { } public render() { const isReadyToRender = this.props.blockchainIsLoaded && this.props.blockchainErr === BlockchainErrs.NoError; - return <div style={styles.wallet}>{isReadyToRender && this._renderRows()}</div>; + return <div style={styles.root}>{isReadyToRender && this._renderRows()}</div>; } private _renderRows() { const isAddressAvailable = !_.isEmpty(this.props.userAddress); @@ -196,6 +200,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { const primaryText = 'wallet'; return ( <ListItem + key={HEADER_ITEM_KEY} primaryText={primaryText.toUpperCase()} leftIcon={<ActionAccountBalanceWallet color={colors.mediumBlue} />} style={styles.paddedItem} @@ -206,6 +211,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { private _renderDisconnectedRows() { return ( <WalletDisconnectedItem + key={DISCONNECTED_ITEM_KEY} providerType={this.props.providerType} injectedProviderName={this.props.injectedProviderName} onToggleLedgerDialog={this.props.onToggleLedgerDialog} @@ -217,6 +223,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { const primaryText = utils.getAddressBeginAndEnd(userAddress); return ( <ListItem + key={HEADER_ITEM_KEY} primaryText={primaryText} leftIcon={<Identicon address={userAddress} diameter={ICON_DIMENSION} />} style={{ ...styles.paddedItem, ...styles.borderedItem }} @@ -226,7 +233,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { } private _renderFooterRows() { const primaryText = '+ other tokens'; - return <ListItem primaryText={primaryText} innerDivStyle={styles.footerItemInnerDiv} />; + return <ListItem key={FOOTER_ITEM_KEY} primaryText={primaryText} innerDivStyle={styles.footerItemInnerDiv} />; } private _renderEthRows() { const primaryText = this._renderAmount( @@ -245,7 +252,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { : { ...styles.tokenItem, ...styles.borderedItem, ...styles.paddedItem }; const etherToken = this._getEthToken(); return ( - <div> + <div key={ETHER_ITEM_KEY}> <ListItem primaryText={primaryText} leftIcon={<img style={{ width: ICON_DIMENSION, height: ICON_DIMENSION }} src={ETHER_ICON_PATH} />} @@ -304,7 +311,7 @@ export class Wallet extends React.Component<WalletProps, WalletState> { : { ...styles.tokenItem, ...styles.borderedItem, ...styles.paddedItem }; const etherToken = this._getEthToken(); return ( - <div> + <div key={token.address}> <ListItem primaryText={amount} leftIcon={this._renderTokenIcon(token, tokenLink)} diff --git a/packages/website/ts/components/wallet/wrap_ether_item.tsx b/packages/website/ts/components/wallet/wrap_ether_item.tsx index 3a876721a..a38163770 100644 --- a/packages/website/ts/components/wallet/wrap_ether_item.tsx +++ b/packages/website/ts/components/wallet/wrap_ether_item.tsx @@ -111,7 +111,7 @@ export class WrapEtherItem extends React.Component<WrapEtherItemProps, WrapEther disableTouchRipple={true} style={walletItemStyles.focusedItem} innerDivStyle={styles.innerDiv} - leftIcon={this.state.isEthConversionHappening && this._renderIsEthConversionHappeningSpinner()} + leftIcon={this._renderIsEthConversionHappeningSpinner()} rightAvatar={this._renderWrapEtherConfirmationButton()} /> ); @@ -123,11 +123,11 @@ export class WrapEtherItem extends React.Component<WrapEtherItemProps, WrapEther }); } private _renderIsEthConversionHappeningSpinner() { - return ( + return this.state.isEthConversionHappening ? ( <div className="pl1" style={{ paddingTop: 10 }}> <i className="zmdi zmdi-spinner zmdi-hc-spin" /> </div> - ); + ) : null; } private _renderWrapEtherConfirmationButton() { const isWrappingEth = this.props.direction === Side.Deposit; diff --git a/packages/website/ts/containers/zero_ex_js_documentation.ts b/packages/website/ts/containers/zero_ex_js_documentation.ts index 6e893133f..da8922e79 100644 --- a/packages/website/ts/containers/zero_ex_js_documentation.ts +++ b/packages/website/ts/containers/zero_ex_js_documentation.ts @@ -121,6 +121,7 @@ const docsInfoConfig: DocsInfoConfig = { 'ExchangeContractErrs', 'ContractEvent', 'Token', + 'Provider', 'ExchangeEvents', 'IndexedFilterValues', 'SubscriptionOpts', diff --git a/packages/website/ts/globals.d.ts b/packages/website/ts/globals.d.ts index 2c2140485..719c2708a 100644 --- a/packages/website/ts/globals.d.ts +++ b/packages/website/ts/globals.d.ts @@ -1,8 +1,5 @@ -declare module 'react-tooltip'; declare module 'truffle-contract'; -declare module 'keccak'; declare module 'whatwg-fetch'; -declare module 'web3-provider-engine/subproviders/filters'; declare module 'thenby'; declare module 'react-document-title'; declare module 'react-ga'; @@ -14,119 +11,9 @@ declare module '*.json' { /* tslint:enable */ } -// tslint:disable:max-classes-per-file - -// find-version declarations -declare function findVersions(version: string): string[]; -declare module 'find-versions' { - export = findVersions; -} - -// semver-sort declarations -declare module 'semver-sort' { - const desc: (versions: string[]) => string[]; -} - -// xml-js declarations -declare interface XML2JSONOpts { - compact?: boolean; - spaces?: number; -} -declare module 'xml-js' { - const xml2json: (xml: string, opts: XML2JSONOpts) => string; -} - // This will be defined by default in TS 2.4 // Source: https://github.com/Microsoft/TypeScript/issues/12364 interface System { import<T>(module: string): Promise<T>; } declare var System: System; - -// jsonschema declarations -// Source: https://github.com/tdegrunt/jsonschema/blob/master/lib/index.d.ts -declare interface Schema { - id?: string; - $schema?: string; - title?: string; - description?: string; - multipleOf?: number; - maximum?: number; - exclusiveMaximum?: boolean; - minimum?: number; - exclusiveMinimum?: boolean; - maxLength?: number; - minLength?: number; - pattern?: string; - additionalItems?: boolean | Schema; - items?: Schema | Schema[]; - maxItems?: number; - minItems?: number; - uniqueItems?: boolean; - maxProperties?: number; - minProperties?: number; - required?: string[]; - additionalProperties?: boolean | Schema; - definitions?: { - [name: string]: Schema; - }; - properties?: { - [name: string]: Schema; - }; - patternProperties?: { - [name: string]: Schema; - }; - dependencies?: { - [name: string]: Schema | string[]; - }; - enum?: any[]; - type?: string | string[]; - allOf?: Schema[]; - anyOf?: Schema[]; - oneOf?: Schema[]; - not?: Schema; - // This is the only property that's not defined in https://github.com/tdegrunt/jsonschema/blob/master/lib/index.d.ts - // There is an open issue for that: https://github.com/tdegrunt/jsonschema/issues/194 - // There is also an opened PR: https://github.com/tdegrunt/jsonschema/pull/218/files - // As soon as it gets merged we should be good to use types from 'jsonschema' package - $ref?: string; -} - -// blockies declarations -declare interface BlockiesIcon { - toDataURL(): string; -} -declare interface BlockiesConfig { - seed: string; -} -declare function blockies(config: BlockiesConfig): BlockiesIcon; -declare module 'blockies' { - export = blockies; -} - -// web3-provider-engine declarations -declare class Subprovider {} -declare module 'web3-provider-engine/subproviders/subprovider' { - export = Subprovider; -} -declare module 'web3-provider-engine/subproviders/rpc' { - import { JSONRPCRequestPayload } from '@0xproject/types'; - class RpcSubprovider { - constructor(options: { rpcUrl: string }); - public handleRequest( - payload: JSONRPCRequestPayload, - next: () => void, - end: (err: Error | null, data?: any) => void, - ): void; - } - export = RpcSubprovider; -} - -declare interface Artifact { - abi: any; - networks: { - [networkId: number]: { - address: string; - }; - }; -} diff --git a/packages/website/ts/types.ts b/packages/website/ts/types.ts index 901483327..dba59f704 100644 --- a/packages/website/ts/types.ts +++ b/packages/website/ts/types.ts @@ -490,4 +490,12 @@ export interface TokenState { allowance: BigNumber; isLoaded: boolean; } + +export interface RelayerInfo { + headerUrl: string; + id: string; + name: string; + marketShare: number; + topTokens: Token[]; +} // tslint:disable:max-file-line-count diff --git a/packages/website/ts/utils/utils.ts b/packages/website/ts/utils/utils.ts index 75597a7e2..afe159beb 100644 --- a/packages/website/ts/utils/utils.ts +++ b/packages/website/ts/utils/utils.ts @@ -1,5 +1,6 @@ -import { ECSignature, ExchangeContractErrs, Web3Provider, ZeroEx, ZeroExError } from '0x.js'; +import { ECSignature, ExchangeContractErrs, ZeroEx, ZeroExError } from '0x.js'; import { constants as sharedConstants, EtherscanLinkSuffixes, Networks } from '@0xproject/react-shared'; +import { Provider } from '@0xproject/types'; import { BigNumber } from '@0xproject/utils'; import deepEqual = require('deep-equal'); import * as _ from 'lodash'; @@ -8,7 +9,6 @@ import { Order, Providers, ScreenWidths, Side, SideToAssetToken, Token, TokenByA import { configs } from 'ts/utils/configs'; import { constants } from 'ts/utils/constants'; import * as u2f from 'ts/vendor/u2f_api'; -import Web3 = require('web3'); const LG_MIN_EM = 64; const MD_MIN_EM = 52; @@ -273,7 +273,7 @@ export const utils = { window.onload = () => resolve(); }); }, - getProviderType(provider: Web3.Provider): Providers | string { + getProviderType(provider: Provider): Providers | string { const constructorName = provider.constructor.name; let parsedProviderName = constructorName; switch (constructorName) { |