diff options
author | Fabio Berger <me@fabioberger.com> | 2017-12-16 02:37:03 +0800 |
---|---|---|
committer | Fabio Berger <me@fabioberger.com> | 2017-12-16 02:37:03 +0800 |
commit | b46dd2e0a277340c19fa137a436981cc53c8cb80 (patch) | |
tree | d2814176fe8ffc5ec6a61534aa77487aae6bcc13 /packages | |
parent | 484dd4c33aa5786def1f0b159f5b51f99a585aa8 (diff) | |
parent | 3eb08735d4d0fe4b046dd6b74f5ed503cf5c64e3 (diff) | |
download | dexon-0x-contracts-b46dd2e0a277340c19fa137a436981cc53c8cb80.tar.gz dexon-0x-contracts-b46dd2e0a277340c19fa137a436981cc53c8cb80.tar.zst dexon-0x-contracts-b46dd2e0a277340c19fa137a436981cc53c8cb80.zip |
Merge branch 'development' into createWethPage
* development: (54 commits)
Fix redundant spaces
Fix tests
Fix website unused vars
Fix connect unused vars
Fix 0x.js unused vars
Dissallow unused vars/imports
Implement first custom linter rule async-suffix
Reuse intervalutils in website
Add a newline
Name a variable
Add a comment
Fix a conditional
Make migrations deterministic
Fix linter error
Fix linter errors
Add a function to init token balances
Rename tokenUtils.getNonProtocolTokens to tokenUtils.getDummyTokens
Add DummyToken to gitignore
Add DummyToken to artifacts list
Increase mocha timeout
...
Diffstat (limited to 'packages')
213 files changed, 1887 insertions, 2955 deletions
diff --git a/packages/abi-gen-templates/contract.mustache b/packages/0x.js/contract_templates/contract.mustache index ec06df507..693fbe4ee 100644 --- a/packages/abi-gen-templates/contract.mustache +++ b/packages/0x.js/contract_templates/contract.mustache @@ -2,13 +2,12 @@ * This file is auto-generated using abi-gen. Don't edit directly. * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. */ -import {promisify} from '@0xproject/utils'; +// tslint:disable-next-line:no-unused-variable +import {TxData, TxDataPayable} from '@0xproject/types'; +import {classUtils, promisify} from '@0xproject/utils'; import {BigNumber} from 'bignumber.js'; import * as Web3 from 'web3'; -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - import {BaseContract} from './base_contract'; export class {{contractName}}Contract extends BaseContract { diff --git a/packages/abi-gen-templates/partials/call.mustache b/packages/0x.js/contract_templates/partials/call.mustache index ef4bda724..ef4bda724 100644 --- a/packages/abi-gen-templates/partials/call.mustache +++ b/packages/0x.js/contract_templates/partials/call.mustache diff --git a/packages/abi-gen-templates/partials/params.mustache b/packages/0x.js/contract_templates/partials/params.mustache index ac5d4ae85..ac5d4ae85 100644 --- a/packages/abi-gen-templates/partials/params.mustache +++ b/packages/0x.js/contract_templates/partials/params.mustache diff --git a/packages/abi-gen-templates/partials/return_type.mustache b/packages/0x.js/contract_templates/partials/return_type.mustache index 383961a40..383961a40 100644 --- a/packages/abi-gen-templates/partials/return_type.mustache +++ b/packages/0x.js/contract_templates/partials/return_type.mustache diff --git a/packages/abi-gen-templates/partials/tx.mustache b/packages/0x.js/contract_templates/partials/tx.mustache index 8a43e5319..8a43e5319 100644 --- a/packages/abi-gen-templates/partials/tx.mustache +++ b/packages/0x.js/contract_templates/partials/tx.mustache diff --git a/packages/abi-gen-templates/partials/typed_params.mustache b/packages/0x.js/contract_templates/partials/typed_params.mustache index 3ea4b2e95..3ea4b2e95 100644 --- a/packages/abi-gen-templates/partials/typed_params.mustache +++ b/packages/0x.js/contract_templates/partials/typed_params.mustache diff --git a/packages/0x.js/package.json b/packages/0x.js/package.json index 62f9ed0f5..fcb08646a 100644 --- a/packages/0x.js/package.json +++ b/packages/0x.js/package.json @@ -12,11 +12,11 @@ "main": "lib/src/index.js", "types": "lib/src/index.d.ts", "scripts": { - "prebuild": "npm run clean", + "prebuild": "run-s clean generate_contract_wrappers", "build": "run-p build:umd:prod build:commonjs; exit 0;", "docs:json": "typedoc --excludePrivate --excludeExternals --target ES5 --json $JSON_FILE_PATH $PROJECT_DIR", "upload_docs_json": "aws s3 cp generated_docs/index.json $S3_URL --profile 0xproject --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --content-type application/json", - "generate_contract_wrappers": "abi-gen --abiGlob 'src/artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry).json' --templates ../abi-gen-templates/ --output src/contract_wrappers/generated --fileExtension ts", + "generate_contract_wrappers": "node ../abi-gen/lib/index.js --abiGlob 'src/artifacts/@(Exchange|Token|TokenTransferProxy|EtherToken|TokenRegistry|DummyToken).json' --templates contract_templates --output src/contract_wrappers/generated", "lint": "tslint --project . 'src/**/*.ts' 'test/**/*.ts'", "test:circleci": "run-s test:coverage report_test_coverage && if [ $CIRCLE_BRANCH = \"development\" ]; then yarn test:umd; fi", "test": "run-s clean test:commonjs", @@ -31,7 +31,7 @@ "test:commonjs": "run-s build:commonjs run_mocha", "pretest:umd": "run-s clean build:umd:dev build:commonjs", "substitute_umd_bundle": "shx mv _bundles/* lib/src", - "run_mocha": "mocha lib/test/**/*_test.js --timeout 5000 --bail --exit" + "run_mocha": "mocha lib/test/**/*_test.js --timeout 10000 --bail --exit" }, "config": { "artifacts": "TokenTransferProxy Exchange TokenRegistry Token EtherToken" @@ -48,6 +48,7 @@ "@0xproject/abi-gen": "^0.0.2", "@0xproject/tslint-config": "^0.2.1", "@0xproject/types": "^0.1.0", + "@0xproject/dev-utils": "^0.0.1", "@types/bintrees": "^1.0.2", "@types/jsonschema": "^1.1.1", "@types/lodash": "^4.14.86", @@ -55,7 +56,6 @@ "@types/node": "^8.0.53", "@types/sinon": "^2.2.2", "@types/uuid": "^3.4.2", - "abi-gen-templates": "^0.0.2", "awesome-typescript-loader": "^3.1.3", "chai": "^4.0.1", "chai-as-promised": "^7.1.0", @@ -78,8 +78,6 @@ "truffle-hdwallet-provider": "^0.0.3", "tslint": "5.8.0", "typedoc": "~0.8.0", - "types-bn": "^0.0.1", - "types-ethereumjs-util": "0xProject/types-ethereumjs-util", "typescript": "~2.6.1", "web3-provider-engine": "^13.0.1", "web3-typescript-typings": "^0.7.2", diff --git a/packages/0x.js/src/0x.ts b/packages/0x.js/src/0x.ts index 935e4ac1a..5a2d6cb05 100644 --- a/packages/0x.js/src/0x.ts +++ b/packages/0x.js/src/0x.ts @@ -1,11 +1,11 @@ import {schemas, SchemaValidator} from '@0xproject/json-schemas'; +import {bigNumberConfigs, intervalUtils} from '@0xproject/utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import BigNumber from 'bignumber.js'; import * as ethUtil from 'ethereumjs-util'; import * as _ from 'lodash'; import {artifacts} from './artifacts'; -import {bigNumberConfigs} from './bignumber_config'; import {EtherTokenWrapper} from './contract_wrappers/ether_token_wrapper'; import {ExchangeWrapper} from './contract_wrappers/exchange_wrapper'; import {TokenRegistryWrapper} from './contract_wrappers/token_registry_wrapper'; @@ -16,7 +16,6 @@ import {zeroExConfigSchema} from './schemas/zero_ex_config_schema'; import { ECSignature, Order, - OrderStateWatcherConfig, SignedOrder, TransactionReceiptWithDecodedLogs, Web3Provider, @@ -26,8 +25,6 @@ import { import {AbiDecoder} from './utils/abi_decoder'; import {assert} from './utils/assert'; import {constants} from './utils/constants'; -import {intervalUtils} from './utils/interval_utils'; -import {OrderStateUtils} from './utils/order_state_utils'; import {signatureUtils} from './utils/signature_utils'; import {utils} from './utils/utils'; diff --git a/packages/0x.js/src/artifacts.ts b/packages/0x.js/src/artifacts.ts index de2030812..7219ac8e2 100644 --- a/packages/0x.js/src/artifacts.ts +++ b/packages/0x.js/src/artifacts.ts @@ -1,3 +1,4 @@ +import * as DummyTokenArtifact from './artifacts/DummyToken.json'; import * as EtherTokenArtifact from './artifacts/EtherToken.json'; import * as ExchangeArtifact from './artifacts/Exchange.json'; import * as TokenArtifact from './artifacts/Token.json'; @@ -8,6 +9,7 @@ import {Artifact} from './types'; export const artifacts = { ZRXArtifact: ZRXArtifact as any as Artifact, + DummyTokenArtifact: DummyTokenArtifact as any as Artifact, TokenArtifact: TokenArtifact as any as Artifact, ExchangeArtifact: ExchangeArtifact as any as Artifact, EtherTokenArtifact: EtherTokenArtifact as any as Artifact, diff --git a/packages/0x.js/src/artifacts/DummyToken.json b/packages/0x.js/src/artifacts/DummyToken.json new file mode 100644 index 000000000..fd44397db --- /dev/null +++ b/packages/0x.js/src/artifacts/DummyToken.json @@ -0,0 +1,23 @@ +{ + "contract_name": "DummyToken", + "abi": + [ + { + "constant": false, + "inputs": [ + { + "name": "_target", + "type": "address" + }, + { + "name": "_value", + "type": "uint256" + } + ], + "name": "setBalance", + "outputs": [], + "payable": false, + "type": "function" + } + ] +} diff --git a/packages/0x.js/src/artifacts/EtherToken.json b/packages/0x.js/src/artifacts/EtherToken.json index 8c1d0f499..de6946cf2 100644 --- a/packages/0x.js/src/artifacts/EtherToken.json +++ b/packages/0x.js/src/artifacts/EtherToken.json @@ -244,7 +244,7 @@ "address": "0x05d090b51c40b020eab3bfcb6a2dff130df22e9c" }, "50": { - "address": "0x48bacb9266a570d521063ef5dd96e61686dbe788" + "address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c" } } } diff --git a/packages/0x.js/src/artifacts/Exchange.json b/packages/0x.js/src/artifacts/Exchange.json index 25495a041..cf9124ca7 100644 --- a/packages/0x.js/src/artifacts/Exchange.json +++ b/packages/0x.js/src/artifacts/Exchange.json @@ -601,7 +601,7 @@ "address": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364" }, "50": { - "address": "0xb69e673309512a9d726f87304c6984054f87a93b" + "address": "0x48bacb9266a570d521063ef5dd96e61686dbe788" } } } diff --git a/packages/0x.js/src/artifacts/TokenTransferProxy.json b/packages/0x.js/src/artifacts/TokenTransferProxy.json index 065343919..023f39bdf 100644 --- a/packages/0x.js/src/artifacts/TokenTransferProxy.json +++ b/packages/0x.js/src/artifacts/TokenTransferProxy.json @@ -178,7 +178,7 @@ "address": "0x087eed4bc1ee3de49befbd66c662b434b15d49d4" }, "50": { - "address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c" + "address": "0x1dc4c1cefef38a777b15aa20260a54e584b16c48" } } } diff --git a/packages/0x.js/src/artifacts/ZRX.json b/packages/0x.js/src/artifacts/ZRX.json index 7da67fde0..a9fe1799a 100644 --- a/packages/0x.js/src/artifacts/ZRX.json +++ b/packages/0x.js/src/artifacts/ZRX.json @@ -11,7 +11,7 @@ "address": "0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570" }, "50": { - "address": "0x25b8fe1de9daf8ba351890744ff28cf7dfa8f5e3" + "address": "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401" } } } diff --git a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts index 5caf06db2..a796dc1ec 100644 --- a/packages/0x.js/src/contract_wrappers/contract_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/contract_wrapper.ts @@ -1,3 +1,4 @@ +import {intervalUtils} from '@0xproject/utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import {Block, BlockAndLogStreamer} from 'ethereumjs-blockstream'; import * as _ from 'lodash'; @@ -19,7 +20,6 @@ import { import {AbiDecoder} from '../utils/abi_decoder'; import {constants} from '../utils/constants'; import {filterUtils} from '../utils/filter_utils'; -import {intervalUtils} from '../utils/interval_utils'; const CONTRACT_NAME_TO_NOT_FOUND_ERROR: {[contractName: string]: ZeroExError} = { ZRX: ZeroExError.ZRXContractDoesNotExist, diff --git a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts index 1e9865395..9bed40079 100644 --- a/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/exchange_wrapper.ts @@ -15,9 +15,7 @@ import { ExchangeContractEventArgs, ExchangeEvents, IndexedFilterValues, - LogCancelContractEventArgs, LogErrorContractEventArgs, - LogFillContractEventArgs, LogWithDecodedArgs, MethodOpts, Order, @@ -26,7 +24,6 @@ import { OrderFillRequest, OrderTransactionOpts, OrderValues, - RawLog, SignedOrder, SubscriptionOpts, ValidateOrderFillableOpts, @@ -88,7 +85,7 @@ export class ExchangeWrapper extends ContractWrapper { tokenWrapper: TokenWrapper, contractAddressIfExists?: string) { super(web3Wrapper, networkId, abiDecoder); this._tokenWrapper = tokenWrapper; - this._orderValidationUtils = new OrderValidationUtils(tokenWrapper, this); + this._orderValidationUtils = new OrderValidationUtils(this); this._contractAddressIfExists = contractAddressIfExists; } /** diff --git a/packages/0x.js/src/contract_wrappers/generated/.gitignore b/packages/0x.js/src/contract_wrappers/generated/.gitignore new file mode 100644 index 000000000..834808b48 --- /dev/null +++ b/packages/0x.js/src/contract_wrappers/generated/.gitignore @@ -0,0 +1,6 @@ +dummy_token.ts +ether_token.ts +exchange.ts +token_registry.ts +token_transfer_proxy.ts +token.ts diff --git a/packages/0x.js/src/contract_wrappers/generated/base_contract.ts b/packages/0x.js/src/contract_wrappers/generated/base_contract.ts index 396a4d593..28a7e2f52 100644 --- a/packages/0x.js/src/contract_wrappers/generated/base_contract.ts +++ b/packages/0x.js/src/contract_wrappers/generated/base_contract.ts @@ -1,8 +1,7 @@ +import {TxData, TxDataPayable} from '@0xproject/types'; import * as _ from 'lodash'; import * as Web3 from 'web3'; -import {TxData, TxDataPayable} from '../../types'; - export class BaseContract { protected web3ContractInstance: Web3.ContractInstance; protected defaults: Partial<TxData>; diff --git a/packages/0x.js/src/contract_wrappers/generated/ether_token.ts b/packages/0x.js/src/contract_wrappers/generated/ether_token.ts deleted file mode 100644 index ce3f9f527..000000000 --- a/packages/0x.js/src/contract_wrappers/generated/ether_token.ts +++ /dev/null @@ -1,363 +0,0 @@ -/** - * This file is auto-generated using abi-gen. Don't edit directly. - * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. - */ -import {promisify} from '@0xproject/utils'; -import {BigNumber} from 'bignumber.js'; -import * as Web3 from 'web3'; - -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - -import {BaseContract} from './base_contract'; - -export class EtherTokenContract extends BaseContract { - public name = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as EtherTokenContract; - const result = await promisify<string - >( - self.web3ContractInstance.name.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public approve = { - async sendTransactionAsync( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.approve.estimateGasAsync.bind( - self, - _spender, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.approve, self.web3ContractInstance, - )( - _spender, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.approve.estimateGas, self.web3ContractInstance, - )( - _spender, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as EtherTokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.approve.getData(); - return abiEncodedTransactionData; - }, - }; - public totalSupply = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as EtherTokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.totalSupply.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public transferFrom = { - async sendTransactionAsync( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transferFrom.estimateGasAsync.bind( - self, - _from, - _to, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transferFrom, self.web3ContractInstance, - )( - _from, - _to, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transferFrom.estimateGas, self.web3ContractInstance, - )( - _from, - _to, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as EtherTokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.transferFrom.getData(); - return abiEncodedTransactionData; - }, - }; - public withdraw = { - async sendTransactionAsync( - amount: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.withdraw.estimateGasAsync.bind( - self, - amount, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.withdraw, self.web3ContractInstance, - )( - amount, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - amount: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.withdraw.estimateGas, self.web3ContractInstance, - )( - amount, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - amount: BigNumber, - txData: TxData = {}, - ): string { - const self = this as EtherTokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.withdraw.getData(); - return abiEncodedTransactionData; - }, - }; - public decimals = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as EtherTokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.decimals.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public balanceOf = { - async callAsync( - _owner: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as EtherTokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.balanceOf.call, - self.web3ContractInstance, - )( - _owner, - ); - return result; - }, - }; - public symbol = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as EtherTokenContract; - const result = await promisify<string - >( - self.web3ContractInstance.symbol.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public transfer = { - async sendTransactionAsync( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transfer.estimateGasAsync.bind( - self, - _to, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transfer, self.web3ContractInstance, - )( - _to, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transfer.estimateGas, self.web3ContractInstance, - )( - _to, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as EtherTokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.transfer.getData(); - return abiEncodedTransactionData; - }, - }; - public deposit = { - async sendTransactionAsync( - txData: TxDataPayable = {}, - ): Promise<string> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.deposit.estimateGasAsync.bind( - self, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.deposit, self.web3ContractInstance, - )( - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - txData: TxData = {}, - ): Promise<number> { - const self = this as EtherTokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.deposit.estimateGas, self.web3ContractInstance, - )( - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - txData: TxData = {}, - ): string { - const self = this as EtherTokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.deposit.getData(); - return abiEncodedTransactionData; - }, - }; - public allowance = { - async callAsync( - _owner: string, - _spender: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as EtherTokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.allowance.call, - self.web3ContractInstance, - )( - _owner, - _spender, - ); - return result; - }, - }; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { - super(web3ContractInstance, defaults); - classUtils.bindAll(this, ['web3ContractInstance', 'defaults']); - } -} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/generated/exchange.ts b/packages/0x.js/src/contract_wrappers/generated/exchange.ts deleted file mode 100644 index e06ed960c..000000000 --- a/packages/0x.js/src/contract_wrappers/generated/exchange.ts +++ /dev/null @@ -1,730 +0,0 @@ -/** - * This file is auto-generated using abi-gen. Don't edit directly. - * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. - */ -import {promisify} from '@0xproject/utils'; -import {BigNumber} from 'bignumber.js'; -import * as Web3 from 'web3'; - -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - -import {BaseContract} from './base_contract'; - -export class ExchangeContract extends BaseContract { - public isRoundingError = { - async callAsync( - numerator: BigNumber, - denominator: BigNumber, - target: BigNumber, - defaultBlock?: Web3.BlockParam, - ): Promise<boolean - > { - const self = this as ExchangeContract; - const result = await promisify<boolean - >( - self.web3ContractInstance.isRoundingError.call, - self.web3ContractInstance, - )( - numerator, - denominator, - target, - ); - return result; - }, - }; - public filled = { - async callAsync( - index: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as ExchangeContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.filled.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public cancelled = { - async callAsync( - index: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as ExchangeContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.cancelled.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public fillOrdersUpTo = { - async sendTransactionAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.fillOrdersUpTo.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.fillOrdersUpTo, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.fillOrdersUpTo.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.fillOrdersUpTo.getData(); - return abiEncodedTransactionData; - }, - }; - public cancelOrder = { - async sendTransactionAsync( - orderAddresses: string[], - orderValues: BigNumber[], - cancelTakerTokenAmount: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.cancelOrder.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - cancelTakerTokenAmount, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.cancelOrder, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - cancelTakerTokenAmount, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[], - orderValues: BigNumber[], - cancelTakerTokenAmount: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.cancelOrder.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - cancelTakerTokenAmount, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[], - orderValues: BigNumber[], - cancelTakerTokenAmount: BigNumber, - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.cancelOrder.getData(); - return abiEncodedTransactionData; - }, - }; - public ZRX_TOKEN_CONTRACT = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as ExchangeContract; - const result = await promisify<string - >( - self.web3ContractInstance.ZRX_TOKEN_CONTRACT.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public batchFillOrKillOrders = { - async sendTransactionAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.batchFillOrKillOrders.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - fillTakerTokenAmounts, - v, - r, - s, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.batchFillOrKillOrders, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmounts, - v, - r, - s, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.batchFillOrKillOrders.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmounts, - v, - r, - s, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.batchFillOrKillOrders.getData(); - return abiEncodedTransactionData; - }, - }; - public fillOrKillOrder = { - async sendTransactionAsync( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.fillOrKillOrder.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - fillTakerTokenAmount, - v, - r, - s, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.fillOrKillOrder, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - v, - r, - s, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.fillOrKillOrder.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - v, - r, - s, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.fillOrKillOrder.getData(); - return abiEncodedTransactionData; - }, - }; - public getUnavailableTakerTokenAmount = { - async callAsync( - orderHash: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as ExchangeContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.getUnavailableTakerTokenAmount.call, - self.web3ContractInstance, - )( - orderHash, - ); - return result; - }, - }; - public isValidSignature = { - async callAsync( - signer: string, - hash: string, - v: number|BigNumber, - r: string, - s: string, - defaultBlock?: Web3.BlockParam, - ): Promise<boolean - > { - const self = this as ExchangeContract; - const result = await promisify<boolean - >( - self.web3ContractInstance.isValidSignature.call, - self.web3ContractInstance, - )( - signer, - hash, - v, - r, - s, - ); - return result; - }, - }; - public getPartialAmount = { - async callAsync( - numerator: BigNumber, - denominator: BigNumber, - target: BigNumber, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as ExchangeContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.getPartialAmount.call, - self.web3ContractInstance, - )( - numerator, - denominator, - target, - ); - return result; - }, - }; - public TOKEN_TRANSFER_PROXY_CONTRACT = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as ExchangeContract; - const result = await promisify<string - >( - self.web3ContractInstance.TOKEN_TRANSFER_PROXY_CONTRACT.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public batchFillOrders = { - async sendTransactionAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.batchFillOrders.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - fillTakerTokenAmounts, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.batchFillOrders, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmounts, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.batchFillOrders.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmounts, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[][], - orderValues: BigNumber[][], - fillTakerTokenAmounts: BigNumber[], - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber[], - r: string[], - s: string[], - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.batchFillOrders.getData(); - return abiEncodedTransactionData; - }, - }; - public batchCancelOrders = { - async sendTransactionAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - cancelTakerTokenAmounts: BigNumber[], - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.batchCancelOrders.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - cancelTakerTokenAmounts, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.batchCancelOrders, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - cancelTakerTokenAmounts, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[][], - orderValues: BigNumber[][], - cancelTakerTokenAmounts: BigNumber[], - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.batchCancelOrders.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - cancelTakerTokenAmounts, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[][], - orderValues: BigNumber[][], - cancelTakerTokenAmounts: BigNumber[], - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.batchCancelOrders.getData(); - return abiEncodedTransactionData; - }, - }; - public fillOrder = { - async sendTransactionAsync( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.fillOrder.estimateGasAsync.bind( - self, - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.fillOrder, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as ExchangeContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.fillOrder.estimateGas, self.web3ContractInstance, - )( - orderAddresses, - orderValues, - fillTakerTokenAmount, - shouldThrowOnInsufficientBalanceOrAllowance, - v, - r, - s, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - orderAddresses: string[], - orderValues: BigNumber[], - fillTakerTokenAmount: BigNumber, - shouldThrowOnInsufficientBalanceOrAllowance: boolean, - v: number|BigNumber, - r: string, - s: string, - txData: TxData = {}, - ): string { - const self = this as ExchangeContract; - const abiEncodedTransactionData = self.web3ContractInstance.fillOrder.getData(); - return abiEncodedTransactionData; - }, - }; - public getOrderHash = { - async callAsync( - orderAddresses: string[], - orderValues: BigNumber[], - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as ExchangeContract; - const result = await promisify<string - >( - self.web3ContractInstance.getOrderHash.call, - self.web3ContractInstance, - )( - orderAddresses, - orderValues, - ); - return result; - }, - }; - public EXTERNAL_QUERY_GAS_LIMIT = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as ExchangeContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.EXTERNAL_QUERY_GAS_LIMIT.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public VERSION = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as ExchangeContract; - const result = await promisify<string - >( - self.web3ContractInstance.VERSION.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { - super(web3ContractInstance, defaults); - classUtils.bindAll(this, ['web3ContractInstance', 'defaults']); - } -} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/generated/token.ts b/packages/0x.js/src/contract_wrappers/generated/token.ts deleted file mode 100644 index 83a4ead34..000000000 --- a/packages/0x.js/src/contract_wrappers/generated/token.ts +++ /dev/null @@ -1,232 +0,0 @@ -/** - * This file is auto-generated using abi-gen. Don't edit directly. - * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. - */ -import {promisify} from '@0xproject/utils'; -import {BigNumber} from 'bignumber.js'; -import * as Web3 from 'web3'; - -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - -import {BaseContract} from './base_contract'; - -export class TokenContract extends BaseContract { - public approve = { - async sendTransactionAsync( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.approve.estimateGasAsync.bind( - self, - _spender, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.approve, self.web3ContractInstance, - )( - _spender, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.approve.estimateGas, self.web3ContractInstance, - )( - _spender, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _spender: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as TokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.approve.getData(); - return abiEncodedTransactionData; - }, - }; - public totalSupply = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as TokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.totalSupply.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public transferFrom = { - async sendTransactionAsync( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transferFrom.estimateGasAsync.bind( - self, - _from, - _to, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transferFrom, self.web3ContractInstance, - )( - _from, - _to, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transferFrom.estimateGas, self.web3ContractInstance, - )( - _from, - _to, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _from: string, - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as TokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.transferFrom.getData(); - return abiEncodedTransactionData; - }, - }; - public balanceOf = { - async callAsync( - _owner: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as TokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.balanceOf.call, - self.web3ContractInstance, - )( - _owner, - ); - return result; - }, - }; - public transfer = { - async sendTransactionAsync( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transfer.estimateGasAsync.bind( - self, - _to, - _value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transfer, self.web3ContractInstance, - )( - _to, - _value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transfer.estimateGas, self.web3ContractInstance, - )( - _to, - _value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _to: string, - _value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as TokenContract; - const abiEncodedTransactionData = self.web3ContractInstance.transfer.getData(); - return abiEncodedTransactionData; - }, - }; - public allowance = { - async callAsync( - _owner: string, - _spender: string, - defaultBlock?: Web3.BlockParam, - ): Promise<BigNumber - > { - const self = this as TokenContract; - const result = await promisify<BigNumber - >( - self.web3ContractInstance.allowance.call, - self.web3ContractInstance, - )( - _owner, - _spender, - ); - return result; - }, - }; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { - super(web3ContractInstance, defaults); - classUtils.bindAll(this, ['web3ContractInstance', 'defaults']); - } -} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/generated/token_registry.ts b/packages/0x.js/src/contract_wrappers/generated/token_registry.ts deleted file mode 100644 index 5d9ad9016..000000000 --- a/packages/0x.js/src/contract_wrappers/generated/token_registry.ts +++ /dev/null @@ -1,550 +0,0 @@ -/** - * This file is auto-generated using abi-gen. Don't edit directly. - * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. - */ -import {promisify} from '@0xproject/utils'; -import {BigNumber} from 'bignumber.js'; -import * as Web3 from 'web3'; - -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - -import {BaseContract} from './base_contract'; - -export class TokenRegistryContract extends BaseContract { - public removeToken = { - async sendTransactionAsync( - _token: string, - _index: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.removeToken.estimateGasAsync.bind( - self, - _token, - _index, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.removeToken, self.web3ContractInstance, - )( - _token, - _index, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _index: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.removeToken.estimateGas, self.web3ContractInstance, - )( - _token, - _index, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _index: BigNumber, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.removeToken.getData(); - return abiEncodedTransactionData; - }, - }; - public getTokenAddressByName = { - async callAsync( - _name: string, - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenRegistryContract; - const result = await promisify<string - >( - self.web3ContractInstance.getTokenAddressByName.call, - self.web3ContractInstance, - )( - _name, - ); - return result; - }, - }; - public getTokenAddressBySymbol = { - async callAsync( - _symbol: string, - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenRegistryContract; - const result = await promisify<string - >( - self.web3ContractInstance.getTokenAddressBySymbol.call, - self.web3ContractInstance, - )( - _symbol, - ); - return result; - }, - }; - public setTokenSwarmHash = { - async sendTransactionAsync( - _token: string, - _swarmHash: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.setTokenSwarmHash.estimateGasAsync.bind( - self, - _token, - _swarmHash, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.setTokenSwarmHash, self.web3ContractInstance, - )( - _token, - _swarmHash, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _swarmHash: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.setTokenSwarmHash.estimateGas, self.web3ContractInstance, - )( - _token, - _swarmHash, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _swarmHash: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.setTokenSwarmHash.getData(); - return abiEncodedTransactionData; - }, - }; - public getTokenMetaData = { - async callAsync( - _token: string, - defaultBlock?: Web3.BlockParam, - ): Promise<[string, string, string, BigNumber, string, string] - > { - const self = this as TokenRegistryContract; - const result = await promisify<[string, string, string, BigNumber, string, string] - >( - self.web3ContractInstance.getTokenMetaData.call, - self.web3ContractInstance, - )( - _token, - ); - return result; - }, - }; - public owner = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenRegistryContract; - const result = await promisify<string - >( - self.web3ContractInstance.owner.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public addToken = { - async sendTransactionAsync( - _token: string, - _name: string, - _symbol: string, - _decimals: number|BigNumber, - _ipfsHash: string, - _swarmHash: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.addToken.estimateGasAsync.bind( - self, - _token, - _name, - _symbol, - _decimals, - _ipfsHash, - _swarmHash, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.addToken, self.web3ContractInstance, - )( - _token, - _name, - _symbol, - _decimals, - _ipfsHash, - _swarmHash, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _name: string, - _symbol: string, - _decimals: number|BigNumber, - _ipfsHash: string, - _swarmHash: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.addToken.estimateGas, self.web3ContractInstance, - )( - _token, - _name, - _symbol, - _decimals, - _ipfsHash, - _swarmHash, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _name: string, - _symbol: string, - _decimals: number|BigNumber, - _ipfsHash: string, - _swarmHash: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.addToken.getData(); - return abiEncodedTransactionData; - }, - }; - public setTokenName = { - async sendTransactionAsync( - _token: string, - _name: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.setTokenName.estimateGasAsync.bind( - self, - _token, - _name, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.setTokenName, self.web3ContractInstance, - )( - _token, - _name, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _name: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.setTokenName.estimateGas, self.web3ContractInstance, - )( - _token, - _name, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _name: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.setTokenName.getData(); - return abiEncodedTransactionData; - }, - }; - public tokens = { - async callAsync( - index: string, - defaultBlock?: Web3.BlockParam, - ): Promise<[string, string, string, BigNumber, string, string] - > { - const self = this as TokenRegistryContract; - const result = await promisify<[string, string, string, BigNumber, string, string] - >( - self.web3ContractInstance.tokens.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public tokenAddresses = { - async callAsync( - index: BigNumber, - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenRegistryContract; - const result = await promisify<string - >( - self.web3ContractInstance.tokenAddresses.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public getTokenByName = { - async callAsync( - _name: string, - defaultBlock?: Web3.BlockParam, - ): Promise<[string, string, string, BigNumber, string, string] - > { - const self = this as TokenRegistryContract; - const result = await promisify<[string, string, string, BigNumber, string, string] - >( - self.web3ContractInstance.getTokenByName.call, - self.web3ContractInstance, - )( - _name, - ); - return result; - }, - }; - public getTokenAddresses = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string[] - > { - const self = this as TokenRegistryContract; - const result = await promisify<string[] - >( - self.web3ContractInstance.getTokenAddresses.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public setTokenIpfsHash = { - async sendTransactionAsync( - _token: string, - _ipfsHash: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.setTokenIpfsHash.estimateGasAsync.bind( - self, - _token, - _ipfsHash, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.setTokenIpfsHash, self.web3ContractInstance, - )( - _token, - _ipfsHash, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _ipfsHash: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.setTokenIpfsHash.estimateGas, self.web3ContractInstance, - )( - _token, - _ipfsHash, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _ipfsHash: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.setTokenIpfsHash.getData(); - return abiEncodedTransactionData; - }, - }; - public getTokenBySymbol = { - async callAsync( - _symbol: string, - defaultBlock?: Web3.BlockParam, - ): Promise<[string, string, string, BigNumber, string, string] - > { - const self = this as TokenRegistryContract; - const result = await promisify<[string, string, string, BigNumber, string, string] - >( - self.web3ContractInstance.getTokenBySymbol.call, - self.web3ContractInstance, - )( - _symbol, - ); - return result; - }, - }; - public setTokenSymbol = { - async sendTransactionAsync( - _token: string, - _symbol: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.setTokenSymbol.estimateGasAsync.bind( - self, - _token, - _symbol, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.setTokenSymbol, self.web3ContractInstance, - )( - _token, - _symbol, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - _token: string, - _symbol: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.setTokenSymbol.estimateGas, self.web3ContractInstance, - )( - _token, - _symbol, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - _token: string, - _symbol: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.setTokenSymbol.getData(); - return abiEncodedTransactionData; - }, - }; - public transferOwnership = { - async sendTransactionAsync( - newOwner: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transferOwnership.estimateGasAsync.bind( - self, - newOwner, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transferOwnership, self.web3ContractInstance, - )( - newOwner, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - newOwner: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenRegistryContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transferOwnership.estimateGas, self.web3ContractInstance, - )( - newOwner, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - newOwner: string, - txData: TxData = {}, - ): string { - const self = this as TokenRegistryContract; - const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData(); - return abiEncodedTransactionData; - }, - }; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { - super(web3ContractInstance, defaults); - classUtils.bindAll(this, ['web3ContractInstance', 'defaults']); - } -} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/generated/token_transfer_proxy.ts b/packages/0x.js/src/contract_wrappers/generated/token_transfer_proxy.ts deleted file mode 100644 index fd50a5894..000000000 --- a/packages/0x.js/src/contract_wrappers/generated/token_transfer_proxy.ts +++ /dev/null @@ -1,285 +0,0 @@ -/** - * This file is auto-generated using abi-gen. Don't edit directly. - * Templates can be found at https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates. - */ -import {promisify} from '@0xproject/utils'; -import {BigNumber} from 'bignumber.js'; -import * as Web3 from 'web3'; - -import {TxData, TxDataPayable} from '../../types'; -import {classUtils} from '../../utils/class_utils'; - -import {BaseContract} from './base_contract'; - -export class TokenTransferProxyContract extends BaseContract { - public transferFrom = { - async sendTransactionAsync( - token: string, - from: string, - to: string, - value: BigNumber, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transferFrom.estimateGasAsync.bind( - self, - token, - from, - to, - value, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transferFrom, self.web3ContractInstance, - )( - token, - from, - to, - value, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - token: string, - from: string, - to: string, - value: BigNumber, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transferFrom.estimateGas, self.web3ContractInstance, - )( - token, - from, - to, - value, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - token: string, - from: string, - to: string, - value: BigNumber, - txData: TxData = {}, - ): string { - const self = this as TokenTransferProxyContract; - const abiEncodedTransactionData = self.web3ContractInstance.transferFrom.getData(); - return abiEncodedTransactionData; - }, - }; - public addAuthorizedAddress = { - async sendTransactionAsync( - target: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.addAuthorizedAddress.estimateGasAsync.bind( - self, - target, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.addAuthorizedAddress, self.web3ContractInstance, - )( - target, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - target: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.addAuthorizedAddress.estimateGas, self.web3ContractInstance, - )( - target, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - target: string, - txData: TxData = {}, - ): string { - const self = this as TokenTransferProxyContract; - const abiEncodedTransactionData = self.web3ContractInstance.addAuthorizedAddress.getData(); - return abiEncodedTransactionData; - }, - }; - public authorities = { - async callAsync( - index: BigNumber, - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenTransferProxyContract; - const result = await promisify<string - >( - self.web3ContractInstance.authorities.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public removeAuthorizedAddress = { - async sendTransactionAsync( - target: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.removeAuthorizedAddress.estimateGasAsync.bind( - self, - target, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.removeAuthorizedAddress, self.web3ContractInstance, - )( - target, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - target: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.removeAuthorizedAddress.estimateGas, self.web3ContractInstance, - )( - target, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - target: string, - txData: TxData = {}, - ): string { - const self = this as TokenTransferProxyContract; - const abiEncodedTransactionData = self.web3ContractInstance.removeAuthorizedAddress.getData(); - return abiEncodedTransactionData; - }, - }; - public owner = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string - > { - const self = this as TokenTransferProxyContract; - const result = await promisify<string - >( - self.web3ContractInstance.owner.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public authorized = { - async callAsync( - index: string, - defaultBlock?: Web3.BlockParam, - ): Promise<boolean - > { - const self = this as TokenTransferProxyContract; - const result = await promisify<boolean - >( - self.web3ContractInstance.authorized.call, - self.web3ContractInstance, - )( - index, - ); - return result; - }, - }; - public getAuthorizedAddresses = { - async callAsync( - defaultBlock?: Web3.BlockParam, - ): Promise<string[] - > { - const self = this as TokenTransferProxyContract; - const result = await promisify<string[] - >( - self.web3ContractInstance.getAuthorizedAddresses.call, - self.web3ContractInstance, - )( - ); - return result; - }, - }; - public transferOwnership = { - async sendTransactionAsync( - newOwner: string, - txData: TxData = {}, - ): Promise<string> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - self.transferOwnership.estimateGasAsync.bind( - self, - newOwner, - ), - ); - const txHash = await promisify<string>( - self.web3ContractInstance.transferOwnership, self.web3ContractInstance, - )( - newOwner, - txDataWithDefaults, - ); - return txHash; - }, - async estimateGasAsync( - newOwner: string, - txData: TxData = {}, - ): Promise<number> { - const self = this as TokenTransferProxyContract; - const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( - txData, - ); - const gas = await promisify<number>( - self.web3ContractInstance.transferOwnership.estimateGas, self.web3ContractInstance, - )( - newOwner, - txDataWithDefaults, - ); - return gas; - }, - getABIEncodedTransactionData( - newOwner: string, - txData: TxData = {}, - ): string { - const self = this as TokenTransferProxyContract; - const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData(); - return abiEncodedTransactionData; - }, - }; - constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { - super(web3ContractInstance, defaults); - classUtils.bindAll(this, ['web3ContractInstance', 'defaults']); - } -} // tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts index 064b826d8..69e9d7e21 100644 --- a/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_registry_wrapper.ts @@ -2,7 +2,7 @@ import {Web3Wrapper} from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; import {artifacts} from '../artifacts'; -import {Token, TokenMetadata, ZeroExError} from '../types'; +import {Token, TokenMetadata} from '../types'; import {assert} from '../utils/assert'; import {constants} from '../utils/constants'; @@ -36,8 +36,6 @@ export class TokenRegistryWrapper extends ContractWrapper { * @return An array of objects that conform to the Token interface. */ public async getTokensAsync(): Promise<Token[]> { - const tokenRegistryContract = await this._getTokenRegistryContractAsync(); - const addresses = await this.getTokenAddressesAsync(); const tokenPromises: Array<Promise<Token|undefined>> = _.map( addresses, 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 1a16e3540..c67ef87df 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 @@ -2,7 +2,6 @@ import {Web3Wrapper} from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; import {artifacts} from '../artifacts'; -import {ZeroExError} from '../types'; import {ContractWrapper} from './contract_wrapper'; import {TokenTransferProxyContract} from './generated/token_transfer_proxy'; diff --git a/packages/0x.js/src/contract_wrappers/token_wrapper.ts b/packages/0x.js/src/contract_wrappers/token_wrapper.ts index 684f291a5..d1553fa7b 100644 --- a/packages/0x.js/src/contract_wrappers/token_wrapper.ts +++ b/packages/0x.js/src/contract_wrappers/token_wrapper.ts @@ -23,8 +23,6 @@ import {ContractWrapper} from './contract_wrapper'; import {TokenContract} from './generated/token'; import {TokenTransferProxyWrapper} from './token_transfer_proxy_wrapper'; -const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 47275; - /** * This class includes all the functionality related to interacting with ERC20 token contracts. * All ERC20 method calls are supported, along with some convenience methods for getting/setting allowances diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts index d4193a3e9..2f5296a9f 100644 --- a/packages/0x.js/src/index.ts +++ b/packages/0x.js/src/index.ts @@ -27,7 +27,6 @@ export { ContractEventArg, Web3Provider, ZeroExConfig, - TransactionReceipt, TransactionReceiptWithDecodedLogs, LogWithDecodedArgs, MethodOpts, @@ -42,3 +41,7 @@ export { OrderStateInvalid, OrderState, } from './types'; + +export { + TransactionReceipt, +} from '@0xproject/types'; diff --git a/packages/0x.js/src/order_watcher/event_watcher.ts b/packages/0x.js/src/order_watcher/event_watcher.ts index d5b30d567..197dfae65 100644 --- a/packages/0x.js/src/order_watcher/event_watcher.ts +++ b/packages/0x.js/src/order_watcher/event_watcher.ts @@ -1,17 +1,14 @@ +import {intervalUtils} from '@0xproject/utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; import * as Web3 from 'web3'; import { BlockParamLiteral, - EventCallback, EventWatcherCallback, ZeroExError, } from '../types'; -import {AbiDecoder} from '../utils/abi_decoder'; import {assert} from '../utils/assert'; -import {intervalUtils} from '../utils/interval_utils'; -import {utils} from '../utils/utils'; const DEFAULT_EVENT_POLLING_INTERVAL_MS = 200; diff --git a/packages/0x.js/src/order_watcher/expiration_watcher.ts b/packages/0x.js/src/order_watcher/expiration_watcher.ts index 9a1bb1ca4..91e8151fd 100644 --- a/packages/0x.js/src/order_watcher/expiration_watcher.ts +++ b/packages/0x.js/src/order_watcher/expiration_watcher.ts @@ -1,10 +1,9 @@ +import {intervalUtils} from '@0xproject/utils'; import {BigNumber} from 'bignumber.js'; import {RBTree} from 'bintrees'; import * as _ from 'lodash'; -import {ZeroEx} from '../0x'; -import {SignedOrder, ZeroExError} from '../types'; -import {intervalUtils} from '../utils/interval_utils'; +import {ZeroExError} from '../types'; import {utils} from '../utils/utils'; const DEFAULT_EXPIRATION_MARGIN_MS = 0; diff --git a/packages/0x.js/src/order_watcher/order_state_watcher.ts b/packages/0x.js/src/order_watcher/order_state_watcher.ts index 08f52d6e1..c4a9eb1ad 100644 --- a/packages/0x.js/src/order_watcher/order_state_watcher.ts +++ b/packages/0x.js/src/order_watcher/order_state_watcher.ts @@ -1,9 +1,9 @@ import {schemas} from '@0xproject/json-schemas'; +import {intervalUtils} from '@0xproject/utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; import {ZeroEx} from '../0x'; -import {artifacts} from '../artifacts'; import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; import {TokenWrapper} from '../contract_wrappers/token_wrapper'; import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store'; @@ -24,12 +24,10 @@ import { SignedOrder, TokenEvents, TransferContractEventArgs, - Web3Provider, ZeroExError, } from '../types'; import {AbiDecoder} from '../utils/abi_decoder'; import {assert} from '../utils/assert'; -import {intervalUtils} from '../utils/interval_utils'; import {OrderStateUtils} from '../utils/order_state_utils'; import {utils} from '../utils/utils'; diff --git a/packages/0x.js/src/stores/balance_proxy_allowance_lazy_store.ts b/packages/0x.js/src/stores/balance_proxy_allowance_lazy_store.ts index 6225e9e72..cde1ef095 100644 --- a/packages/0x.js/src/stores/balance_proxy_allowance_lazy_store.ts +++ b/packages/0x.js/src/stores/balance_proxy_allowance_lazy_store.ts @@ -1,6 +1,5 @@ import {BigNumber} from 'bignumber.js'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import {TokenWrapper} from '../contract_wrappers/token_wrapper'; import {BlockParamLiteral} from '../types'; diff --git a/packages/0x.js/src/stores/order_filled_cancelled_lazy_store.ts b/packages/0x.js/src/stores/order_filled_cancelled_lazy_store.ts index 28b32f9e2..b35355e38 100644 --- a/packages/0x.js/src/stores/order_filled_cancelled_lazy_store.ts +++ b/packages/0x.js/src/stores/order_filled_cancelled_lazy_store.ts @@ -1,6 +1,5 @@ import {BigNumber} from 'bignumber.js'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; import {BlockParamLiteral} from '../types'; diff --git a/packages/0x.js/src/types.ts b/packages/0x.js/src/types.ts index 3586919cb..f33e05bb8 100644 --- a/packages/0x.js/src/types.ts +++ b/packages/0x.js/src/types.ts @@ -1,3 +1,4 @@ +import {TransactionReceipt} from '@0xproject/types'; import BigNumber from 'bignumber.js'; import * as Web3 from 'web3'; @@ -385,28 +386,4 @@ export interface OrderStateInvalid { export type OrderState = OrderStateValid|OrderStateInvalid; export type OnOrderStateChangeCallback = (orderState: OrderState) => void; - -export interface TxData { - from?: string; - gas?: number; - gasPrice?: BigNumber; - nonce?: number; -} - -export interface TxDataPayable extends TxData { - value?: BigNumber; -} - -export interface TransactionReceipt { - blockHash: string; - blockNumber: number; - transactionHash: string; - transactionIndex: number; - from: string; - to: string; - status: null|0|1; - cumulativeGasUsed: number; - gasUsed: number; - contractAddress: string|null; - logs: Web3.LogEntry[]; -} // tslint:disable:max-file-line-count +// tslint:disable:max-file-line-count diff --git a/packages/0x.js/src/utils/assert.ts b/packages/0x.js/src/utils/assert.ts index 4cf6caf77..86a6a7c01 100644 --- a/packages/0x.js/src/utils/assert.ts +++ b/packages/0x.js/src/utils/assert.ts @@ -1,15 +1,15 @@ import {assert as sharedAssert} from '@0xproject/assert'; -import {Schema, SchemaValidator} from '@0xproject/json-schemas'; +// We need those two unused imports because they're actually used by sharedAssert which gets injected here +// tslint:disable-next-line:no-unused-variable +import {Schema} from '@0xproject/json-schemas'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; -import BigNumber from 'bignumber.js'; +// tslint:disable-next-line:no-unused-variable +import * as BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import {ECSignature} from '../types'; import {signatureUtils} from '../utils/signature_utils'; -const HEX_REGEX = /^0x[0-9A-F]*$/i; - export const assert = { ...sharedAssert, isValidSignature(orderHash: string, ecSignature: ECSignature, signerAddress: string) { diff --git a/packages/0x.js/src/utils/order_state_utils.ts b/packages/0x.js/src/utils/order_state_utils.ts index 6b7f811ae..a0985d028 100644 --- a/packages/0x.js/src/utils/order_state_utils.ts +++ b/packages/0x.js/src/utils/order_state_utils.ts @@ -1,24 +1,19 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import {ZeroEx} from '../0x'; import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; -import {TokenWrapper} from '../contract_wrappers/token_wrapper'; import {RemainingFillableCalculator} from '../order_watcher/remaining_fillable_calculator'; import {BalanceAndProxyAllowanceLazyStore} from '../stores/balance_proxy_allowance_lazy_store'; import {OrderFilledCancelledLazyStore} from '../stores/order_filled_cancelled_lazy_store'; import { ExchangeContractErrs, - MethodOpts, OrderRelevantState, OrderState, OrderStateInvalid, OrderStateValid, SignedOrder, } from '../types'; -import {constants} from '../utils/constants'; -import {utils} from '../utils/utils'; const ACCEPTABLE_RELATIVE_ROUNDING_ERROR = 0.0001; diff --git a/packages/0x.js/src/utils/order_validation_utils.ts b/packages/0x.js/src/utils/order_validation_utils.ts index d514483e0..9185eef2b 100644 --- a/packages/0x.js/src/utils/order_validation_utils.ts +++ b/packages/0x.js/src/utils/order_validation_utils.ts @@ -3,7 +3,6 @@ import * as _ from 'lodash'; import {ZeroEx} from '../0x'; import {ExchangeWrapper} from '../contract_wrappers/exchange_wrapper'; -import {TokenWrapper} from '../contract_wrappers/token_wrapper'; import {ExchangeContractErrs, Order, SignedOrder, TradeSide, TransferType, ZeroExError} from '../types'; import {constants} from '../utils/constants'; import {utils} from '../utils/utils'; @@ -11,7 +10,6 @@ import {utils} from '../utils/utils'; import {ExchangeTransferSimulator} from './exchange_transfer_simulator'; export class OrderValidationUtils { - private tokenWrapper: TokenWrapper; private exchangeWrapper: ExchangeWrapper; public static validateCancelOrderThrowIfInvalid( order: Order, cancelTakerTokenAmount: BigNumber, unavailableTakerTokenAmount: BigNumber, @@ -84,8 +82,7 @@ export class OrderValidationUtils { .round(0); return fillMakerTokenAmount; } - constructor(tokenWrapper: TokenWrapper, exchangeWrapper: ExchangeWrapper) { - this.tokenWrapper = tokenWrapper; + constructor(exchangeWrapper: ExchangeWrapper) { this.exchangeWrapper = exchangeWrapper; } public async validateOrderFillableOrThrowAsync( diff --git a/packages/0x.js/test/0x.js_test.ts b/packages/0x.js/test/0x.js_test.ts index 6b7a70699..e1ceb12c8 100644 --- a/packages/0x.js/test/0x.js_test.ts +++ b/packages/0x.js/test/0x.js_test.ts @@ -1,18 +1,18 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as _ from 'lodash'; import 'mocha'; import * as Sinon from 'sinon'; -import {ApprovalContractEventArgs, LogWithDecodedArgs, Order, TokenEvents, ZeroEx, ZeroExError} from '../src'; +import {ApprovalContractEventArgs, LogWithDecodedArgs, Order, TokenEvents, ZeroEx} from '../src'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {TokenUtils} from './utils/token_utils'; import {web3Factory} from './utils/web3_factory'; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); chaiSetup.configure(); const expect = chai.expect; diff --git a/packages/0x.js/test/artifacts_test.ts b/packages/0x.js/test/artifacts_test.ts index f4599a24d..d12346db3 100644 --- a/packages/0x.js/test/artifacts_test.ts +++ b/packages/0x.js/test/artifacts_test.ts @@ -1,4 +1,3 @@ -import * as chai from 'chai'; import * as fs from 'fs'; import HDWalletProvider = require('truffle-hdwallet-provider'); @@ -8,7 +7,6 @@ import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; chaiSetup.configure(); -const expect = chai.expect; // Those tests are slower cause they're talking to a remote node const TIMEOUT = 10000; diff --git a/packages/0x.js/test/ether_token_wrapper_test.ts b/packages/0x.js/test/ether_token_wrapper_test.ts index d3e4439ee..e0d738f84 100644 --- a/packages/0x.js/test/ether_token_wrapper_test.ts +++ b/packages/0x.js/test/ether_token_wrapper_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import 'mocha'; @@ -5,14 +6,13 @@ import * as Web3 from 'web3'; import {ZeroEx, ZeroExError} from '../src'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); // Since the address depositing/withdrawing ETH/WETH also needs to pay gas costs for the transaction, // a small amount of ETH will be used to pay this gas cost. We therefore check that the difference between diff --git a/packages/0x.js/test/event_watcher_test.ts b/packages/0x.js/test/event_watcher_test.ts index 3d92c62a3..95af99268 100644 --- a/packages/0x.js/test/event_watcher_test.ts +++ b/packages/0x.js/test/event_watcher_test.ts @@ -1,5 +1,4 @@ import {Web3Wrapper} from '@0xproject/web3-wrapper'; -import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as _ from 'lodash'; import 'mocha'; @@ -7,15 +6,12 @@ import * as Sinon from 'sinon'; import * as Web3 from 'web3'; import { - DecodedLogEvent, LogEvent, - ZeroEx, } from '../src'; import {EventWatcher} from '../src/order_watcher/event_watcher'; import {DoneCallback} from '../src/types'; import {chaiSetup} from './utils/chai_setup'; -import {constants} from './utils/constants'; import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); @@ -26,7 +22,6 @@ describe('EventWatcher', () => { let stubs: Sinon.SinonStub[] = []; let eventWatcher: EventWatcher; let web3Wrapper: Web3Wrapper; - const numConfirmations = 0; const logA: Web3.LogEntry = { address: '0x71d271f8b14adef568f8f28f1587ce7271ac4ca5', blockHash: null, diff --git a/packages/0x.js/test/exchange_transfer_simulator_test.ts b/packages/0x.js/test/exchange_transfer_simulator_test.ts index a1d9bdade..dbd1e99bd 100644 --- a/packages/0x.js/test/exchange_transfer_simulator_test.ts +++ b/packages/0x.js/test/exchange_transfer_simulator_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; @@ -5,14 +6,13 @@ import {ExchangeContractErrs, Token, ZeroEx} from '../src'; import {BlockParamLiteral, TradeSide, TransferType} from '../src/types'; import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); describe('ExchangeTransferSimulator', () => { const web3 = web3Factory.create(); diff --git a/packages/0x.js/test/exchange_wrapper_test.ts b/packages/0x.js/test/exchange_wrapper_test.ts index 14559c706..51b511dbf 100644 --- a/packages/0x.js/test/exchange_wrapper_test.ts +++ b/packages/0x.js/test/exchange_wrapper_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import 'mocha'; @@ -8,7 +9,6 @@ import { ExchangeContractErrs, ExchangeEvents, LogCancelContractEventArgs, - LogEvent, LogFillContractEventArgs, OrderCancellationRequest, OrderFillRequest, @@ -19,7 +19,6 @@ import { } from '../src'; import {BlockParamLiteral, DoneCallback} from '../src/types'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {FillScenarios} from './utils/fill_scenarios'; @@ -28,7 +27,7 @@ import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); const NON_EXISTENT_ORDER_HASH = '0x79370342234e7acd6bbeac335bd3bb1d368383294b64b8160a00f4060e4d3777'; @@ -53,6 +52,7 @@ describe('ExchangeWrapper', () => { tokenUtils = new TokenUtils(tokens); zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address; fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); + await fillScenarios.initTokenBalancesAsync(); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); @@ -71,7 +71,7 @@ describe('ExchangeWrapper', () => { before(async () => { [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; tokens = await zeroEx.tokenRegistry.getTokensAsync(); - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); @@ -201,7 +201,7 @@ describe('ExchangeWrapper', () => { before(async () => { [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; tokens = await zeroEx.tokenRegistry.getTokensAsync(); - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); @@ -436,7 +436,7 @@ describe('ExchangeWrapper', () => { const cancelAmount = new BigNumber(3); beforeEach(async () => { [coinbase, makerAddress, takerAddress] = userAddresses; - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; signedOrder = await fillScenarios.createFillableSignedOrderAsync( @@ -557,7 +557,8 @@ describe('ExchangeWrapper', () => { let orderHash: string; before(() => { takerAddress = userAddresses[1]; - const [makerToken, takerToken] = tokens; + tokenUtils = new TokenUtils(tokens); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); @@ -633,7 +634,7 @@ describe('ExchangeWrapper', () => { const cancelTakerAmountInBaseUnits = new BigNumber(1); before(() => { [coinbase, makerAddress, takerAddress] = userAddresses; - const [makerToken, takerToken] = tokens; + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); @@ -731,7 +732,7 @@ describe('ExchangeWrapper', () => { const fillableAmount = new BigNumber(5); before(async () => { [, makerAddress, takerAddress] = userAddresses; - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); @@ -766,7 +767,7 @@ describe('ExchangeWrapper', () => { let txHash: string; before(async () => { [, makerAddress, takerAddress] = userAddresses; - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); diff --git a/packages/0x.js/test/expiration_watcher_test.ts b/packages/0x.js/test/expiration_watcher_test.ts index d4581259d..30c395f00 100644 --- a/packages/0x.js/test/expiration_watcher_test.ts +++ b/packages/0x.js/test/expiration_watcher_test.ts @@ -1,4 +1,4 @@ -import {Web3Wrapper} from '@0xproject/web3-wrapper'; +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as _ from 'lodash'; @@ -12,8 +12,8 @@ import {DoneCallback, Token} from '../src/types'; import {constants} from '../src/utils/constants'; import {utils} from '../src/utils/utils'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; +import {constants as testConstants} from './utils/constants'; import {FillScenarios} from './utils/fill_scenarios'; import {reportCallbackErrors} from './utils/report_callback_errors'; import {TokenUtils} from './utils/token_utils'; @@ -21,7 +21,7 @@ import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(testConstants.RPC_URL); describe('ExpirationWatcher', () => { let web3: Web3; @@ -56,7 +56,7 @@ describe('ExpirationWatcher', () => { fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses; tokens = await zeroEx.tokenRegistry.getTokensAsync(); - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; }); diff --git a/packages/0x.js/test/order_state_watcher_test.ts b/packages/0x.js/test/order_state_watcher_test.ts index b5968dc24..df32c7f14 100644 --- a/packages/0x.js/test/order_state_watcher_test.ts +++ b/packages/0x.js/test/order_state_watcher_test.ts @@ -1,4 +1,4 @@ -import {Web3Wrapper} from '@0xproject/web3-wrapper'; +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as _ from 'lodash'; @@ -6,22 +6,17 @@ import 'mocha'; import * as Web3 from 'web3'; import { - DecodedLogEvent, ExchangeContractErrs, - LogEvent, OrderState, OrderStateInvalid, OrderStateValid, SignedOrder, Token, ZeroEx, - ZeroExConfig, ZeroExError, } from '../src'; -import {OrderStateWatcher} from '../src/order_watcher/order_state_watcher'; import {DoneCallback} from '../src/types'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {FillScenarios} from './utils/fill_scenarios'; @@ -33,7 +28,7 @@ const TIMEOUT_MS = 150; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); describe('OrderStateWatcher', () => { let web3: Web3; @@ -48,7 +43,6 @@ describe('OrderStateWatcher', () => { let takerToken: Token; let maker: string; let taker: string; - let web3Wrapper: Web3Wrapper; let signedOrder: SignedOrder; const config = { networkId: constants.TESTRPC_NETWORK_ID, @@ -65,8 +59,8 @@ describe('OrderStateWatcher', () => { tokenUtils = new TokenUtils(tokens); zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address; fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); - [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); - web3Wrapper = (zeroEx as any)._web3Wrapper; + await fillScenarios.initTokenBalancesAsync(); + [makerToken, takerToken] = tokenUtils.getDummyTokens(); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); @@ -141,7 +135,6 @@ describe('OrderStateWatcher', () => { signedOrder = await fillScenarios.createFillableSignedOrderAsync( makerToken.address, takerToken.address, maker, taker, fillableAmount, ); - const orderHash = ZeroEx.getOrderHashHex(signedOrder); zeroEx.orderStateWatcher.addOrder(signedOrder); const callback = reportCallbackErrors(done)((orderState: OrderState) => { throw new Error('OrderState callback fired for irrelevant order'); @@ -150,7 +143,6 @@ describe('OrderStateWatcher', () => { const notTheMaker = userAddresses[0]; const anyRecipient = taker; const transferAmount = new BigNumber(2); - const notTheMakerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, notTheMaker); await zeroEx.token.transferAsync(makerToken.address, notTheMaker, anyRecipient, transferAmount); setTimeout(() => { done(); @@ -207,8 +199,6 @@ describe('OrderStateWatcher', () => { ); const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker); - const fillAmountInBaseUnits = new BigNumber(2); const orderHash = ZeroEx.getOrderHashHex(signedOrder); zeroEx.orderStateWatcher.addOrder(signedOrder); @@ -241,11 +231,10 @@ describe('OrderStateWatcher', () => { signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync( makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount, taker); - const orderHash = ZeroEx.getOrderHashHex(signedOrder); - zeroEx.orderStateWatcher.addOrder(signedOrder); const callback = reportCallbackErrors(done)((orderState: OrderState) => { done(); }); + zeroEx.orderStateWatcher.addOrder(signedOrder); zeroEx.orderStateWatcher.subscribe(callback); await zeroEx.token.setProxyAllowanceAsync(zrxTokenAddress, maker, new BigNumber(0)); })().catch(done); @@ -259,8 +248,6 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, maker, taker, makerFillableAmount, takerFillableAmount, ); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker); const fillAmountInBaseUnits = ZeroEx.toBaseUnitAmount(new BigNumber(2), decimals); const orderHash = ZeroEx.getOrderHashHex(signedOrder); zeroEx.orderStateWatcher.addOrder(signedOrder); @@ -288,8 +275,6 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, maker, taker, fillableAmount, ); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const changedMakerApprovalAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals); zeroEx.orderStateWatcher.addOrder(signedOrder); @@ -342,8 +327,6 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount, feeRecipient); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals); const transferTokenAmount = makerFee.sub(remainingTokenAmount); zeroEx.orderStateWatcher.addOrder(signedOrder); @@ -369,10 +352,7 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount, feeRecipient); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const remainingFeeAmount = ZeroEx.toBaseUnitAmount(new BigNumber(3), decimals); - const transferFeeAmount = makerFee.sub(remainingFeeAmount); const remainingTokenAmount = ZeroEx.toBaseUnitAmount(new BigNumber(4), decimals); const transferTokenAmount = makerFee.sub(remainingTokenAmount); @@ -400,7 +380,6 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, makerFee, takerFee, maker, taker, fillableAmount, feeRecipient); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); zeroEx.orderStateWatcher.addOrder(signedOrder); const callback = reportCallbackErrors(done)((orderState: OrderState) => { @@ -433,7 +412,6 @@ describe('OrderStateWatcher', () => { }); zeroEx.orderStateWatcher.subscribe(callback); - const shouldThrowOnInsufficientBalanceOrAllowance = true; await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount); })().catch(done); }); @@ -465,9 +443,6 @@ describe('OrderStateWatcher', () => { makerToken.address, takerToken.address, maker, taker, fillableAmount, ); - const makerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, maker); - const takerBalance = await zeroEx.token.getBalanceAsync(makerToken.address, taker); - const cancelAmountInBaseUnits = new BigNumber(2); const orderHash = ZeroEx.getOrderHashHex(signedOrder); zeroEx.orderStateWatcher.addOrder(signedOrder); diff --git a/packages/0x.js/test/order_validation_test.ts b/packages/0x.js/test/order_validation_test.ts index d585c1f3c..b36a513fe 100644 --- a/packages/0x.js/test/order_validation_test.ts +++ b/packages/0x.js/test/order_validation_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as Sinon from 'sinon'; @@ -8,7 +9,6 @@ import {BlockParamLiteral, TradeSide, TransferType} from '../src/types'; import {ExchangeTransferSimulator} from '../src/utils/exchange_transfer_simulator'; import {OrderValidationUtils} from '../src/utils/order_validation_utils'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {FillScenarios} from './utils/fill_scenarios'; @@ -17,7 +17,7 @@ import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); describe('OrderValidation', () => { let web3: Web3; @@ -34,7 +34,6 @@ describe('OrderValidation', () => { let makerAddress: string; let takerAddress: string; let feeRecipient: string; - let orderValidationUtils: OrderValidationUtils; const fillableAmount = new BigNumber(5); const fillTakerAmount = new BigNumber(5); const config = { @@ -50,10 +49,9 @@ describe('OrderValidation', () => { tokenUtils = new TokenUtils(tokens); zrxTokenAddress = tokenUtils.getProtocolTokenOrThrow().address; fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress); - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; - orderValidationUtils = new OrderValidationUtils(zeroEx.token, zeroEx.exchange); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); @@ -181,17 +179,15 @@ describe('OrderValidation', () => { }); describe('validateCancelOrderAndThrowIfInvalidAsync', () => { let signedOrder: SignedOrder; - let orderHashHex: string; const cancelAmount = new BigNumber(3); beforeEach(async () => { [coinbase, makerAddress, takerAddress] = userAddresses; - const [makerToken, takerToken] = tokenUtils.getNonProtocolTokens(); + const [makerToken, takerToken] = tokenUtils.getDummyTokens(); makerTokenAddress = makerToken.address; takerTokenAddress = takerToken.address; signedOrder = await fillScenarios.createFillableSignedOrderAsync( makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount, ); - orderHashHex = ZeroEx.getOrderHashHex(signedOrder); }); it('should throw when cancel amount is zero', async () => { const zeroCancelAmount = new BigNumber(0); @@ -204,7 +200,6 @@ describe('OrderValidation', () => { makerTokenAddress, takerTokenAddress, makerAddress, takerAddress, fillableAmount, expirationInPast, ); - orderHashHex = ZeroEx.getOrderHashHex(expiredSignedOrder); return expect(zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(expiredSignedOrder, cancelAmount)) .to.be.rejectedWith(ExchangeContractErrs.OrderCancelExpired); }); diff --git a/packages/0x.js/test/remaining_fillable_calculator_test.ts b/packages/0x.js/test/remaining_fillable_calculator_test.ts index 610bf9b1a..95ef0a4f1 100644 --- a/packages/0x.js/test/remaining_fillable_calculator_test.ts +++ b/packages/0x.js/test/remaining_fillable_calculator_test.ts @@ -2,12 +2,11 @@ import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import 'mocha'; -import { ZeroEx } from '../src/0x'; -import { RemainingFillableCalculator } from '../src/order_watcher/remaining_fillable_calculator'; -import { ECSignature, SignedOrder } from '../src/types'; +import {ZeroEx} from '../src/0x'; +import {RemainingFillableCalculator} from '../src/order_watcher/remaining_fillable_calculator'; +import {ECSignature, SignedOrder} from '../src/types'; -import { chaiSetup } from './utils/chai_setup'; -import { TokenUtils } from './utils/token_utils'; +import {chaiSetup} from './utils/chai_setup'; chaiSetup.configure(); const expect = chai.expect; @@ -27,7 +26,7 @@ describe('RemainingFillableCalculator', () => { const decimals: number = 4; const zero: BigNumber = new BigNumber(0); const zeroAddress = '0x0'; - const signature: ECSignature = { v: 27, r: '', s: ''}; + const signature: ECSignature = {v: 27, r: '', s: ''}; beforeEach(async () => { [makerAmount, takerAmount, makerFeeAmount] = [ZeroEx.toBaseUnitAmount(new BigNumber(50), decimals), ZeroEx.toBaseUnitAmount(new BigNumber(5), decimals), diff --git a/packages/0x.js/test/subscription_test.ts b/packages/0x.js/test/subscription_test.ts index 3aeeaa109..43e6b63b6 100644 --- a/packages/0x.js/test/subscription_test.ts +++ b/packages/0x.js/test/subscription_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as _ from 'lodash'; @@ -11,27 +12,23 @@ import { Token, TokenEvents, ZeroEx, - ZeroExError, } from '../src'; -import {BlockParamLiteral, DoneCallback} from '../src/types'; +import {DoneCallback} from '../src/types'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {reportCallbackErrors} from './utils/report_callback_errors'; -import {TokenUtils} from './utils/token_utils'; import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); describe('SubscriptionTest', () => { let web3: Web3; let zeroEx: ZeroEx; let userAddresses: string[]; let tokens: Token[]; - let tokenUtils: TokenUtils; let coinbase: string; let addressWithoutFunds: string; const config = { @@ -42,7 +39,6 @@ describe('SubscriptionTest', () => { zeroEx = new ZeroEx(web3.currentProvider, config); userAddresses = await zeroEx.getAvailableAddressesAsync(); tokens = await zeroEx.tokenRegistry.getTokensAsync(); - tokenUtils = new TokenUtils(tokens); coinbase = userAddresses[0]; addressWithoutFunds = userAddresses[1]; }); @@ -54,9 +50,7 @@ describe('SubscriptionTest', () => { }); describe('#subscribe', () => { const indexFilterValues = {}; - const shouldThrowOnInsufficientBalanceOrAllowance = true; let tokenAddress: string; - const transferAmount = new BigNumber(42); const allowanceAmount = new BigNumber(42); let stubs: Sinon.SinonStub[] = []; before(() => { diff --git a/packages/0x.js/test/token_registry_wrapper_test.ts b/packages/0x.js/test/token_registry_wrapper_test.ts index f1f307f3a..533384450 100644 --- a/packages/0x.js/test/token_registry_wrapper_test.ts +++ b/packages/0x.js/test/token_registry_wrapper_test.ts @@ -1,3 +1,4 @@ +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import {schemas, SchemaValidator} from '@0xproject/json-schemas'; import * as chai from 'chai'; import * as _ from 'lodash'; @@ -5,14 +6,13 @@ import 'mocha'; import {Token, ZeroEx} from '../src'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); const TOKEN_REGISTRY_SIZE_AFTER_MIGRATION = 7; diff --git a/packages/0x.js/test/token_transfer_proxy_wrapper_test.ts b/packages/0x.js/test/token_transfer_proxy_wrapper_test.ts index 05861d112..9674b64ac 100644 --- a/packages/0x.js/test/token_transfer_proxy_wrapper_test.ts +++ b/packages/0x.js/test/token_transfer_proxy_wrapper_test.ts @@ -1,7 +1,6 @@ import * as chai from 'chai'; import {ZeroEx} from '../src'; -import {TokenTransferProxyWrapper} from '../src/contract_wrappers/token_transfer_proxy_wrapper'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; diff --git a/packages/0x.js/test/token_wrapper_test.ts b/packages/0x.js/test/token_wrapper_test.ts index ae6016869..70637dbfe 100644 --- a/packages/0x.js/test/token_wrapper_test.ts +++ b/packages/0x.js/test/token_wrapper_test.ts @@ -1,4 +1,4 @@ -import {promisify} from '@0xproject/utils'; +import {BlockchainLifecycle} from '@0xproject/dev-utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; @@ -7,13 +7,9 @@ import * as Web3 from 'web3'; import { ApprovalContractEventArgs, - ContractEvent, DecodedLogEvent, - LogEvent, - LogWithDecodedArgs, SubscriptionOpts, Token, - TokenContractEventArgs, TokenEvents, TransferContractEventArgs, ZeroEx, @@ -21,7 +17,6 @@ import { } from '../src'; import {BlockParamLiteral, DoneCallback} from '../src/types'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; import {chaiSetup} from './utils/chai_setup'; import {constants} from './utils/constants'; import {TokenUtils} from './utils/token_utils'; @@ -29,7 +24,7 @@ import {web3Factory} from './utils/web3_factory'; chaiSetup.configure(); const expect = chai.expect; -const blockchainLifecycle = new BlockchainLifecycle(); +const blockchainLifecycle = new BlockchainLifecycle(constants.RPC_URL); describe('TokenWrapper', () => { let web3: Web3; @@ -71,8 +66,7 @@ describe('TokenWrapper', () => { const toAddress = addressWithoutFunds; const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); expect(preBalance).to.be.bignumber.equal(0); - const txHash = await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount); - const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, transferAmount); const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); return expect(postBalance).to.be.bignumber.equal(transferAmount); }); @@ -354,7 +348,6 @@ describe('TokenWrapper', () => { }); describe('#subscribe', () => { const indexFilterValues = {}; - const shouldThrowOnInsufficientBalanceOrAllowance = true; let tokenAddress: string; const transferAmount = new BigNumber(42); const allowanceAmount = new BigNumber(42); diff --git a/packages/0x.js/test/utils/constants.ts b/packages/0x.js/test/utils/constants.ts index 75fdf49c9..d486da581 100644 --- a/packages/0x.js/test/utils/constants.ts +++ b/packages/0x.js/test/utils/constants.ts @@ -1,7 +1,6 @@ export const constants = { NULL_ADDRESS: '0x0000000000000000000000000000000000000000', - RPC_HOST: 'localhost', - RPC_PORT: 8545, + RPC_URL: 'http://localhost:8545', ROPSTEN_NETWORK_ID: 3, KOVAN_NETWORK_ID: 42, TESTRPC_NETWORK_ID: 50, diff --git a/packages/0x.js/test/utils/fill_scenarios.ts b/packages/0x.js/test/utils/fill_scenarios.ts index 090493935..5f3e89906 100644 --- a/packages/0x.js/test/utils/fill_scenarios.ts +++ b/packages/0x.js/test/utils/fill_scenarios.ts @@ -1,10 +1,15 @@ +import {Web3Wrapper} from '@0xproject/web3-wrapper'; import BigNumber from 'bignumber.js'; import {SignedOrder, Token, ZeroEx} from '../../src'; +import {artifacts} from '../../src/artifacts'; +import {DummyTokenContract} from '../../src/contract_wrappers/generated/dummy_token'; import {orderFactory} from '../utils/order_factory'; import {constants} from './constants'; +const INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS = new BigNumber(100); + export class FillScenarios { private zeroEx: ZeroEx; private userAddresses: string[]; @@ -21,6 +26,23 @@ export class FillScenarios { this.zrxTokenAddress = zrxTokenAddress; this.exchangeContractAddress = exchangeContractAddress; } + public async initTokenBalancesAsync() { + const web3Wrapper = (this.zeroEx as any)._web3Wrapper as Web3Wrapper; + for (const token of this.tokens) { + if (token.symbol !== 'ZRX' && token.symbol !== 'WETH') { + const contractInstance = web3Wrapper.getContractInstance( + artifacts.DummyTokenArtifact.abi, token.address, + ); + const defaults = {}; + const dummyToken = new DummyTokenContract(contractInstance, defaults); + const tokenSupply = ZeroEx.toBaseUnitAmount(INITIAL_COINBASE_TOKEN_SUPPLY_IN_UNITS, token.decimals); + const txHash = await dummyToken.setBalance.sendTransactionAsync(this.coinbase, tokenSupply, { + from: this.coinbase, + }); + await this.zeroEx.awaitTransactionMinedAsync(txHash); + } + } + } public async createFillableSignedOrderAsync(makerTokenAddress: string, takerTokenAddress: string, makerAddress: string, takerAddress: string, fillableAmount: BigNumber, diff --git a/packages/0x.js/test/utils/report_callback_errors.ts b/packages/0x.js/test/utils/report_callback_errors.ts index 8a8f4d966..0aaef3f05 100644 --- a/packages/0x.js/test/utils/report_callback_errors.ts +++ b/packages/0x.js/test/utils/report_callback_errors.ts @@ -1,4 +1,4 @@ -import { DoneCallback } from '../../src/types'; +import {DoneCallback} from '../../src/types'; export const reportCallbackErrors = (done: DoneCallback) => { return (f: (...args: any[]) => void) => { diff --git a/packages/0x.js/test/utils/token_utils.ts b/packages/0x.js/test/utils/token_utils.ts index 9c20f52a1..4634899a7 100644 --- a/packages/0x.js/test/utils/token_utils.ts +++ b/packages/0x.js/test/utils/token_utils.ts @@ -3,6 +3,7 @@ import * as _ from 'lodash'; import {InternalZeroExError, Token} from '../../src/types'; const PROTOCOL_TOKEN_SYMBOL = 'ZRX'; +const WETH_TOKEN_SYMBOL = 'WETH'; export class TokenUtils { private tokens: Token[]; @@ -16,10 +17,10 @@ export class TokenUtils { } return zrxToken; } - public getNonProtocolTokens(): Token[] { - const nonProtocolTokens = _.filter(this.tokens, token => { - return token.symbol !== PROTOCOL_TOKEN_SYMBOL; + public getDummyTokens(): Token[] { + const dummyTokens = _.filter(this.tokens, token => { + return !_.includes([PROTOCOL_TOKEN_SYMBOL, WETH_TOKEN_SYMBOL], token.symbol); }); - return nonProtocolTokens; + return dummyTokens; } } diff --git a/packages/0x.js/test/utils/web3_factory.ts b/packages/0x.js/test/utils/web3_factory.ts index da4828943..6f72cec58 100644 --- a/packages/0x.js/test/utils/web3_factory.ts +++ b/packages/0x.js/test/utils/web3_factory.ts @@ -21,13 +21,12 @@ export const web3Factory = { }, getRpcProvider(hasAddresses: boolean = true): Web3.Provider { const provider = new ProviderEngine(); - const rpcUrl = `http://${constants.RPC_HOST}:${constants.RPC_PORT}`; if (!hasAddresses) { provider.addProvider(new EmptyWalletSubprovider()); } provider.addProvider(new FakeGasEstimateSubprovider(constants.GAS_ESTIMATE)); provider.addProvider(new RpcSubprovider({ - rpcUrl, + rpcUrl: constants.RPC_URL, })); provider.start(); return provider; diff --git a/packages/abi-gen-templates/package.json b/packages/abi-gen-templates/package.json deleted file mode 100644 index 60b88d8d7..000000000 --- a/packages/abi-gen-templates/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "abi-gen-templates", - "private": true, - "version": "0.0.2", - "description": "Handlebars templates to generate TS contract wrappers", - "repository": { - "type": "git", - "url": "https://github.com/0xProject/0x.js.git" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/0xProject/0x.js/issues" - }, - "homepage": "https://github.com/0xProject/0x.js/packages/abi-gen-templates/README.md" -} diff --git a/packages/abi-gen/README.md b/packages/abi-gen/README.md index 16dd9b969..0eaacd86f 100644 --- a/packages/abi-gen/README.md +++ b/packages/abi-gen/README.md @@ -5,7 +5,7 @@ It's heavily inspired by [Geth abigen](https://github.com/ethereum/go-ethereum/w You can write your custom handlebars templates which will allow you to seamlessly integrate the generated code into your existing codebase with existing conventions. For an example of the generated [wrapper files](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/src/contract_wrappers/generated) check out 0x.js. -[Here](https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates) are the templates used to generate those files. +[Here](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/src/contract_templates) are the templates used to generate those files. ## Instalation `yarn add -g @0xproject/abi-gen` @@ -29,7 +29,7 @@ We could've just used `--abiGlob 'src/artifacts/*.json` but we wanted to exclude The abi file should be either a [Truffle](http://truffleframework.com/) contract artifact (a JSON object with an abi key) or a JSON abi array. ## How to write custom templates? -The best way to get started is to copy [0x.js templates](https://github.com/0xProject/0x.js/tree/development/packages/abi-gen-templates) and start adjusting them for your needs. +The best way to get started is to copy [0x.js templates](https://github.com/0xProject/0x.js/tree/development/packages/0x.js/src/contract_templates) and start adjusting them for your needs. We use [handlebars](handlebarsjs.com) template engine under the hood. You need to have a master template called `contract.mustache`. it will be used to generate each contract wrapper. Although - you don't need and probably shouldn't write all your logic in a single template file. You can write [partial templates](http://handlebarsjs.com/partials.html) and as long as they are within a partials folder - they will be registered and available. ## Which data/context do I get in my templates? diff --git a/packages/assert/test/assert_test.ts b/packages/assert/test/assert_test.ts index 5fa96e49a..6a9efc748 100644 --- a/packages/assert/test/assert_test.ts +++ b/packages/assert/test/assert_test.ts @@ -25,7 +25,7 @@ describe('Assertions', () => { 'test', 42, false, - { random: 'test' }, + {random: 'test'}, undefined, ]; invalidInputs.forEach(input => expect(assert.isBigNumber.bind(assert, variableName, input)).to.throw()); @@ -43,7 +43,7 @@ describe('Assertions', () => { 'test', 42, false, - { random: 'test' }, + {random: 'test'}, ]; invalidInputs.forEach(input => expect(assert.isUndefined.bind(assert, input, variableName)).to.throw()); }); @@ -60,7 +60,7 @@ describe('Assertions', () => { const invalidInputs = [ 42, false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -79,7 +79,7 @@ describe('Assertions', () => { const invalidInputs = [ 42, false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -98,7 +98,7 @@ describe('Assertions', () => { const invalidInputs = [ 42, false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), '0x61a3ed31B43c8780e905a260a35faYfEc527be7516aa11c0256729b5b351bc33', @@ -121,7 +121,7 @@ describe('Assertions', () => { const invalidInputs = [ 42, false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), '0x6FFFd0ae3f7d88c9b4925323f54c6e4b2918c5fd', @@ -150,7 +150,7 @@ describe('Assertions', () => { const invalidInputs = [ 42, false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -192,7 +192,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ false, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -210,7 +210,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ 42, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -220,8 +220,8 @@ describe('Assertions', () => { describe('#isWeb3Provider', () => { it('should not throw for valid input', () => { const validInputs = [ - { send: () => 45 }, - { sendAsync: () => 45 }, + {send: () => 45}, + {sendAsync: () => 45}, ]; validInputs.forEach(input => expect(assert.isWeb3Provider.bind(assert, variableName, input)).to.not.throw(), @@ -230,7 +230,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ 42, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -253,7 +253,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ 42, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), ]; @@ -277,7 +277,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ 42, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), 'ws://www.api.example-relayer.net', @@ -309,7 +309,7 @@ describe('Assertions', () => { it('should throw for invalid input', () => { const invalidInputs = [ 42, - { random: 'test' }, + {random: 'test'}, undefined, new BigNumber(45), 'www.google.com', diff --git a/packages/connect/src/utils/orderbook_channel_message_parsers.ts b/packages/connect/src/utils/orderbook_channel_message_parsers.ts index 486a416ef..d9a84cca2 100644 --- a/packages/connect/src/utils/orderbook_channel_message_parsers.ts +++ b/packages/connect/src/utils/orderbook_channel_message_parsers.ts @@ -5,7 +5,6 @@ import * as _ from 'lodash'; import { OrderbookChannelMessage, OrderbookChannelMessageTypes, - SignedOrder, } from '../types'; import {typeConverters} from './type_converters'; diff --git a/packages/connect/src/ws_orderbook_channel.ts b/packages/connect/src/ws_orderbook_channel.ts index 6687025c0..f58593484 100644 --- a/packages/connect/src/ws_orderbook_channel.ts +++ b/packages/connect/src/ws_orderbook_channel.ts @@ -8,7 +8,6 @@ import { OrderbookChannelHandler, OrderbookChannelMessageTypes, OrderbookChannelSubscriptionOpts, - SignedOrder, WebsocketClientEventType, WebsocketConnectionEventType, } from './types'; @@ -99,7 +98,6 @@ export class WebSocketOrderbookChannel implements OrderbookChannel { try { const utf8Data = message.utf8Data; const parserResult = orderbookChannelMessageParsers.parser(utf8Data); - const type = parserResult.type; if (parserResult.requestId === requestId) { switch (parserResult.type) { case (OrderbookChannelMessageTypes.Snapshot): { diff --git a/packages/contracts/contracts/Exchange.sol b/packages/contracts/contracts/Exchange.sol index 02deee967..a402e7ca5 100644 --- a/packages/contracts/contracts/Exchange.sol +++ b/packages/contracts/contracts/Exchange.sol @@ -16,11 +16,11 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./TokenTransferProxy.sol"; -import "./base/Token.sol"; -import "./base/SafeMath.sol"; +import "./tokens/Token.sol"; +import "./utils/SafeMath.sol"; /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> @@ -600,3 +600,4 @@ contract Exchange is SafeMath { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy } } + diff --git a/packages/contracts/contracts/TokenRegistry.sol b/packages/contracts/contracts/TokenRegistry.sol index d370f8cfe..d2570e71d 100644 --- a/packages/contracts/contracts/TokenRegistry.sol +++ b/packages/contracts/contracts/TokenRegistry.sol @@ -16,9 +16,9 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; -import "./base/Ownable.sol"; +import "./utils/Ownable.sol"; /// @title Token Registry - Stores metadata associated with ERC20 tokens. See ERC22 https://github.com/ethereum/EIPs/issues/22 /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> @@ -306,3 +306,4 @@ contract TokenRegistry is Ownable { return tokenAddresses; } } + diff --git a/packages/contracts/contracts/TokenTransferProxy.sol b/packages/contracts/contracts/TokenTransferProxy.sol index 23b0b9e6d..fd2358496 100644 --- a/packages/contracts/contracts/TokenTransferProxy.sol +++ b/packages/contracts/contracts/TokenTransferProxy.sol @@ -16,10 +16,10 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; -import "./base/Token.sol"; -import "./base/Ownable.sol"; +import "./tokens/Token.sol"; +import "./utils/Ownable.sol"; /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> @@ -113,3 +113,4 @@ contract TokenTransferProxy is Ownable { return authorities; } } + diff --git a/packages/contracts/contracts/base/SafeMath.sol b/packages/contracts/contracts/base/SafeMath.sol deleted file mode 100644 index fac674a20..000000000 --- a/packages/contracts/contracts/base/SafeMath.sol +++ /dev/null @@ -1,41 +0,0 @@ -pragma solidity 0.4.11; - -contract SafeMath { - function safeMul(uint a, uint b) internal constant returns (uint256) { - uint c = a * b; - assert(a == 0 || c / a == b); - return c; - } - - function safeDiv(uint a, uint b) internal constant returns (uint256) { - uint c = a / b; - return c; - } - - function safeSub(uint a, uint b) internal constant returns (uint256) { - assert(b <= a); - return a - b; - } - - function safeAdd(uint a, uint b) internal constant returns (uint256) { - uint c = a + b; - assert(c >= a); - return c; - } - - function max64(uint64 a, uint64 b) internal constant returns (uint64) { - return a >= b ? a : b; - } - - function min64(uint64 a, uint64 b) internal constant returns (uint64) { - return a < b ? a : b; - } - - function max256(uint256 a, uint256 b) internal constant returns (uint256) { - return a >= b ? a : b; - } - - function min256(uint256 a, uint256 b) internal constant returns (uint256) { - return a < b ? a : b; - } -} diff --git a/packages/contracts/contracts/base/MultiSigWallet.sol b/packages/contracts/contracts/multisig/MultiSigWallet.sol index 7531224ea..ae7ef06fd 100644 --- a/packages/contracts/contracts/base/MultiSigWallet.sol +++ b/packages/contracts/contracts/multisig/MultiSigWallet.sol @@ -1,4 +1,4 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> @@ -363,3 +363,4 @@ contract MultiSigWallet { _transactionIds[i - from] = transactionIdsTemp[i]; } } + diff --git a/packages/contracts/contracts/MultiSigWalletWithTimeLock.sol b/packages/contracts/contracts/multisig/MultiSigWalletWithTimeLock.sol index 70123e6b6..62273eba3 100644 --- a/packages/contracts/contracts/MultiSigWalletWithTimeLock.sol +++ b/packages/contracts/contracts/multisig/MultiSigWalletWithTimeLock.sol @@ -16,9 +16,9 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; -import "./base/MultiSigWallet.sol"; +import "./MultiSigWallet.sol"; /// @title Multisignature wallet with time lock- Allows multiple parties to execute a transaction after a time lock has passed. /// @author Amir Bandeali - <amir@0xProject.com> @@ -130,3 +130,4 @@ contract MultiSigWalletWithTimeLock is MultiSigWallet { ConfirmationTimeSet(transactionId, confirmationTime); } } + diff --git a/packages/contracts/contracts/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol b/packages/contracts/contracts/multisig/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol index 15fdb1d07..07beb9f5b 100644 --- a/packages/contracts/contracts/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol +++ b/packages/contracts/contracts/multisig/MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress.sol @@ -16,7 +16,7 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./MultiSigWalletWithTimeLock.sol"; @@ -80,3 +80,4 @@ contract MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress is MultiSigWall return true; } } + diff --git a/packages/contracts/contracts/test/DummyToken.sol b/packages/contracts/contracts/test/DummyToken.sol index 414c17b2a..046af3059 100644 --- a/packages/contracts/contracts/test/DummyToken.sol +++ b/packages/contracts/contracts/test/DummyToken.sol @@ -1,7 +1,7 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./Mintable.sol"; -import "./../base/Ownable.sol"; +import "./../utils/Ownable.sol"; contract DummyToken is Mintable, Ownable { string public name; @@ -21,7 +21,9 @@ contract DummyToken is Mintable, Ownable { balances[msg.sender] = _totalSupply; } - function setBalance(address _target, uint _value) onlyOwner { + function setBalance(address _target, uint _value) + onlyOwner + { uint currBalance = balanceOf(_target); if (_value < currBalance) { totalSupply = safeSub(totalSupply, safeSub(currBalance, _value)); @@ -31,3 +33,4 @@ contract DummyToken is Mintable, Ownable { balances[_target] = _value; } } + diff --git a/packages/contracts/contracts/test/DummyToken_v2.sol b/packages/contracts/contracts/test/DummyToken_v2.sol new file mode 100644 index 000000000..bd4d06be9 --- /dev/null +++ b/packages/contracts/contracts/test/DummyToken_v2.sol @@ -0,0 +1,38 @@ +pragma solidity 0.4.18; + +import "./Mintable_v2.sol"; +import "./../utils/Ownable_v2.sol"; + +contract DummyToken_v2 is Mintable_v2, Ownable_v2 { + string public name; + string public symbol; + uint public decimals; + + function DummyToken_v2( + string _name, + string _symbol, + uint _decimals, + uint _totalSupply) + public + { + name = _name; + symbol = _symbol; + decimals = _decimals; + totalSupply = _totalSupply; + balances[msg.sender] = _totalSupply; + } + + function setBalance(address _target, uint _value) + public + onlyOwner + { + uint currBalance = balanceOf(_target); + if (_value < currBalance) { + totalSupply = safeSub(totalSupply, safeSub(currBalance, _value)); + } else { + totalSupply = safeAdd(totalSupply, safeSub(_value, currBalance)); + } + balances[_target] = _value; + } +} + diff --git a/packages/contracts/contracts/test/MaliciousToken.sol b/packages/contracts/contracts/test/MaliciousToken.sol index 3c1a53612..3e7d5d1a5 100644 --- a/packages/contracts/contracts/test/MaliciousToken.sol +++ b/packages/contracts/contracts/test/MaliciousToken.sol @@ -1,11 +1,13 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; -import "./../base/StandardToken.sol"; +import "./../tokens/StandardToken.sol"; contract MaliciousToken is StandardToken { uint8 stateToUpdate = 1; // Not null so that change only requires 5000 gas - function updateState() internal { + function updateState() + internal + { stateToUpdate++; } @@ -27,3 +29,4 @@ contract MaliciousToken is StandardToken { return allowed[_owner][_spender]; } } + diff --git a/packages/contracts/contracts/test/Mintable.sol b/packages/contracts/contracts/test/Mintable.sol index c0438f304..3b91415ef 100644 --- a/packages/contracts/contracts/test/Mintable.sol +++ b/packages/contracts/contracts/test/Mintable.sol @@ -1,16 +1,19 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./../tokens/UnlimitedAllowanceToken.sol"; -import "./../base/SafeMath.sol"; +import "./../utils/SafeMath.sol"; /* * Mintable * Base contract that creates a mintable UnlimitedAllowanceToken */ contract Mintable is UnlimitedAllowanceToken, SafeMath { - function mint(uint _value) { + function mint(uint _value) + public + { require(_value <= 100000000000000000000); balances[msg.sender] = safeAdd(_value, balances[msg.sender]); totalSupply = safeAdd(totalSupply, _value); } } + diff --git a/packages/contracts/contracts/test/Mintable_v2.sol b/packages/contracts/contracts/test/Mintable_v2.sol new file mode 100644 index 000000000..829145cfb --- /dev/null +++ b/packages/contracts/contracts/test/Mintable_v2.sol @@ -0,0 +1,19 @@ +pragma solidity 0.4.18; + +import "./../tokens/UnlimitedAllowanceToken_v2.sol"; +import "./../utils/SafeMath_v2.sol"; + +/* + * Mintable + * Base contract that creates a mintable UnlimitedAllowanceToken + */ +contract Mintable_v2 is UnlimitedAllowanceToken_v2, SafeMath_v2 { + function mint(uint _value) + public + { + require(_value <= 100000000000000000000); + balances[msg.sender] = safeAdd(_value, balances[msg.sender]); + totalSupply = safeAdd(totalSupply, _value); + } +} + diff --git a/packages/contracts/contracts/tokens/ERC20Token.sol b/packages/contracts/contracts/tokens/ERC20Token.sol new file mode 100644 index 000000000..318da8c01 --- /dev/null +++ b/packages/contracts/contracts/tokens/ERC20Token.sol @@ -0,0 +1,59 @@ +pragma solidity 0.4.18; + +import "./Token_v2.sol"; + +contract ERC20Token is Token_v2 { + + function transfer(address _to, uint _value) + public + returns (bool) + { + require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) + public + returns (bool) + { + require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]); + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint _value) + public + returns (bool) + { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function balanceOf(address _owner) + public + view + returns (uint) + { + return balances[_owner]; + } + + function allowance(address _owner, address _spender) + public + view + returns (uint) + { + return allowed[_owner][_spender]; + } + + mapping (address => uint) balances; + mapping (address => mapping (address => uint)) allowed; + uint public totalSupply; +} + diff --git a/packages/contracts/contracts/tokens/EtherToken.sol b/packages/contracts/contracts/tokens/EtherToken.sol index 68148e095..2eae012fc 100644 --- a/packages/contracts/contracts/tokens/EtherToken.sol +++ b/packages/contracts/contracts/tokens/EtherToken.sol @@ -16,10 +16,10 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./UnlimitedAllowanceToken.sol"; -import "./../base/SafeMath.sol"; +import "./../utils/SafeMath.sol"; contract EtherToken is UnlimitedAllowanceToken, SafeMath { @@ -54,3 +54,4 @@ contract EtherToken is UnlimitedAllowanceToken, SafeMath { require(msg.sender.send(amount)); } } + diff --git a/packages/contracts/contracts/tokens/EtherToken_v2.sol b/packages/contracts/contracts/tokens/EtherToken_v2.sol new file mode 100644 index 000000000..f172c8e35 --- /dev/null +++ b/packages/contracts/contracts/tokens/EtherToken_v2.sol @@ -0,0 +1,60 @@ +/* + + Copyright 2017 ZeroEx Intl. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +pragma solidity 0.4.18; + +import "./UnlimitedAllowanceToken_v2.sol"; +import "./../utils/SafeMath_v2.sol"; + +contract EtherToken_v2 is UnlimitedAllowanceToken_v2, SafeMath_v2 { + + string constant public name = "Ether Token"; + string constant public symbol = "WETH"; + string constant public version = "2.0.0"; // version 1.0.0 deployed on mainnet at 0x2956356cd2a2bf3202f771f50d3d14a367b48070 + uint8 constant public decimals = 18; + + /// @dev Fallback to calling deposit when ether is sent directly to contract. + function() + public + payable + { + deposit(); + } + + /// @dev Buys tokens with Ether, exchanging them 1:1. + function deposit() + public + payable + { + balances[msg.sender] = safeAdd(balances[msg.sender], msg.value); + totalSupply = safeAdd(totalSupply, msg.value); + Transfer(address(0), msg.sender, msg.value); + } + + /// @dev Sells tokens in exchange for Ether, exchanging them 1:1. + /// @param _value Number of tokens to sell. + function withdraw(uint _value) + public + { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + totalSupply = safeSub(totalSupply, _value); + require(msg.sender.send(_value)); + Transfer(msg.sender, address(0), _value); + } +} + diff --git a/packages/contracts/contracts/base/StandardToken.sol b/packages/contracts/contracts/tokens/StandardToken.sol index e0719d89a..9cd53d94a 100644 --- a/packages/contracts/contracts/base/StandardToken.sol +++ b/packages/contracts/contracts/tokens/StandardToken.sol @@ -1,4 +1,4 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./Token.sol"; @@ -42,3 +42,4 @@ contract StandardToken is Token { mapping (address => mapping (address => uint)) allowed; uint public totalSupply; } + diff --git a/packages/contracts/contracts/base/Token.sol b/packages/contracts/contracts/tokens/Token.sol index c6a55c2c0..507de9b12 100644 --- a/packages/contracts/contracts/base/Token.sol +++ b/packages/contracts/contracts/tokens/Token.sol @@ -1,4 +1,4 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; contract Token { @@ -36,3 +36,4 @@ contract Token { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } + diff --git a/packages/contracts/contracts/tokens/Token_v2.sol b/packages/contracts/contracts/tokens/Token_v2.sol new file mode 100644 index 000000000..e1088c560 --- /dev/null +++ b/packages/contracts/contracts/tokens/Token_v2.sol @@ -0,0 +1,36 @@ +pragma solidity 0.4.18; + +contract Token_v2 { + + /// @notice send `_value` token to `_to` from `msg.sender` + /// @param _to The address of the recipient + /// @param _value The amount of token to be transferred + /// @return Whether the transfer was successful or not + function transfer(address _to, uint _value) public returns (bool) {} + + /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` + /// @param _from The address of the sender + /// @param _to The address of the recipient + /// @param _value The amount of token to be transferred + /// @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint _value) public returns (bool) {} + + /// @notice `msg.sender` approves `_addr` to spend `_value` tokens + /// @param _spender The address of the account able to transfer the tokens + /// @param _value The amount of wei to be approved for transfer + /// @return Whether the approval was successful or not + function approve(address _spender, uint _value) public returns (bool) {} + + /// @param _owner The address from which the balance will be retrieved + /// @return The balance + function balanceOf(address _owner) public view returns (uint) {} + + /// @param _owner The address of the account owning tokens + /// @param _spender The address of the account able to transfer the tokens + /// @return Amount of remaining tokens allowed to spent + function allowance(address _owner, address _spender) public view returns (uint) {} + + event Transfer(address indexed _from, address indexed _to, uint _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); +} + diff --git a/packages/contracts/contracts/tokens/UnlimitedAllowanceToken.sol b/packages/contracts/contracts/tokens/UnlimitedAllowanceToken.sol index 40e01b360..0994cfae4 100644 --- a/packages/contracts/contracts/tokens/UnlimitedAllowanceToken.sol +++ b/packages/contracts/contracts/tokens/UnlimitedAllowanceToken.sol @@ -16,9 +16,9 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; -import "./../base/StandardToken.sol"; +import "./StandardToken.sol"; contract UnlimitedAllowanceToken is StandardToken { @@ -50,3 +50,4 @@ contract UnlimitedAllowanceToken is StandardToken { } } } + diff --git a/packages/contracts/contracts/tokens/UnlimitedAllowanceToken_v2.sol b/packages/contracts/contracts/tokens/UnlimitedAllowanceToken_v2.sol new file mode 100644 index 000000000..b2caab8af --- /dev/null +++ b/packages/contracts/contracts/tokens/UnlimitedAllowanceToken_v2.sol @@ -0,0 +1,47 @@ +/* + + Copyright 2017 ZeroEx Intl. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +pragma solidity 0.4.18; + +import "./ERC20Token.sol"; + +contract UnlimitedAllowanceToken_v2 is ERC20Token { + + uint constant MAX_UINT = 2**256 - 1; + + /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. See https://github.com/ethereum/EIPs/issues/717 + /// @param _from Address to transfer from. + /// @param _to Address to transfer to. + /// @param _value Amount to transfer. + /// @return Success of transfer. + function transferFrom(address _from, address _to, uint _value) + public + returns (bool) + { + uint allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value && balances[_to] + _value >= balances[_to]); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT) { + allowed[_from][msg.sender] -= _value; + } + Transfer(_from, _to, _value); + return true; + } +} + diff --git a/packages/contracts/contracts/tokens/ZRXToken.sol b/packages/contracts/contracts/tokens/ZRXToken.sol index c8b9c08ab..af1dfac99 100644 --- a/packages/contracts/contracts/tokens/ZRXToken.sol +++ b/packages/contracts/contracts/tokens/ZRXToken.sol @@ -16,7 +16,7 @@ */ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; import "./UnlimitedAllowanceToken.sol"; @@ -31,3 +31,4 @@ contract ZRXToken is UnlimitedAllowanceToken { balances[msg.sender] = totalSupply; } } + diff --git a/packages/contracts/contracts/base/Ownable.sol b/packages/contracts/contracts/utils/Ownable.sol index b7d6ac71c..77fdaf085 100644 --- a/packages/contracts/contracts/base/Ownable.sol +++ b/packages/contracts/contracts/utils/Ownable.sol @@ -1,4 +1,4 @@ -pragma solidity 0.4.11; +pragma solidity ^0.4.11; /* * Ownable @@ -25,3 +25,4 @@ contract Ownable { } } } + diff --git a/packages/contracts/contracts/utils/Ownable_v2.sol b/packages/contracts/contracts/utils/Ownable_v2.sol new file mode 100644 index 000000000..77e1fed08 --- /dev/null +++ b/packages/contracts/contracts/utils/Ownable_v2.sol @@ -0,0 +1,33 @@ +pragma solidity 0.4.18; + +/* + * Ownable + * + * Base contract with an owner. + * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. + */ + +contract Ownable_v2 { + address public owner; + + function Ownable_v2() + public + { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) + public + onlyOwner + { + if (newOwner != address(0)) { + owner = newOwner; + } + } +} + diff --git a/packages/contracts/contracts/utils/SafeMath.sol b/packages/contracts/contracts/utils/SafeMath.sol new file mode 100644 index 000000000..a7891a7af --- /dev/null +++ b/packages/contracts/contracts/utils/SafeMath.sol @@ -0,0 +1,74 @@ +pragma solidity ^0.4.11; + +contract SafeMath { + function safeMul(uint a, uint b) + internal + constant + returns (uint256) + { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) + internal + constant + returns (uint256) + { + uint c = a / b; + return c; + } + + function safeSub(uint a, uint b) + internal + constant + returns (uint256) + { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) + internal + constant + returns (uint256) + { + uint c = a + b; + assert(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) + internal + constant + returns (uint64) + { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) + internal + constant + returns (uint64) + { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) + internal + constant + returns (uint256) + { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) + internal + constant + returns (uint256) + { + return a < b ? a : b; + } +} + diff --git a/packages/contracts/contracts/utils/SafeMath_v2.sol b/packages/contracts/contracts/utils/SafeMath_v2.sol new file mode 100644 index 000000000..6eda03999 --- /dev/null +++ b/packages/contracts/contracts/utils/SafeMath_v2.sol @@ -0,0 +1,74 @@ +pragma solidity 0.4.18; + +contract SafeMath_v2 { + function safeMul(uint a, uint b) + internal + pure + returns (uint256) + { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) + internal + pure + returns (uint256) + { + uint c = a / b; + return c; + } + + function safeSub(uint a, uint b) + internal + pure + returns (uint256) + { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) + internal + pure + returns (uint256) + { + uint c = a + b; + assert(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) + internal + pure + returns (uint256) + { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) + internal + pure + returns (uint256) + { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + return a < b ? a : b; + } +} + diff --git a/packages/contracts/deploy/migrations/migrate.ts b/packages/contracts/deploy/migrations/migrate.ts index c3d38875e..e893e6a6f 100644 --- a/packages/contracts/deploy/migrations/migrate.ts +++ b/packages/contracts/deploy/migrations/migrate.ts @@ -1,59 +1,42 @@ import {Web3Wrapper} from '@0xproject/web3-wrapper'; import {BigNumber} from 'bignumber.js'; import * as _ from 'lodash'; -import * as Web3 from 'web3'; import {Deployer} from './../src/deployer'; import {constants} from './../src/utils/constants'; -import {Token} from './../src/utils/types'; import {tokenInfo} from './config/token_info'; export const migrator = { /** * Custom migrations should be defined in this function. This will be called with the CLI 'migrate' command. + * Some operations might be completed in parallel, but we don't do that on purpose. + * That way the addresses are deterministic. * @param deployer Deployer instance. */ async runMigrationsAsync(deployer: Deployer): Promise<void> { const web3Wrapper: Web3Wrapper = deployer.web3Wrapper; const accounts: string[] = await web3Wrapper.getAvailableAddressesAsync(); - const independentContracts: Web3.ContractInstance[] = await Promise.all([ - deployer.deployAndSaveAsync('TokenTransferProxy'), - deployer.deployAndSaveAsync('ZRXToken'), - deployer.deployAndSaveAsync('EtherToken'), - deployer.deployAndSaveAsync('TokenRegistry'), - ]); - const [tokenTransferProxy, zrxToken, etherToken, tokenReg] = independentContracts; + const tokenTransferProxy = await deployer.deployAndSaveAsync('TokenTransferProxy'); + const zrxToken = await deployer.deployAndSaveAsync('ZRXToken'); + const etherToken = await deployer.deployAndSaveAsync('EtherToken'); + const tokenReg = await deployer.deployAndSaveAsync('TokenRegistry'); const exchangeArgs = [zrxToken.address, tokenTransferProxy.address]; const owners = [accounts[0], accounts[1]]; const confirmationsRequired = new BigNumber(2); const secondsRequired = new BigNumber(0); const multiSigArgs = [owners, confirmationsRequired, secondsRequired, tokenTransferProxy.address]; - const dependentContracts: Web3.ContractInstance[] = await Promise.all([ - deployer.deployAndSaveAsync('Exchange', exchangeArgs), - deployer.deployAndSaveAsync('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', multiSigArgs), - ]); - const [exchange, multiSig] = dependentContracts; + const exchange = await deployer.deployAndSaveAsync('Exchange', exchangeArgs); + const multiSig = await deployer.deployAndSaveAsync( + 'MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', multiSigArgs, + ); const owner = accounts[0]; await tokenTransferProxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, {from: owner}); await tokenTransferProxy.transferOwnership.sendTransactionAsync(multiSig.address, {from: owner}); - - const tokensToRegister: Web3.ContractInstance[] = await Promise.all( - _.map(tokenInfo, async (token: Token): Promise<Web3.ContractInstance> => { - const totalSupply = new BigNumber(0); - const args = [ - token.name, - token.symbol, - token.decimals, - totalSupply, - ]; - return deployer.deployAsync('DummyToken', args); - }), - ); const addTokenGasEstimate = await tokenReg.addToken.estimateGasAsync( - tokensToRegister[0].address, + zrxToken.address, tokenInfo[0].name, tokenInfo[0].symbol, tokenInfo[0].decimals, @@ -61,35 +44,41 @@ export const migrator = { tokenInfo[0].swarmHash, {from: owner}, ); - const addTokenPromises = [ - tokenReg.addToken.sendTransactionAsync( - zrxToken.address, - '0x Protocol Token', - 'ZRX', - 18, - constants.NULL_BYTES, - constants.NULL_BYTES, - { - from: owner, - gas: addTokenGasEstimate, - }, - ), - tokenReg.addToken.sendTransactionAsync( - etherToken.address, - 'Ether Token', - 'WETH', - 18, - constants.NULL_BYTES, - constants.NULL_BYTES, - { - from: owner, - gas: addTokenGasEstimate, - }, - ), - ]; - const addDummyTokenPromises = _.map(tokenInfo, async (token: Token, i: number): Promise<void> => { - return tokenReg.addToken.sendTransactionAsync( - tokensToRegister[i].address, + await tokenReg.addToken.sendTransactionAsync( + zrxToken.address, + '0x Protocol Token', + 'ZRX', + 18, + constants.NULL_BYTES, + constants.NULL_BYTES, + { + from: owner, + gas: addTokenGasEstimate, + }, + ); + await tokenReg.addToken.sendTransactionAsync( + etherToken.address, + 'Ether Token', + 'WETH', + 18, + constants.NULL_BYTES, + constants.NULL_BYTES, + { + from: owner, + gas: addTokenGasEstimate, + }, + ); + for (const token of tokenInfo) { + const totalSupply = new BigNumber(0); + const args = [ + token.name, + token.symbol, + token.decimals, + totalSupply, + ]; + const dummyToken = await deployer.deployAsync('DummyToken', args); + await tokenReg.addToken.sendTransactionAsync( + dummyToken.address, token.name, token.symbol, token.decimals, @@ -100,7 +89,6 @@ export const migrator = { gas: addTokenGasEstimate, }, ); - }); - await Promise.all([...addDummyTokenPromises, ...addTokenPromises]); + } }, }; diff --git a/packages/contracts/deploy/src/compiler.ts b/packages/contracts/deploy/src/compiler.ts index 8a44e94a3..333a2d0ce 100644 --- a/packages/contracts/deploy/src/compiler.ts +++ b/packages/contracts/deploy/src/compiler.ts @@ -1,4 +1,3 @@ -import {promisify} from '@0xproject/utils'; import * as ethUtil from 'ethereumjs-util'; import * as _ from 'lodash'; import * as path from 'path'; @@ -14,7 +13,6 @@ import { ContractNetworks, ContractSources, ImportContents, - SolcErrors, } from './utils/types'; import {utils} from './utils/utils'; diff --git a/packages/contracts/deploy/src/deployer.ts b/packages/contracts/deploy/src/deployer.ts index 4c8018ecc..991504972 100644 --- a/packages/contracts/deploy/src/deployer.ts +++ b/packages/contracts/deploy/src/deployer.ts @@ -1,5 +1,4 @@ import {TxData} from '@0xproject/types'; -import {promisify} from '@0xproject/utils'; import {Web3Wrapper} from '@0xproject/web3-wrapper'; import * as _ from 'lodash'; import * as Web3 from 'web3'; diff --git a/packages/contracts/deploy/test/deploy_test.ts b/packages/contracts/deploy/test/deploy_test.ts index 7e7b98f90..263174a94 100644 --- a/packages/contracts/deploy/test/deploy_test.ts +++ b/packages/contracts/deploy/test/deploy_test.ts @@ -4,7 +4,7 @@ import 'mocha'; import {Compiler} from './../src/compiler'; import {Deployer} from './../src/deployer'; import {fsWrapper} from './../src/utils/fs_wrapper'; -import {CompilerOptions, ContractArtifact, ContractData, DeployerOptions, DoneCallback} from './../src/utils/types'; +import {CompilerOptions, ContractArtifact, ContractData, DoneCallback} from './../src/utils/types'; import {constructor_args, exchange_binary} from './fixtures/exchange_bin'; import {constants} from './util/constants'; diff --git a/packages/contracts/deploy/test/util/constants.ts b/packages/contracts/deploy/test/util/constants.ts index a2de44b63..65525a1f7 100644 --- a/packages/contracts/deploy/test/util/constants.ts +++ b/packages/contracts/deploy/test/util/constants.ts @@ -5,7 +5,7 @@ export const constants = { jsonrpcPort: 8545, optimizerEnabled: 0, gasPrice: new BigNumber(20000000000), - timeoutMs: 12000, + timeoutMs: 20000, zrxTokenAddress: '0xe41d2489571d322189246dafa5ebde1f4699f498', tokenTransferProxyAddress: '0x8da0d80f5007ef1e431dd2127178d224e32c2ef4', }; diff --git a/packages/contracts/migrations/2_deploy_independent_contracts.ts b/packages/contracts/migrations/2_deploy_independent_contracts.ts index 878860eb6..4bf316be6 100644 --- a/packages/contracts/migrations/2_deploy_independent_contracts.ts +++ b/packages/contracts/migrations/2_deploy_independent_contracts.ts @@ -1,9 +1,10 @@ import {Artifacts} from '../util/artifacts'; -import {ContractInstance, MultiSigConfigByNetwork} from '../util/types'; +import {MultiSigConfigByNetwork} from '../util/types'; const { MultiSigWalletWithTimeLock, TokenTransferProxy, EtherToken, + EtherTokenV2, TokenRegistry, } = new Artifacts(artifacts); @@ -28,11 +29,13 @@ module.exports = (deployer: any, network: string, accounts: string[]) => { deployer.deploy(MultiSigWalletWithTimeLock, config.owners, config.confirmationsRequired, config.secondsRequired) .then(() => { - return deployer.deploy(TokenTransferProxy); + return deployer.deploy(TokenTransferProxy); }).then(() => { - return deployer.deploy(TokenRegistry); + return deployer.deploy(TokenRegistry); }).then(() => { - return deployer.deploy(EtherToken); + return deployer.deploy(EtherToken); + }).then(() => { + return deployer.deploy(EtherTokenV2); }); } else { deployer.deploy([ diff --git a/packages/contracts/migrations/3_register_tokens.ts b/packages/contracts/migrations/3_register_tokens.ts index c72ac1510..f81693628 100644 --- a/packages/contracts/migrations/3_register_tokens.ts +++ b/packages/contracts/migrations/3_register_tokens.ts @@ -3,7 +3,7 @@ import * as _ from 'lodash'; import {Artifacts} from '../util/artifacts'; import {constants} from '../util/constants'; -import {ContractInstance, Token, TokenInfoByNetwork} from '../util/types'; +import {ContractInstance, Token} from '../util/types'; import {tokenInfo} from './config/token_info'; const { diff --git a/packages/contracts/package.json b/packages/contracts/package.json index d2f30933a..c8ccd0a3a 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -15,6 +15,7 @@ "migrate:truffle": "npm run build; truffle migrate", "migrate": "npm run build; node lib/deploy/cli.js migrate", "lint": "tslint --project . 'migrations/**/*.ts' 'test/**/*.ts' 'util/**/*.ts' 'deploy/**/*.ts'", + "test:circleci": "yarn test; yarn test:deployer", "test:deployer": "npm run build; mocha lib/deploy/test/*_test.js" }, "repository": { @@ -28,10 +29,10 @@ }, "homepage": "https://github.com/0xProject/0x.js/packages/contracts/README.md", "devDependencies": { + "@0xproject/dev-utils": "^0.0.1", "@0xproject/tslint-config": "^0.2.1", "@0xproject/types": "^0.1.0", "@types/bluebird": "^3.5.3", - "@types/isomorphic-fetch": "^0.0.34", "@types/lodash": "^4.14.86", "@types/node": "^8.0.53", "@types/request-promise-native": "^1.0.2", @@ -45,7 +46,7 @@ "dirty-chai": "^2.0.1", "mocha": "^4.0.1", "solc": "^0.4.18", - "truffle": "3.4.3", + "truffle": "^4.0.1", "tslint": "5.8.0", "types-bn": "^0.0.1", "types-ethereumjs-util": "0xProject/types-ethereumjs-util", @@ -54,7 +55,7 @@ "yargs": "^10.0.3" }, "dependencies": { - "0x.js": "^0.22.6", + "0x.js": "~0.27.2", "@0xproject/json-schemas": "^0.6.10", "@0xproject/utils": "^0.1.0", "@0xproject/web3-wrapper": "^0.1.0", diff --git a/packages/contracts/test/ts/ether_token.ts b/packages/contracts/test/ts/ether_token.ts index dbb4d2ee6..2f9df59a4 100644 --- a/packages/contracts/test/ts/ether_token.ts +++ b/packages/contracts/test/ts/ether_token.ts @@ -5,6 +5,7 @@ import * as chai from 'chai'; import Web3 = require('web3'); import {Artifacts} from '../../util/artifacts'; +import {constants} from '../../util/constants'; import {chaiSetup} from './utils/chai_setup'; @@ -22,11 +23,13 @@ contract('EtherToken', (accounts: string[]) => { const gasPrice = ZeroEx.toBaseUnitAmount(new BigNumber(20), 9); let zeroEx: ZeroEx; let etherTokenAddress: string; + before(async () => { etherTokenAddress = EtherToken.address; zeroEx = new ZeroEx(web3.currentProvider, { - gasPrice, - etherTokenContractAddress: etherTokenAddress, + gasPrice, + etherTokenContractAddress: etherTokenAddress, + networkId: constants.TESTRPC_NETWORK_ID, }); }); @@ -78,7 +81,9 @@ contract('EtherToken', (accounts: string[]) => { const initEthBalance = await getEthBalanceAsync(account); const ethTokensToWithdraw = initEthTokenBalance; expect(ethTokensToWithdraw).to.not.be.bignumber.equal(0); - const txHash = await zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account); + const txHash = await zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account, { + gasLimit: constants.MAX_ETHERTOKEN_WITHDRAW_GAS, + }); const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); const ethSpentOnGas = gasPrice.times(receipt.gasUsed); diff --git a/packages/contracts/test/ts/ether_token_v2.ts b/packages/contracts/test/ts/ether_token_v2.ts new file mode 100644 index 000000000..61ac4cb57 --- /dev/null +++ b/packages/contracts/test/ts/ether_token_v2.ts @@ -0,0 +1,167 @@ +import {ZeroEx, ZeroExError} from '0x.js'; +import {promisify} from '@0xproject/utils'; +import {BigNumber} from 'bignumber.js'; +import * as chai from 'chai'; +import Web3 = require('web3'); + +import {Artifacts} from '../../util/artifacts'; +import {constants} from '../../util/constants'; + +import {chaiSetup} from './utils/chai_setup'; + +const {EtherTokenV2} = new Artifacts(artifacts); + +chaiSetup.configure(); +const expect = chai.expect; + +// In order to benefit from type-safety, we re-assign the global web3 instance injected by Truffle +// with type `any` to a variable of type `Web3`. +const web3: Web3 = (global as any).web3; + +contract('EtherTokenV2', (accounts: string[]) => { + const account = accounts[0]; + const gasPrice = ZeroEx.toBaseUnitAmount(new BigNumber(20), 9); + let zeroEx: ZeroEx; + let etherTokenAddress: string; + beforeEach(async () => { + const etherToken = await EtherTokenV2.new(); + etherTokenAddress = etherToken.address; + zeroEx = new ZeroEx(web3.currentProvider, { + gasPrice, + etherTokenContractAddress: etherTokenAddress, + networkId: constants.TESTRPC_NETWORK_ID, + }); + }); + + const sendTransactionAsync = promisify<string>(web3.eth.sendTransaction); + const getEthBalanceAsync = async (owner: string) => { + const balanceStr = await promisify<string>(web3.eth.getBalance)(owner); + const balance = new BigNumber(balanceStr); + return balance; + }; + + describe('deposit', () => { + it('should throw if caller attempts to deposit more Ether than caller balance', async () => { + const initEthBalance = await getEthBalanceAsync(account); + const ethToDeposit = initEthBalance.plus(1); + + return expect(zeroEx.etherToken.depositAsync(ethToDeposit, account)) + .to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit); + }); + + it('should convert deposited Ether to wrapped Ether tokens', async () => { + const initEthBalance = await getEthBalanceAsync(account); + const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + + const ethToDeposit = new BigNumber(web3.toWei(1, 'ether')); + + const txHash = await zeroEx.etherToken.depositAsync(ethToDeposit, account); + const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + + const ethSpentOnGas = gasPrice.times(receipt.gasUsed); + const finalEthBalance = await getEthBalanceAsync(account); + const finalEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + + expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas))); + expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit)); + }); + + it('should log 1 event with correct arguments', async () => { + const ethToDeposit = new BigNumber(web3.toWei(1, 'ether')); + + const txHash = await zeroEx.etherToken.depositAsync(ethToDeposit, account); + const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + + const logs = receipt.logs; + expect(logs.length).to.equal(1); + + const expectedFrom = ZeroEx.NULL_ADDRESS; + const expectedTo = account; + const expectedValue = ethToDeposit; + const logArgs = (logs[0] as any).args; + expect(logArgs._from).to.equal(expectedFrom); + expect(logArgs._to).to.equal(expectedTo); + expect(logArgs._value).to.be.bignumber.equal(expectedValue); + }); + }); + + describe('withdraw', () => { + beforeEach(async () => { + const ethToDeposit = new BigNumber(web3.toWei(1, 'ether')); + await zeroEx.etherToken.depositAsync(ethToDeposit, account); + }); + + it('should throw if caller attempts to withdraw greater than caller balance', async () => { + const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + const ethTokensToWithdraw = initEthTokenBalance.plus(1); + + return expect(zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account)) + .to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal); + }); + + it('should convert ether tokens to ether with sufficient balance', async () => { + const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + const initEthBalance = await getEthBalanceAsync(account); + const ethTokensToWithdraw = initEthTokenBalance; + expect(ethTokensToWithdraw).to.not.be.bignumber.equal(0); + const txHash = await zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account, { + gasLimit: constants.MAX_ETHERTOKEN_WITHDRAW_GAS, + }); + const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + + const ethSpentOnGas = gasPrice.times(receipt.gasUsed); + const finalEthBalance = await getEthBalanceAsync(account); + const finalEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + + expect(finalEthBalance).to.be.bignumber + .equal(initEthBalance.plus(ethTokensToWithdraw.minus(ethSpentOnGas))); + expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.minus(ethTokensToWithdraw)); + }); + + it('should log 1 event with correct arguments', async () => { + const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + const ethTokensToWithdraw = initEthTokenBalance; + expect(ethTokensToWithdraw).to.not.be.bignumber.equal(0); + const txHash = await zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account, { + gasLimit: constants.MAX_ETHERTOKEN_WITHDRAW_GAS, + }); + const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + + const logs = receipt.logs; + expect(logs.length).to.equal(1); + + const expectedFrom = account; + const expectedTo = ZeroEx.NULL_ADDRESS; + const expectedValue = ethTokensToWithdraw; + const logArgs = (logs[0] as any).args; + expect(logArgs._from).to.equal(expectedFrom); + expect(logArgs._to).to.equal(expectedTo); + expect(logArgs._value).to.be.bignumber.equal(expectedValue); + }); + }); + + describe('fallback', () => { + it('should convert sent ether to ether tokens', async () => { + const initEthBalance = await getEthBalanceAsync(account); + const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + + const ethToDeposit = ZeroEx.toBaseUnitAmount(new BigNumber(1), 18); + + const txHash = await sendTransactionAsync({ + from: account, + to: etherTokenAddress, + value: ethToDeposit, + gasPrice, + }); + + const receipt = await zeroEx.awaitTransactionMinedAsync(txHash); + + const ethSpentOnGas = gasPrice.times(receipt.gasUsed); + const finalEthBalance = await getEthBalanceAsync(account); + const finalEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account); + + expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas))); + expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit)); + }); + }); +}); diff --git a/packages/contracts/test/ts/exchange/core.ts b/packages/contracts/test/ts/exchange/core.ts index daf46ca37..aef2b5a5d 100644 --- a/packages/contracts/test/ts/exchange/core.ts +++ b/packages/contracts/test/ts/exchange/core.ts @@ -59,6 +59,7 @@ contract('Exchange', (accounts: string[]) => { exWrapper = new ExchangeWrapper(exchange); zeroEx = new ZeroEx(web3.currentProvider, { exchangeContractAddress: exchange.address, + networkId: constants.TESTRPC_NETWORK_ID, }); const [repAddress, dgdAddress, zrxAddress] = await Promise.all([ @@ -422,7 +423,7 @@ contract('Exchange', (accounts: string[]) => { takerTokenAmount: ZeroEx.toBaseUnitAmount(new BigNumber(200), 18), }); - return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if signature is invalid', async () => { @@ -432,7 +433,7 @@ contract('Exchange', (accounts: string[]) => { order.params.r = ethUtil.bufferToHex(ethUtil.sha3('invalidR')); order.params.s = ethUtil.bufferToHex(ethUtil.sha3('invalidS')); - return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if makerTokenAmount is 0', async () => { @@ -440,7 +441,7 @@ contract('Exchange', (accounts: string[]) => { makerTokenAmount: new BigNumber(0), }); - return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if takerTokenAmount is 0', async () => { @@ -448,14 +449,14 @@ contract('Exchange', (accounts: string[]) => { takerTokenAmount: new BigNumber(0), }); - return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.fillOrderAsync(order, taker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if fillTakerTokenAmount is 0', async () => { order = await orderFactory.newSignedOrderAsync(); return expect(exWrapper.fillOrderAsync(order, taker, {fillTakerTokenAmount: new BigNumber(0)})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should not change balances if maker balances are too low to fill order and \ @@ -478,7 +479,7 @@ contract('Exchange', (accounts: string[]) => { }); return expect(exWrapper.fillOrderAsync(order, taker, {shouldThrowOnInsufficientBalanceOrAllowance: true})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should not change balances if taker balances are too low to fill order and \ @@ -501,7 +502,7 @@ contract('Exchange', (accounts: string[]) => { }); return expect(exWrapper.fillOrderAsync(order, taker, {shouldThrowOnInsufficientBalanceOrAllowance: true})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should not change balances if maker allowances are too low to fill order and \ @@ -520,7 +521,7 @@ contract('Exchange', (accounts: string[]) => { async () => { await rep.approve(TokenTransferProxy.address, 0, {from: maker}); expect(exWrapper.fillOrderAsync(order, taker, {shouldThrowOnInsufficientBalanceOrAllowance: true})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); await rep.approve(TokenTransferProxy.address, INITIAL_ALLOWANCE, {from: maker}); }); @@ -540,7 +541,7 @@ contract('Exchange', (accounts: string[]) => { async () => { await dgd.approve(TokenTransferProxy.address, 0, {from: taker}); expect(exWrapper.fillOrderAsync(order, taker, {shouldThrowOnInsufficientBalanceOrAllowance: true})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); await dgd.approve(TokenTransferProxy.address, INITIAL_ALLOWANCE, {from: taker}); }); @@ -610,7 +611,7 @@ contract('Exchange', (accounts: string[]) => { }); return expect(exWrapper.fillOrderAsync(order, taker, {shouldThrowOnInsufficientBalanceOrAllowance: false})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should not change balances if an order is expired', async () => { @@ -651,7 +652,7 @@ contract('Exchange', (accounts: string[]) => { }); it('should throw if not sent by maker', async () => { - return expect(exWrapper.cancelOrderAsync(order, taker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.cancelOrderAsync(order, taker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if makerTokenAmount is 0', async () => { @@ -659,7 +660,7 @@ contract('Exchange', (accounts: string[]) => { makerTokenAmount: new BigNumber(0), }); - return expect(exWrapper.cancelOrderAsync(order, maker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.cancelOrderAsync(order, maker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if takerTokenAmount is 0', async () => { @@ -667,14 +668,14 @@ contract('Exchange', (accounts: string[]) => { takerTokenAmount: new BigNumber(0), }); - return expect(exWrapper.cancelOrderAsync(order, maker)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(exWrapper.cancelOrderAsync(order, maker)).to.be.rejectedWith(constants.REVERT); }); it('should throw if cancelTakerTokenAmount is 0', async () => { order = await orderFactory.newSignedOrderAsync(); return expect(exWrapper.cancelOrderAsync(order, maker, {cancelTakerTokenAmount: new BigNumber(0)})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should be able to cancel a full order', async () => { @@ -747,7 +748,6 @@ contract('Exchange', (accounts: string[]) => { const res = await exWrapper.cancelOrderAsync(order, maker); expect(res.logs).to.have.length(1); - const errId = res.logs[0].args.errorId.toNumber(); const errCode = res.logs[0].args.errorId.toNumber(); expect(errCode).to.be.equal(ExchangeContractErrs.ERROR_ORDER_FULLY_FILLED_OR_CANCELLED); }); diff --git a/packages/contracts/test/ts/exchange/wrapper.ts b/packages/contracts/test/ts/exchange/wrapper.ts index c40d60104..13a0b6058 100644 --- a/packages/contracts/test/ts/exchange/wrapper.ts +++ b/packages/contracts/test/ts/exchange/wrapper.ts @@ -133,7 +133,7 @@ contract('Exchange', (accounts: string[]) => { }); return expect(exWrapper.fillOrKillOrderAsync(order, taker)) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw if entire fillTakerTokenAmount not filled', async () => { @@ -143,7 +143,7 @@ contract('Exchange', (accounts: string[]) => { await exWrapper.fillOrderAsync(order, from, {fillTakerTokenAmount: order.params.takerTokenAmount.div(2)}); return expect(exWrapper.fillOrKillOrderAsync(order, taker)) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); @@ -227,8 +227,6 @@ contract('Exchange', (accounts: string[]) => { it('should throw if a single order does not fill the expected amount', async () => { const fillTakerTokenAmounts: BigNumber[] = []; - const makerToken = rep.address; - const takerToken = dgd.address; orders.forEach(order => { const fillTakerTokenAmount = order.params.takerTokenAmount.div(2); fillTakerTokenAmounts.push(fillTakerTokenAmount); @@ -237,7 +235,7 @@ contract('Exchange', (accounts: string[]) => { await exWrapper.fillOrKillOrderAsync(orders[0], taker); return expect(exWrapper.batchFillOrKillOrdersAsync(orders, taker, {fillTakerTokenAmounts})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); @@ -302,7 +300,7 @@ contract('Exchange', (accounts: string[]) => { return expect( exWrapper.fillOrdersUpToAsync( orders, taker, {fillTakerTokenAmount: ZeroEx.toBaseUnitAmount(new BigNumber(1000), 18)}), - ).to.be.rejectedWith(constants.INVALID_OPCODE); + ).to.be.rejectedWith(constants.REVERT); }); }); @@ -311,7 +309,7 @@ contract('Exchange', (accounts: string[]) => { const cancelTakerTokenAmounts = _.map(orders, order => order.params.takerTokenAmount); await exWrapper.batchCancelOrdersAsync(orders, maker, {cancelTakerTokenAmounts}); - const res = await exWrapper.batchFillOrdersAsync( + await exWrapper.batchFillOrdersAsync( orders, taker, {fillTakerTokenAmounts: cancelTakerTokenAmounts}); const newBalances = await dmyBalances.getAsync(); expect(balances).to.be.deep.equal(newBalances); diff --git a/packages/contracts/test/ts/multi_sig_with_time_lock.ts b/packages/contracts/test/ts/multi_sig_with_time_lock.ts index 6dd4dc3b2..d92c5967f 100644 --- a/packages/contracts/test/ts/multi_sig_with_time_lock.ts +++ b/packages/contracts/test/ts/multi_sig_with_time_lock.ts @@ -1,13 +1,14 @@ +import {RPC} from '@0xproject/dev-utils'; import {promisify} from '@0xproject/utils'; import {BigNumber} from 'bignumber.js'; import * as chai from 'chai'; import Web3 = require('web3'); import * as multiSigWalletJSON from '../../build/contracts/MultiSigWalletWithTimeLock.json'; +import * as truffleConf from '../../truffle.js'; import {Artifacts} from '../../util/artifacts'; import {constants} from '../../util/constants'; import {MultiSigWrapper} from '../../util/multi_sig_wrapper'; -import {RPC} from '../../util/rpc'; import {ContractInstance} from '../../util/types'; import {chaiSetup} from './utils/chai_setup'; @@ -38,13 +39,14 @@ contract('MultiSigWalletWithTimeLock', (accounts: string[]) => { const secondsTimeLocked = await multiSig.secondsTimeLocked.call(); initialSecondsTimeLocked = secondsTimeLocked.toNumber(); - rpc = new RPC(); + const rpcUrl = `http://${truffleConf.networks.development.host}:${truffleConf.networks.development.port}`; + rpc = new RPC(rpcUrl); }); describe('changeTimeLock', () => { it('should throw when not called by wallet', async () => { return expect(multiSig.changeTimeLock(SECONDS_TIME_LOCKED, {from: owners[0]})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw without enough confirmations', async () => { @@ -58,7 +60,7 @@ contract('MultiSigWalletWithTimeLock', (accounts: string[]) => { const subRes = await multiSigWrapper.submitTransactionAsync(destination, from, dataParams); txId = subRes.logs[0].args.transactionId.toNumber(); - return expect(multiSig.executeTransaction(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeTransaction(txId)).to.be.rejectedWith(constants.REVERT); }); it('should set confirmation time with enough confirmations', async () => { @@ -97,7 +99,7 @@ contract('MultiSigWalletWithTimeLock', (accounts: string[]) => { const confRes = await multiSig.confirmTransaction(txId, {from: owners[1]}); expect(confRes.logs).to.have.length(2); - return expect(multiSig.executeTransaction(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeTransaction(txId)).to.be.rejectedWith(constants.REVERT); }); it('should execute if it has enough confirmations and is past the time lock', async () => { diff --git a/packages/contracts/test/ts/multi_sig_with_time_lock_except_remove_auth_addr.ts b/packages/contracts/test/ts/multi_sig_with_time_lock_except_remove_auth_addr.ts index 97ccac2bd..6f7aaa6cd 100644 --- a/packages/contracts/test/ts/multi_sig_with_time_lock_except_remove_auth_addr.ts +++ b/packages/contracts/test/ts/multi_sig_with_time_lock_except_remove_auth_addr.ts @@ -44,7 +44,7 @@ contract('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', (accounts: s it('should throw if data is not for removeAuthorizedAddress', async () => { const data = MultiSigWrapper.encodeFnArgs('addAuthorizedAddress', PROXY_ABI, [owners[0]]); return expect(multiSig.isFunctionRemoveAuthorizedAddress.call(data)) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should return true if data is for removeAuthorizedAddress', async () => { @@ -64,7 +64,7 @@ contract('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', (accounts: s const res = await multiSigWrapper.submitTransactionAsync(validDestination, owners[0], dataParams); const txId = res.logs[0].args.transactionId.toString(); - return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.REVERT); }); it('should throw if tx destination is not the tokenTransferProxy', async () => { @@ -81,7 +81,7 @@ contract('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', (accounts: s const isConfirmed = await multiSig.isConfirmed.call(txId); expect(isConfirmed).to.be.true(); - return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.REVERT); }); it('should throw if tx data is not for removeAuthorizedAddress', async () => { @@ -96,7 +96,7 @@ contract('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', (accounts: s const isConfirmed = await multiSig.isConfirmed.call(txId); expect(isConfirmed).to.be.true(); - return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.REVERT); }); it('should execute removeAuthorizedAddress for valid tokenTransferProxy if fully confirmed', async () => { @@ -131,7 +131,7 @@ contract('MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress', (accounts: s const tx = await multiSig.transactions.call(txId); const isExecuted = tx[3]; expect(isExecuted).to.be.true(); - return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(multiSig.executeRemoveAuthorizedAddress(txId)).to.be.rejectedWith(constants.REVERT); }); }); }); diff --git a/packages/contracts/test/ts/token_registry.ts b/packages/contracts/test/ts/token_registry.ts index ed0bbf55b..36f3edcfc 100644 --- a/packages/contracts/test/ts/token_registry.ts +++ b/packages/contracts/test/ts/token_registry.ts @@ -58,7 +58,7 @@ contract('TokenRegistry', (accounts: string[]) => { describe('addToken', () => { it('should throw when not called by owner', async () => { - return expect(tokenRegWrapper.addTokenAsync(token1, notOwner)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(tokenRegWrapper.addTokenAsync(token1, notOwner)).to.be.rejectedWith(constants.REVERT); }); it('should add token metadata when called by owner', async () => { @@ -70,11 +70,11 @@ contract('TokenRegistry', (accounts: string[]) => { it('should throw if token already exists', async () => { await tokenRegWrapper.addTokenAsync(token1, owner); - return expect(tokenRegWrapper.addTokenAsync(token1, owner)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(tokenRegWrapper.addTokenAsync(token1, owner)).to.be.rejectedWith(constants.REVERT); }); it('should throw if token address is null', async () => { - return expect(tokenRegWrapper.addTokenAsync(nullToken, owner)).to.be.rejectedWith(constants.INVALID_OPCODE); + return expect(tokenRegWrapper.addTokenAsync(nullToken, owner)).to.be.rejectedWith(constants.REVERT); }); it('should throw if name already exists', async () => { @@ -82,7 +82,7 @@ contract('TokenRegistry', (accounts: string[]) => { const duplicateNameToken = _.assign({}, token2, {name: token1.name}); return expect(tokenRegWrapper.addTokenAsync(duplicateNameToken, owner)) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw if symbol already exists', async () => { @@ -90,7 +90,7 @@ contract('TokenRegistry', (accounts: string[]) => { const duplicateSymbolToken = _.assign({}, token2, {symbol: token1.symbol}); return expect(tokenRegWrapper.addTokenAsync(duplicateSymbolToken, owner)) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); @@ -116,7 +116,7 @@ contract('TokenRegistry', (accounts: string[]) => { describe('setTokenName', () => { it('should throw when not called by owner', async () => { return expect(tokenReg.setTokenName(token1.address, token2.name, {from: notOwner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should change the token name when called by owner', async () => { @@ -137,19 +137,19 @@ contract('TokenRegistry', (accounts: string[]) => { await tokenRegWrapper.addTokenAsync(token2, owner); return expect(tokenReg.setTokenName(token1.address, token2.name, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw if token does not exist', async () => { return expect(tokenReg.setTokenName(nullToken.address, token2.name, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); describe('setTokenSymbol', () => { it('should throw when not called by owner', async () => { return expect(tokenReg.setTokenSymbol(token1.address, token2.symbol, {from: notOwner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should change the token symbol when called by owner', async () => { @@ -170,12 +170,12 @@ contract('TokenRegistry', (accounts: string[]) => { await tokenRegWrapper.addTokenAsync(token2, owner); return expect(tokenReg.setTokenSymbol(token1.address, token2.symbol, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw if token does not exist', async () => { return expect(tokenReg.setTokenSymbol(nullToken.address, token2.symbol, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); @@ -183,7 +183,7 @@ contract('TokenRegistry', (accounts: string[]) => { it('should throw if not called by owner', async () => { const index = 0; return expect(tokenReg.removeToken(token1.address, index, {from: notOwner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should remove token metadata when called by owner', async () => { @@ -197,14 +197,14 @@ contract('TokenRegistry', (accounts: string[]) => { it('should throw if token does not exist', async () => { const index = 0; return expect(tokenReg.removeToken(nullToken.address, index, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should throw if token at given index does not match address', async () => { await tokenRegWrapper.addTokenAsync(token2, owner); const incorrectIndex = 0; return expect(tokenReg.removeToken(token2.address, incorrectIndex, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); diff --git a/packages/contracts/test/ts/token_transfer_proxy/auth.ts b/packages/contracts/test/ts/token_transfer_proxy/auth.ts index 785fbc016..7c0a3d231 100644 --- a/packages/contracts/test/ts/token_transfer_proxy/auth.ts +++ b/packages/contracts/test/ts/token_transfer_proxy/auth.ts @@ -23,7 +23,7 @@ contract('TokenTransferProxy', (accounts: string[]) => { describe('addAuthorizedAddress', () => { it('should throw if not called by owner', async () => { return expect(tokenTransferProxy.addAuthorizedAddress(notOwner, {from: notOwner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should allow owner to add an authorized address', async () => { @@ -36,14 +36,14 @@ contract('TokenTransferProxy', (accounts: string[]) => { it('should throw if owner attempts to authorize a duplicate address', async () => { return expect(tokenTransferProxy.addAuthorizedAddress(authorized, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); describe('removeAuthorizedAddress', () => { it('should throw if not called by owner', async () => { return expect(tokenTransferProxy.removeAuthorizedAddress(authorized, {from: notOwner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should allow owner to remove an authorized address', async () => { @@ -57,7 +57,7 @@ contract('TokenTransferProxy', (accounts: string[]) => { it('should throw if owner attempts to remove an address that is not authorized', async () => { return expect(tokenTransferProxy.removeAuthorizedAddress(notAuthorized, {from: owner})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); }); diff --git a/packages/contracts/test/ts/token_transfer_proxy/transfer_from.ts b/packages/contracts/test/ts/token_transfer_proxy/transfer_from.ts index 6e0bfdc1a..8b40bfb1e 100644 --- a/packages/contracts/test/ts/token_transfer_proxy/transfer_from.ts +++ b/packages/contracts/test/ts/token_transfer_proxy/transfer_from.ts @@ -46,7 +46,7 @@ contract('TokenTransferProxy', (accounts: string[]) => { describe('transferFrom', () => { it('should throw when called by an unauthorized address', async () => { expect(tokenTransferProxy.transferFrom(rep.address, accounts[0], accounts[1], 1000, {from: notAuthorized})) - .to.be.rejectedWith(constants.INVALID_OPCODE); + .to.be.rejectedWith(constants.REVERT); }); it('should allow an authorized address to transfer', async () => { diff --git a/packages/contracts/test/ts/unlimitedAllowanceToken.ts b/packages/contracts/test/ts/unlimited_allowance_token.ts index ca3fcd7d2..33b2a5721 100644 --- a/packages/contracts/test/ts/unlimitedAllowanceToken.ts +++ b/packages/contracts/test/ts/unlimited_allowance_token.ts @@ -4,6 +4,7 @@ import * as chai from 'chai'; import * as Web3 from 'web3'; import {Artifacts} from '../../util/artifacts'; +import {constants} from '../../util/constants'; import {ContractInstance} from '../../util/types'; import {chaiSetup} from './utils/chai_setup'; @@ -14,7 +15,10 @@ chaiSetup.configure(); const expect = chai.expect; contract('UnlimitedAllowanceToken', (accounts: string[]) => { - const zeroEx = new ZeroEx(web3.currentProvider); + const config = { + networkId: constants.TESTRPC_NETWORK_ID, + }; + const zeroEx = new ZeroEx(web3.currentProvider, config); const owner = accounts[0]; const spender = accounts[1]; @@ -81,7 +85,9 @@ contract('UnlimitedAllowanceToken', (accounts: string[]) => { const amountToTransfer = initOwnerBalance; const initSpenderAllowance = zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); - await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(tokenAddress, owner, spender); expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance); @@ -92,7 +98,9 @@ contract('UnlimitedAllowanceToken', (accounts: string[]) => { const amountToTransfer = initOwnerBalance; const initSpenderAllowance = initOwnerBalance; await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); - await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); const newOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); const newSpenderBalance = await zeroEx.token.getBalanceAsync(tokenAddress, spender); @@ -106,7 +114,9 @@ contract('UnlimitedAllowanceToken', (accounts: string[]) => { const amountToTransfer = initOwnerBalance; const initSpenderAllowance = initOwnerBalance; await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); - await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(tokenAddress, owner, spender); expect(newSpenderAllowance).to.be.bignumber.equal(0); diff --git a/packages/contracts/test/ts/unlimited_allowance_token_v2.ts b/packages/contracts/test/ts/unlimited_allowance_token_v2.ts new file mode 100644 index 000000000..4fa06e483 --- /dev/null +++ b/packages/contracts/test/ts/unlimited_allowance_token_v2.ts @@ -0,0 +1,132 @@ +import {ZeroEx} from '0x.js'; +import {BigNumber} from 'bignumber.js'; +import * as chai from 'chai'; +import * as Web3 from 'web3'; + +import {Artifacts} from '../../util/artifacts'; +import {constants} from '../../util/constants'; +import {ContractInstance} from '../../util/types'; + +import {chaiSetup} from './utils/chai_setup'; + +const {DummyTokenV2} = new Artifacts(artifacts); +const web3: Web3 = (global as any).web3; +chaiSetup.configure(); +const expect = chai.expect; + +contract('UnlimitedAllowanceTokenV2', (accounts: string[]) => { + const config = { + networkId: constants.TESTRPC_NETWORK_ID, + }; + const zeroEx = new ZeroEx(web3.currentProvider, config); + const owner = accounts[0]; + const spender = accounts[1]; + + const MAX_MINT_VALUE = new BigNumber(100000000000000000000); + let tokenAddress: string; + let token: ContractInstance; + + beforeEach(async () => { + token = await DummyTokenV2.new({from: owner}); + await token.mint(MAX_MINT_VALUE, {from: owner}); + tokenAddress = token.address; + }); + + describe('transfer', () => { + it('should throw if owner has insufficient balance', async () => { + const ownerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = ownerBalance.plus(1); + return expect(token.transfer.call(spender, amountToTransfer, {from: owner})) + .to.be.rejectedWith(constants.REVERT); + }); + + it('should transfer balance from sender to receiver', async () => { + const receiver = spender; + const initOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = new BigNumber(1); + await zeroEx.token.transferAsync(tokenAddress, owner, receiver, amountToTransfer); + const finalOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const finalReceiverBalance = await zeroEx.token.getBalanceAsync(tokenAddress, receiver); + + const expectedFinalOwnerBalance = initOwnerBalance.minus(amountToTransfer); + const expectedFinalReceiverBalance = amountToTransfer; + expect(finalOwnerBalance).to.be.bignumber.equal(expectedFinalOwnerBalance); + expect(finalReceiverBalance).to.be.bignumber.equal(expectedFinalReceiverBalance); + }); + + it('should return true on a 0 value transfer', async () => { + const didReturnTrue = await token.transfer.call(spender, 0, {from: owner}); + expect(didReturnTrue).to.be.true(); + }); + }); + + describe('transferFrom', () => { + it('should throw if owner has insufficient balance', async () => { + const ownerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = ownerBalance.plus(1); + await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, amountToTransfer); + return expect(token.transferFrom.call(owner, spender, amountToTransfer, {from: spender})) + .to.be.rejectedWith(constants.REVERT); + }); + + it('should throw if spender has insufficient allowance', async () => { + const ownerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = ownerBalance; + + const spenderAllowance = await zeroEx.token.getAllowanceAsync(tokenAddress, owner, spender); + const spenderAllowanceIsInsufficient = spenderAllowance.cmp(amountToTransfer) < 0; + expect(spenderAllowanceIsInsufficient).to.be.true(); + + return expect(token.transferFrom.call(owner, spender, amountToTransfer, {from: spender})) + .to.be.rejectedWith(constants.REVERT); + }); + + it('should return true on a 0 value transfer', async () => { + const amountToTransfer = 0; + const didReturnTrue = await token.transferFrom.call(owner, spender, amountToTransfer, {from: spender}); + expect(didReturnTrue).to.be.true(); + }); + + it('should not modify spender allowance if spender allowance is 2^256 - 1', async () => { + const initOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = initOwnerBalance; + const initSpenderAllowance = zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; + await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); + + const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(tokenAddress, owner, spender); + expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance); + }); + + it('should transfer the correct balances if spender has sufficient allowance', async () => { + const initOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = initOwnerBalance; + const initSpenderAllowance = initOwnerBalance; + await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); + + const newOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const newSpenderBalance = await zeroEx.token.getBalanceAsync(tokenAddress, spender); + + expect(newOwnerBalance).to.be.bignumber.equal(0); + expect(newSpenderBalance).to.be.bignumber.equal(initOwnerBalance); + }); + + it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => { + const initOwnerBalance = await zeroEx.token.getBalanceAsync(tokenAddress, owner); + const amountToTransfer = initOwnerBalance; + const initSpenderAllowance = initOwnerBalance; + await zeroEx.token.setAllowanceAsync(tokenAddress, owner, spender, initSpenderAllowance); + await zeroEx.token.transferFromAsync(tokenAddress, owner, spender, spender, amountToTransfer, { + gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS, + }); + + const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(tokenAddress, owner, spender); + expect(newSpenderAllowance).to.be.bignumber.equal(0); + }); + }); +}); diff --git a/packages/contracts/test/ts/zrxToken.ts b/packages/contracts/test/ts/zrx_token.ts index 471ee93f2..6312056b2 100644 --- a/packages/contracts/test/ts/zrxToken.ts +++ b/packages/contracts/test/ts/zrx_token.ts @@ -4,6 +4,7 @@ import * as chai from 'chai'; import Web3 = require('web3'); import {Artifacts} from '../../util/artifacts'; +import {constants} from '../../util/constants'; import {ContractInstance} from '../../util/types'; import {chaiSetup} from './utils/chai_setup'; @@ -25,9 +26,10 @@ contract('ZRXToken', (accounts: string[]) => { beforeEach(async () => { zeroEx = new ZeroEx(web3.currentProvider, { - exchangeContractAddress: Exchange.address, + exchangeContractAddress: Exchange.address, + networkId: constants.TESTRPC_NETWORK_ID, }); - zrxAddress = await zeroEx.exchange.getZRXTokenAddressAsync(); + zrxAddress = zeroEx.exchange.getZRXTokenAddress(); zrx = await ZRXToken.at(zrxAddress); MAX_UINT = zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; }); @@ -92,12 +94,14 @@ contract('ZRXToken', (accounts: string[]) => { it('should return false if owner has insufficient balance', async () => { const ownerBalance = await zeroEx.token.getBalanceAsync(zrxAddress, owner); const amountToTransfer = ownerBalance.plus(1); - let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, amountToTransfer); + let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, amountToTransfer, + {gasLimit: constants.MAX_TOKEN_APPROVE_GAS}); await zeroEx.awaitTransactionMinedAsync(txHash); const didReturnTrue = await zrx.transferFrom.call(owner, spender, amountToTransfer, {from: spender}); expect(didReturnTrue).to.be.false(); // Reset allowance - txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, new BigNumber(0)); + txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, new BigNumber(0), + {gasLimit: constants.MAX_TOKEN_APPROVE_GAS}); await zeroEx.awaitTransactionMinedAsync(txHash); }); @@ -125,7 +129,8 @@ contract('ZRXToken', (accounts: string[]) => { const initSpenderAllowance = MAX_UINT; let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance); await zeroEx.awaitTransactionMinedAsync(txHash); - txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer); + txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer, + {gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS}); await zeroEx.awaitTransactionMinedAsync(txHash); const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(zrxAddress, owner, spender); @@ -142,7 +147,8 @@ contract('ZRXToken', (accounts: string[]) => { const initSpenderAllowance = initOwnerBalance; let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance); await zeroEx.awaitTransactionMinedAsync(txHash); - txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer); + txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer, + {gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS}); await zeroEx.awaitTransactionMinedAsync(txHash); const newOwnerBalance = await zeroEx.token.getBalanceAsync(zrxAddress, owner); @@ -158,7 +164,8 @@ contract('ZRXToken', (accounts: string[]) => { const initSpenderAllowance = initOwnerBalance; let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance); await zeroEx.awaitTransactionMinedAsync(txHash); - txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer); + txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer, + {gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS}); await zeroEx.awaitTransactionMinedAsync(txHash); const newSpenderAllowance = await zeroEx.token.getAllowanceAsync(zrxAddress, owner, spender); diff --git a/packages/contracts/util/artifacts.ts b/packages/contracts/util/artifacts.ts index b15c9216f..6b05df78c 100644 --- a/packages/contracts/util/artifacts.ts +++ b/packages/contracts/util/artifacts.ts @@ -6,7 +6,9 @@ export class Artifacts { public Exchange: any; public ZRXToken: any; public DummyToken: any; + public DummyTokenV2: any; public EtherToken: any; + public EtherTokenV2: any; public MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress: any; public MaliciousToken: any; constructor(artifacts: any) { @@ -17,7 +19,9 @@ export class Artifacts { this.Exchange = artifacts.require('Exchange'); this.ZRXToken = artifacts.require('ZRXToken'); this.DummyToken = artifacts.require('DummyToken'); + this.DummyTokenV2 = artifacts.require('DummyToken_v2'); this.EtherToken = artifacts.require('EtherToken'); + this.EtherTokenV2 = artifacts.require('EtherToken_v2'); this.MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress = artifacts.require( 'MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress'); this.MaliciousToken = artifacts.require('MaliciousToken'); diff --git a/packages/contracts/util/balances.ts b/packages/contracts/util/balances.ts index fce15db6d..7f5e843a5 100644 --- a/packages/contracts/util/balances.ts +++ b/packages/contracts/util/balances.ts @@ -1,7 +1,7 @@ +import {bigNumberConfigs} from '@0xproject/utils'; import {BigNumber} from 'bignumber.js'; import * as _ from 'lodash'; -import {bigNumberConfigs} from './bignumber_config'; import {BalancesByOwner, ContractInstance} from './types'; bigNumberConfigs.configure(); diff --git a/packages/contracts/util/bignumber_config.ts b/packages/contracts/util/bignumber_config.ts deleted file mode 100644 index 38f59d341..000000000 --- a/packages/contracts/util/bignumber_config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import {BigNumber} from 'bignumber.js'; - -export const bigNumberConfigs = { - configure() { - // By default BigNumber's `toString` method converts to exponential notation if the value has - // more then 20 digits. We want to avoid this behavior, so we set EXPONENTIAL_AT to a high number - BigNumber.config({ - EXPONENTIAL_AT: 1000, - }); - }, -}; diff --git a/packages/contracts/util/constants.ts b/packages/contracts/util/constants.ts index 5beebc68c..e61b2f802 100644 --- a/packages/contracts/util/constants.ts +++ b/packages/contracts/util/constants.ts @@ -1,4 +1,9 @@ export const constants = { NULL_BYTES: '0x', INVALID_OPCODE: 'invalid opcode', + REVERT: 'revert', + TESTRPC_NETWORK_ID: 50, + MAX_ETHERTOKEN_WITHDRAW_GAS: 43000, + MAX_TOKEN_TRANSFERFROM_GAS: 80000, + MAX_TOKEN_APPROVE_GAS: 60000, }; diff --git a/packages/contracts/util/crypto.ts b/packages/contracts/util/crypto.ts index 5253b8c15..2e43ae816 100644 --- a/packages/contracts/util/crypto.ts +++ b/packages/contracts/util/crypto.ts @@ -1,4 +1,3 @@ -import {BigNumber} from 'bignumber.js'; import BN = require('bn.js'); import ABI = require('ethereumjs-abi'); import ethUtil = require('ethereumjs-util'); diff --git a/packages/contracts/util/rpc.ts b/packages/contracts/util/rpc.ts deleted file mode 100644 index 023602bd6..000000000 --- a/packages/contracts/util/rpc.ts +++ /dev/null @@ -1,43 +0,0 @@ -import 'isomorphic-fetch'; - -import * as truffleConf from '../truffle.js'; - -export class RPC { - private host: string; - private port: number; - private id: number; - constructor() { - this.host = truffleConf.networks.development.host; - this.port = truffleConf.networks.development.port; - this.id = 0; - } - public async increaseTimeAsync(time: number) { - const method = 'evm_increaseTime'; - const params = [time]; - const payload = this.toPayload(method, params); - return this.sendAsync(payload); - } - public async mineBlockAsync() { - const method = 'evm_mine'; - const payload = this.toPayload(method); - return this.sendAsync(payload); - } - private toPayload(method: string, params: any[] = []) { - const payload = JSON.stringify({ - id: this.id, - method, - params, - }); - this.id++; - return payload; - } - private async sendAsync(payload: string): Promise<any> { - const opts = { - method: 'POST', - body: payload, - }; - const response = await fetch(`http://${this.host}:${this.port}`, opts); - const responsePayload = await response.json(); - return responsePayload; - } -} diff --git a/packages/dev-utils/README.md b/packages/dev-utils/README.md new file mode 100644 index 000000000..98f31cda6 --- /dev/null +++ b/packages/dev-utils/README.md @@ -0,0 +1,10 @@ +Dev utils +------ + +Dev utils to be shared across 0x projects and packages + +## Install + +```bash +yarn add @0xproject/dev-utils +``` diff --git a/packages/dev-utils/package.json b/packages/dev-utils/package.json new file mode 100644 index 000000000..d9a0fa193 --- /dev/null +++ b/packages/dev-utils/package.json @@ -0,0 +1,37 @@ +{ + "name": "@0xproject/dev-utils", + "version": "0.0.1", + "description": "0x dev TS utils", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "scripts": { + "build": "tsc", + "clean": "shx rm -rf lib", + "lint": "tslint --project . 'src/**/*.ts'" + }, + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/0xProject/0x.js.git" + }, + "bugs": { + "url": "https://github.com/0xProject/0x.js/issues" + }, + "homepage": "https://github.com/0xProject/0x.js/packages/dev-utils/README.md", + "devDependencies": { + "@0xproject/tslint-config": "^0.2.0", + "@types/lodash": "^4.14.86", + "npm-run-all": "^4.1.2", + "shx": "^0.2.2", + "tslint": "5.8.0", + "typescript": "~2.6.1", + "types-bn": "^0.0.1", + "types-ethereumjs-util": "0xProject/types-ethereumjs-util" + }, + "dependencies": { + "bignumber.js": "~4.1.0", + "ethereumjs-util": "^5.1.2", + "lodash": "^4.17.4", + "request-promise-native": "^1.0.5" + } +} diff --git a/packages/0x.js/test/utils/blockchain_lifecycle.ts b/packages/dev-utils/src/blockchain_lifecycle.ts index 9a44ccd6f..0e493eb48 100644 --- a/packages/0x.js/test/utils/blockchain_lifecycle.ts +++ b/packages/dev-utils/src/blockchain_lifecycle.ts @@ -3,8 +3,8 @@ import {RPC} from './rpc'; export class BlockchainLifecycle { private rpc: RPC; private snapshotIdsStack: number[]; - constructor() { - this.rpc = new RPC(); + constructor(url: string) { + this.rpc = new RPC(url); this.snapshotIdsStack = []; } // TODO: In order to run these tests on an actual node, we should check if we are running against @@ -20,7 +20,4 @@ export class BlockchainLifecycle { throw new Error(`Snapshot with id #${snapshotId} failed to revert`); } } - public async mineABlock(): Promise<void> { - await this.rpc.mineBlockAsync(); - } } diff --git a/packages/dev-utils/src/index.ts b/packages/dev-utils/src/index.ts new file mode 100644 index 000000000..97c5ebc0c --- /dev/null +++ b/packages/dev-utils/src/index.ts @@ -0,0 +1,2 @@ +export {RPC} from './rpc'; +export {BlockchainLifecycle} from './blockchain_lifecycle'; diff --git a/packages/0x.js/test/utils/rpc.ts b/packages/dev-utils/src/rpc.ts index 309a96d5e..19834dbb4 100644 --- a/packages/0x.js/test/utils/rpc.ts +++ b/packages/dev-utils/src/rpc.ts @@ -1,15 +1,11 @@ import * as ethUtil from 'ethereumjs-util'; import * as request from 'request-promise-native'; -import {constants} from './constants'; - export class RPC { - private host: string; - private port: number; + private url: string; private id: number; - constructor() { - this.host = constants.RPC_HOST; - this.port = constants.RPC_PORT; + constructor(url: string) { + this.url = url; this.id = 0; } public async takeSnapshotAsync(): Promise<number> { @@ -27,6 +23,12 @@ export class RPC { const didRevert = await this.sendAsync(payload); return didRevert; } + public async increaseTimeAsync(time: number) { + const method = 'evm_increaseTime'; + const params = [time]; + const payload = this.toPayload(method, params); + return this.sendAsync(payload); + } public async mineBlockAsync(): Promise<void> { const method = 'evm_mine'; const params: any[] = []; @@ -45,7 +47,7 @@ export class RPC { private async sendAsync(payload: string): Promise<any> { const opts = { method: 'POST', - uri: `http://${this.host}:${this.port}`, + uri: this.url, body: payload, headers: { 'content-type': 'application/json', diff --git a/packages/dev-utils/tsconfig.json b/packages/dev-utils/tsconfig.json new file mode 100644 index 000000000..66609c87d --- /dev/null +++ b/packages/dev-utils/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ "es2017", "dom"], + "outDir": "lib", + "sourceMap": true, + "declaration": true, + "noImplicitAny": true, + "strictNullChecks": true + }, + "include": [ + "./src/**/*", + "../../node_modules/types-bn/index.d.ts", + "../../node_modules/types-ethereumjs-util/index.d.ts" + ] +} diff --git a/packages/dev-utils/tslint.json b/packages/dev-utils/tslint.json new file mode 100644 index 000000000..a07795151 --- /dev/null +++ b/packages/dev-utils/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "@0xproject/tslint-config" + ] +} diff --git a/packages/json-schemas/test/schema_test.ts b/packages/json-schemas/test/schema_test.ts index 8a2f9407d..067b02827 100644 --- a/packages/json-schemas/test/schema_test.ts +++ b/packages/json-schemas/test/schema_test.ts @@ -1,4 +1,3 @@ -import {promisify} from '@0xproject/utils'; import BigNumber from 'bignumber.js'; import * as chai from 'chai'; import * as dirtyChai from 'dirty-chai'; @@ -16,7 +15,6 @@ const { addressSchema, ecSignatureSchema, ecSignatureParameterSchema, - indexFilterValuesSchema, orderCancellationRequestsSchema, orderFillOrKillRequestsSchema, orderFillRequestsSchema, diff --git a/packages/kovan-faucets/Dockerfile b/packages/kovan-faucets/Dockerfile new file mode 100644 index 000000000..6d6ddc192 --- /dev/null +++ b/packages/kovan-faucets/Dockerfile @@ -0,0 +1,13 @@ +FROM node + +WORKDIR /src + +COPY package.json . +RUN npm i +RUN npm install forever -g + +COPY . . + +EXPOSE 3000 + +CMD ["forever", "./bin/server.js"] diff --git a/packages/kovan-faucets/README.md b/packages/kovan-faucets/README.md new file mode 100644 index 000000000..8903440e3 --- /dev/null +++ b/packages/kovan-faucets/README.md @@ -0,0 +1,66 @@ +Test Ether Faucet +---------------------- + +This faucet dispenses 0.1 test ether to one recipient per second. It has a max queue size of 1000. + + +## Install + +Install project dependencies: + +``` +npm install +``` + +## Start + +Set the following environment variables: + +``` +export FAUCET_ENVIRONMENT=development +export DISPENSER_ADDRESS=0x5409ed021d9299bf6814279a6a1411a7e866a631 +export DISPENSER_PRIVATE_KEY=f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d +export FAUCET_ROLLBAR_ACCESS_KEY={GET_THIS_FROM_ROLLBAR_ACCOUNT_SETTINGS} +export INFURA_API_KEY={GET_THIS_FROM_INFURA} +``` + +Infura API Key can be requested here: https://infura.io/register.html + +Note: The above public/private keys exist when running `testrpc` with the following option `--mnemonic concert load couple harbor equip island argue ramp clarify fence smart topic`. + +``` +npm run dev +``` + +## Endpoints + +```GET /ether/:recipient``` + +Where recipient_address is a hex encoded Ethereum address prefixed with `0x`. + +```GET /zrx/:recipient``` + +Where recipient_address is a hex encoded Ethereum address prefixed with `0x`. + + +```javascript +{ + "full": false, + "size": 0 +} +``` + +## Docker configs + +``` +docker run -d \ +-p 80:3000 \ +--name kovan-faucets \ +--log-opt max-size=100m \ +--log-opt max-file=20 \ +-e DISPENSER_ADDRESS=$DISPENSER_ADDRESS \ +-e DISPENSER_PRIVATE_KEY=$DISPENSER_PRIVATE_KEY \ +-e FAUCET_ROLLBAR_ACCESS_KEY=$FAUCET_ROLLBAR_ACCESS_KEY \ +-e FAUCET_ENVIRONMENT=production \ +kovan-faucets +``` diff --git a/packages/kovan-faucets/gulpfile.js b/packages/kovan-faucets/gulpfile.js new file mode 100644 index 000000000..773faf33a --- /dev/null +++ b/packages/kovan-faucets/gulpfile.js @@ -0,0 +1,92 @@ +const gulp = require('gulp'); +const nodemon = require('nodemon'); +const path = require('path'); +const webpack = require('webpack'); +const fs = require('fs'); +const nodeExternals = require('webpack-node-externals'); + +const config = { + target: 'node', + entry: [path.join(__dirname, '/src/ts/server.ts')], + output: { + path: path.join(__dirname, '/bin'), + filename: 'server.js', + }, + devtool: 'source-map', + resolve: { + modules: [ + path.join(__dirname, '/src/ts'), + 'node_modules', + ], + extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], + alias: { + ts: path.join(__dirname, '/src/ts'), + contract_artifacts: path.join(__dirname, '/src/contract_artifacts'), + }, + }, + module: { + rules: [ + { + test: /\.js$/, + loader: 'source-map-loader', + }, + { + test: /\.tsx?$/, + loader: 'awesome-typescript-loader', + }, + ], + }, + plugins: [ + new webpack.BannerPlugin({ + banner: 'require("source-map-support").install();', + raw: true, + entryOnly: false, + }), + ], + externals: nodeExternals({ + modulesDir: path.join(__dirname, '../../node_modules') + }), + watchOptions: { + ignored: /bin|node_modules|transpiled/ + }, +}; + +gulp.task('build', function(done) { + webpack(config).run(onBuild(done)); +}); + +gulp.task('watch', function() { + webpack(config).watch(100, function(err, stats) { + onBuild()(err, stats); + nodemon.restart(); + }); +}); + +gulp.task('run', ['watch'], function() { + nodemon({ + execMap: { + js: 'node', + }, + script: path.join(__dirname, 'bin/server'), + ignore: ['*'], + watch: ['foo/'], + ext: 'noop', + }).on('restart', function() { + console.log('Restarted!'); + }); +}); + +function onBuild(done) { + return function(err, stats) { + if(err) { + console.log('Error', err); + } + else { + console.log(stats.toString()); + } + + if(done) { + done(); + } + } +} diff --git a/packages/kovan-faucets/package.json b/packages/kovan-faucets/package.json new file mode 100644 index 000000000..378cd2613 --- /dev/null +++ b/packages/kovan-faucets/package.json @@ -0,0 +1,44 @@ +{ + "private": true, + "name": "@0xproject/kovan_faucets", + "version": "1.0.0", + "description": "A faucet micro-service that dispenses test ERC20 tokens or Ether", + "main": "server.js", + "scripts": { + "build": "node ../../node_modules/gulp/bin/gulp.js build", + "dev": "node ../../node_modules/gulp/bin/gulp.js run", + "start": "node ./bin/server.js", + "lint": "tslint --project . 'src/**/*.ts'", + "clean": "shx rm -rf bin" + }, + "author": "Fabio Berger", + "license": "Apache-2.0", + "dependencies": { + "@0xproject/utils": "^0.1.0", + "0x.js": "~0.27.2", + "bignumber.js": "~4.1.0", + "body-parser": "^1.17.1", + "ethereumjs-tx": "^1.3.3", + "express": "^4.15.2", + "lodash": "^4.17.4", + "rollbar": "^0.6.5", + "web3": "^0.20.0", + "web3-provider-engine": "^13.0.1" + }, + "devDependencies": { + "@0xproject/tslint-config": "^0.2.1", + "@types/body-parser": "^1.16.1", + "@types/express": "^4.0.35", + "@types/lodash": "^4.14.86", + "awesome-typescript-loader": "^3.1.3", + "gulp": "^3.9.1", + "nodemon": "^1.11.0", + "shx": "^0.2.2", + "source-map-loader": "^0.1.6", + "tslint": "5.8.0", + "typescript": "~2.6.1", + "web3-typescript-typings": "^0.7.2", + "webpack": "^3.1.0", + "webpack-node-externals": "^1.6.0" + } +} diff --git a/packages/kovan-faucets/src/ts/configs.ts b/packages/kovan-faucets/src/ts/configs.ts new file mode 100644 index 000000000..f432ba66f --- /dev/null +++ b/packages/kovan-faucets/src/ts/configs.ts @@ -0,0 +1,11 @@ +export const configs = { + DISPENSER_ADDRESS: process.env.DISPENSER_ADDRESS.toLowerCase(), + DISPENSER_PRIVATE_KEY: process.env.DISPENSER_PRIVATE_KEY, + ENVIRONMENT: process.env.FAUCET_ENVIRONMENT, + ROLLBAR_ACCESS_KEY: process.env.FAUCET_ROLLBAR_ACCESS_KEY, + RPC_URL: process.env.FAUCET_ENVIRONMENT === 'development' ? + 'http://127.0.0.1:8545' : + `https://kovan.infura.io/${process.env.INFURA_API_KEY}`, + ZRX_TOKEN_ADDRESS: '0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570', + KOVAN_NETWORK_ID: 42, +}; diff --git a/packages/kovan-faucets/src/ts/error_reporter.ts b/packages/kovan-faucets/src/ts/error_reporter.ts new file mode 100644 index 000000000..bc1844aa2 --- /dev/null +++ b/packages/kovan-faucets/src/ts/error_reporter.ts @@ -0,0 +1,40 @@ +import * as express from 'express'; +import rollbar = require('rollbar'); + +import {configs} from './configs'; +import {utils} from './utils'; + +export const errorReporter = { + setup() { + rollbar.init(configs.ROLLBAR_ACCESS_KEY, { + environment: configs.ENVIRONMENT, + }); + + rollbar.handleUncaughtExceptions(configs.ROLLBAR_ACCESS_KEY); + + process.on('unhandledRejection', (err: Error) => { + utils.consoleLog(`Uncaught exception ${err}. Stack: ${err.stack}`); + this.report(err); + process.exit(1); + }); + }, + async reportAsync(err: Error, req?: express.Request): Promise<any> { + if (configs.ENVIRONMENT === 'development') { + return; // Do not log development environment errors + } + + return new Promise((resolve, reject) => { + rollbar.handleError(err, req, (rollbarErr: Error) => { + if (rollbarErr) { + utils.consoleLog(`Error reporting to rollbar, ignoring: ${rollbarErr}`); + reject(rollbarErr); + } else { + resolve(); + } + }); + }); + }, + errorHandler() { + return rollbar.errorHandler(configs.ROLLBAR_ACCESS_KEY); + }, +}; diff --git a/packages/kovan-faucets/src/ts/ether_request_queue.ts b/packages/kovan-faucets/src/ts/ether_request_queue.ts new file mode 100644 index 000000000..0750e6170 --- /dev/null +++ b/packages/kovan-faucets/src/ts/ether_request_queue.ts @@ -0,0 +1,27 @@ +import {promisify} from '@0xproject/utils'; +import * as _ from 'lodash'; + +import {configs} from './configs'; +import {errorReporter} from './error_reporter'; +import {RequestQueue} from './request_queue'; +import {utils} from './utils'; + +const DISPENSE_AMOUNT_ETHER = 0.1; + +export class EtherRequestQueue extends RequestQueue { + protected async processNextRequestFireAndForgetAsync(recipientAddress: string) { + utils.consoleLog(`Processing ETH ${recipientAddress}`); + const sendTransactionAsync = promisify(this.web3.eth.sendTransaction); + try { + const txHash = await sendTransactionAsync({ + from: configs.DISPENSER_ADDRESS, + to: recipientAddress, + value: this.web3.toWei(DISPENSE_AMOUNT_ETHER, 'ether'), + }); + utils.consoleLog(`Sent ${DISPENSE_AMOUNT_ETHER} ETH to ${recipientAddress} tx: ${txHash}`); + } catch (err) { + utils.consoleLog(`Unexpected err: ${err} - ${JSON.stringify(err)}`); + await errorReporter.reportAsync(err); + } + } +} diff --git a/packages/kovan-faucets/src/ts/global.d.ts b/packages/kovan-faucets/src/ts/global.d.ts new file mode 100644 index 000000000..97cd35680 --- /dev/null +++ b/packages/kovan-faucets/src/ts/global.d.ts @@ -0,0 +1,26 @@ +declare module 'rollbar'; +declare module 'web3-provider-engine'; +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 */ + export default json; + /* tslint:enable */ +} + +// Ethereumjs-tx declarations +declare module 'ethereumjs-tx' { + class EthereumTx { + public raw: Buffer[]; + public r: Buffer; + public s: Buffer; + public v: Buffer; + public serialize(): Buffer; + public sign(buffer: Buffer): void; + constructor(txParams: any); + } + export = EthereumTx; +} diff --git a/packages/kovan-faucets/src/ts/handler.ts b/packages/kovan-faucets/src/ts/handler.ts new file mode 100644 index 000000000..1c6866a1c --- /dev/null +++ b/packages/kovan-faucets/src/ts/handler.ts @@ -0,0 +1,91 @@ +import * as express from 'express'; +import * as _ from 'lodash'; +import ProviderEngine = require('web3-provider-engine'); +import HookedWalletSubprovider = require('web3-provider-engine/subproviders/hooked-wallet'); +import NonceSubprovider = require('web3-provider-engine/subproviders/nonce-tracker'); +import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); + +import {configs} from './configs'; +import {EtherRequestQueue} from './ether_request_queue'; +import {idManagement} from './id_management'; +import {utils} from './utils'; +import {ZRXRequestQueue} from './zrx_request_queue'; + +// HACK: web3 leaks XMLHttpRequest into the global scope and causes requests to hang +// because they are using the wrong XHR package. +// Issue: https://github.com/trufflesuite/truffle-contract/issues/14 +// tslint:disable-next-line:ordered-imports +import * as Web3 from 'web3'; + +export class Handler { + private etherRequestQueue: EtherRequestQueue; + private zrxRequestQueue: ZRXRequestQueue; + private web3: Web3; + constructor() { + // Setup provider engine to talk with RPC node + const providerObj = this.createProviderEngine(configs.RPC_URL); + this.web3 = new Web3(providerObj); + + this.etherRequestQueue = new EtherRequestQueue(this.web3); + this.zrxRequestQueue = new ZRXRequestQueue(this.web3); + } + public dispenseEther(req: express.Request, res: express.Response) { + const recipientAddress = req.params.recipient; + if (_.isUndefined(recipientAddress) || !this.isValidEthereumAddress(recipientAddress)) { + res.status(400).send('INVALID_REQUEST'); + return; + } + const lowerCaseRecipientAddress = recipientAddress.toLowerCase(); + const didAddToQueue = this.etherRequestQueue.add(lowerCaseRecipientAddress); + if (!didAddToQueue) { + res.status(503).send('QUEUE_IS_FULL'); + return; + } + utils.consoleLog(`Added ${lowerCaseRecipientAddress} to the ETH queue`); + res.status(200).end(); + } + public dispenseZRX(req: express.Request, res: express.Response) { + const recipientAddress = req.params.recipient; + if (_.isUndefined(recipientAddress) || !this.isValidEthereumAddress(recipientAddress)) { + res.status(400).send('INVALID_REQUEST'); + return; + } + const lowerCaseRecipientAddress = recipientAddress.toLowerCase(); + const didAddToQueue = this.zrxRequestQueue.add(lowerCaseRecipientAddress); + if (!didAddToQueue) { + res.status(503).send('QUEUE_IS_FULL'); + return; + } + utils.consoleLog(`Added ${lowerCaseRecipientAddress} to the ZRX queue`); + res.status(200).end(); + } + public getQueueInfo(req: express.Request, res: express.Response) { + res.setHeader('Content-Type', 'application/json'); + const payload = JSON.stringify({ + ether: { + full: this.etherRequestQueue.isFull(), + size: this.etherRequestQueue.size(), + }, + zrx: { + full: this.zrxRequestQueue.isFull(), + size: this.zrxRequestQueue.size(), + }, + }); + res.status(200).send(payload); + } + // tslint:disable-next-line:prefer-function-over-method + private createProviderEngine(rpcUrl: string) { + const engine = new ProviderEngine(); + engine.addProvider(new NonceSubprovider()); + engine.addProvider(new HookedWalletSubprovider(idManagement)); + engine.addProvider(new RpcSubprovider({ + rpcUrl, + })); + engine.start(); + return engine; + } + private isValidEthereumAddress(address: string): boolean { + const lowercaseAddress = address.toLowerCase(); + return this.web3.isAddress(lowercaseAddress); + } +} diff --git a/packages/kovan-faucets/src/ts/id_management.ts b/packages/kovan-faucets/src/ts/id_management.ts new file mode 100644 index 000000000..89d6f6fd1 --- /dev/null +++ b/packages/kovan-faucets/src/ts/id_management.ts @@ -0,0 +1,25 @@ +import EthereumTx = require('ethereumjs-tx'); + +import {configs} from './configs'; +import {utils} from './utils'; + +type Callback = (err: Error, accounts: any) => void; + +export const idManagement = { + getAccounts(callback: Callback) { + utils.consoleLog(`configs.DISPENSER_ADDRESS: ${configs.DISPENSER_ADDRESS}`); + callback(null, [ + configs.DISPENSER_ADDRESS, + ]); + }, + approveTransaction(txData: object, callback: Callback) { + callback(null, true); + }, + signTransaction(txData: object, callback: Callback) { + const tx = new EthereumTx(txData); + const privateKeyBuffer = new Buffer(configs.DISPENSER_PRIVATE_KEY, 'hex'); + tx.sign(privateKeyBuffer); + const rawTx = `0x${tx.serialize().toString('hex')}`; + callback(null, rawTx); + }, +}; diff --git a/packages/kovan-faucets/src/ts/request_queue.ts b/packages/kovan-faucets/src/ts/request_queue.ts new file mode 100644 index 000000000..0b5e66ae9 --- /dev/null +++ b/packages/kovan-faucets/src/ts/request_queue.ts @@ -0,0 +1,57 @@ +import * as _ from 'lodash'; +import * as timers from 'timers'; + +// HACK: web3 leaks XMLHttpRequest into the global scope and causes requests to hang +// because they are using the wrong XHR package. +// Issue: https://github.com/trufflesuite/truffle-contract/issues/14 +// tslint:disable-next-line:ordered-imports +import * as Web3 from 'web3'; + +const MAX_QUEUE_SIZE = 500; +const DEFAULT_QUEUE_INTERVAL_MS = 1000; + +export class RequestQueue { + protected queueIntervalMs: number; + protected queue: string[]; + protected queueIntervalId: NodeJS.Timer; + protected web3: Web3; + constructor(web3: any) { + this.queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS; + this.queue = []; + + this.web3 = web3; + + this.start(); + } + public add(recipientAddress: string): boolean { + if (this.isFull()) { + return false; + } + this.queue.push(recipientAddress); + return true; + } + public size(): number { + return this.queue.length; + } + public isFull(): boolean { + return this.size() >= MAX_QUEUE_SIZE; + } + protected start() { + this.queueIntervalId = timers.setInterval(() => { + if (this.queue.length === 0) { + return; + } + const recipientAddress = this.queue.shift(); + // tslint:disable-next-line:no-floating-promises + this.processNextRequestFireAndForgetAsync(recipientAddress); + + }, this.queueIntervalMs); + } + protected stop() { + clearInterval(this.queueIntervalId); + } + // tslint:disable-next-line:prefer-function-over-method + protected async processNextRequestFireAndForgetAsync(recipientAddress: string) { + throw new Error('Expected processNextRequestFireAndForgetAsync to be implemented by a superclass'); + } +} diff --git a/packages/kovan-faucets/src/ts/server.ts b/packages/kovan-faucets/src/ts/server.ts new file mode 100644 index 000000000..fbb9caf1e --- /dev/null +++ b/packages/kovan-faucets/src/ts/server.ts @@ -0,0 +1,26 @@ +import * as bodyParser from 'body-parser'; +import * as express from 'express'; + +import {errorReporter} from './error_reporter'; +import {Handler} from './handler'; + +// Setup the errorReporter to catch uncaught exceptions and unhandled rejections +errorReporter.setup(); + +const app = express(); +app.use(bodyParser.json()); // for parsing application/json +app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); + next(); +}); + +const handler = new Handler(); +app.get('/ping', (req: express.Request, res: express.Response) => { res.status(200).send('pong'); }); +app.get('/ether/:recipient', handler.dispenseEther.bind(handler)); +app.get('/zrx/:recipient', handler.dispenseZRX.bind(handler)); + +// Log to rollbar any errors unhandled by handlers +app.use(errorReporter.errorHandler()); +const port = process.env.PORT || 3000; +app.listen(port); diff --git a/packages/kovan-faucets/src/ts/utils.ts b/packages/kovan-faucets/src/ts/utils.ts new file mode 100644 index 000000000..893f82ca3 --- /dev/null +++ b/packages/kovan-faucets/src/ts/utils.ts @@ -0,0 +1,7 @@ +export const utils = { + consoleLog(message: string) { + /* tslint:disable */ + console.log(message); + /* tslint:enable */ + }, +}; diff --git a/packages/kovan-faucets/src/ts/zrx_request_queue.ts b/packages/kovan-faucets/src/ts/zrx_request_queue.ts new file mode 100644 index 000000000..3b505690f --- /dev/null +++ b/packages/kovan-faucets/src/ts/zrx_request_queue.ts @@ -0,0 +1,42 @@ +import {ZeroEx} from '0x.js'; +import BigNumber from 'bignumber.js'; +import * as _ from 'lodash'; + +import {configs} from './configs'; +import {errorReporter} from './error_reporter'; +import {RequestQueue} from './request_queue'; +import {utils} from './utils'; + +// HACK: web3 leaks XMLHttpRequest into the global scope and causes requests to hang +// because they are using the wrong XHR package. +// Issue: https://github.com/trufflesuite/truffle-contract/issues/14 +// tslint:disable-next-line:ordered-imports +import * as Web3 from 'web3'; + +const DISPENSE_AMOUNT_ZRX = new BigNumber(0.1); +const QUEUE_INTERVAL_MS = 5000; + +export class ZRXRequestQueue extends RequestQueue { + private zeroEx: ZeroEx; + constructor(web3: Web3) { + super(web3); + this.queueIntervalMs = QUEUE_INTERVAL_MS; + const zeroExConfig = { + networkId: configs.KOVAN_NETWORK_ID, + }; + this.zeroEx = new ZeroEx(web3.currentProvider, zeroExConfig); + } + protected async processNextRequestFireAndForgetAsync(recipientAddress: string) { + utils.consoleLog(`Processing ZRX ${recipientAddress}`); + const baseUnitAmount = ZeroEx.toBaseUnitAmount(DISPENSE_AMOUNT_ZRX, 18); + try { + await this.zeroEx.token.transferAsync( + configs.ZRX_TOKEN_ADDRESS, configs.DISPENSER_ADDRESS, recipientAddress, baseUnitAmount, + ); + utils.consoleLog(`Sent ${DISPENSE_AMOUNT_ZRX} ZRX to ${recipientAddress}`); + } catch (err) { + utils.consoleLog(`Unexpected err: ${err} - ${JSON.stringify(err)}`); + await errorReporter.reportAsync(err); + } + } +} diff --git a/packages/kovan-faucets/tsconfig.json b/packages/kovan-faucets/tsconfig.json new file mode 100644 index 000000000..6b14a6f6b --- /dev/null +++ b/packages/kovan-faucets/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ "es2015", "dom" ], + "outDir": "lib", + "sourceMap": true, + "declaration": true, + "noImplicitAny": true, + "experimentalDecorators": true, + }, + "include": [ + "../../node_modules/web3-typescript-typings/index.d.ts", + "./src/ts/**/*" + ] +} diff --git a/packages/kovan-faucets/tslint.json b/packages/kovan-faucets/tslint.json new file mode 100644 index 000000000..a07795151 --- /dev/null +++ b/packages/kovan-faucets/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "@0xproject/tslint-config" + ] +} diff --git a/packages/subproviders/package.json b/packages/subproviders/package.json index b0c5686a6..8a222457d 100644 --- a/packages/subproviders/package.json +++ b/packages/subproviders/package.json @@ -31,6 +31,7 @@ }, "devDependencies": { "@0xproject/tslint-config": "^0.2.1", + "@0xproject/utils": "^0.1.0", "@types/lodash": "^4.14.86", "@types/mocha": "^2.2.42", "@types/node": "^8.0.53", diff --git a/packages/subproviders/src/globals.d.ts b/packages/subproviders/src/globals.d.ts index 400bbef5b..adef23806 100644 --- a/packages/subproviders/src/globals.d.ts +++ b/packages/subproviders/src/globals.d.ts @@ -5,6 +5,7 @@ declare module 'es6-promisify'; // tslint:disable:max-classes-per-file // tslint:disable:class-name +// tslint:disable:async-suffix // tslint:disable:completed-docs // Ethereumjs-tx declarations diff --git a/packages/subproviders/src/subproviders/ledger.ts b/packages/subproviders/src/subproviders/ledger.ts index 578f6ff6f..9ffc105a4 100644 --- a/packages/subproviders/src/subproviders/ledger.ts +++ b/packages/subproviders/src/subproviders/ledger.ts @@ -1,9 +1,7 @@ import {assert} from '@0xproject/assert'; import {addressUtils} from '@0xproject/utils'; -import promisify = require('es6-promisify'); import EthereumTx = require('ethereumjs-tx'); import ethUtil = require('ethereumjs-util'); -import * as ledger from 'ledgerco'; import * as _ from 'lodash'; import Semaphore from 'semaphore-async-await'; import Web3 = require('web3'); @@ -23,7 +21,6 @@ const DEFAULT_DERIVATION_PATH = `44'/60'/0'`; const NUM_ADDRESSES_TO_FETCH = 10; const ASK_FOR_ON_DEVICE_CONFIRMATION = false; const SHOULD_GET_CHAIN_CODE = false; -const HEX_REGEX = /^[0-9A-Fa-f]+$/g; export class LedgerSubprovider extends Subprovider { private _nonceLock: Semaphore; @@ -34,18 +31,6 @@ export class LedgerSubprovider extends Subprovider { private _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync; private _ledgerClientIfExists?: LedgerEthereumClient; private _shouldAlwaysAskForConfirmation: boolean; - private static isValidHex(data: string) { - if (!_.isString(data)) { - return false; - } - const isHexPrefixed = data.slice(0, 2) === '0x'; - if (!isHexPrefixed) { - return false; - } - const nonPrefixed = data.slice(2); - const isValid = nonPrefixed.match(HEX_REGEX); - return isValid; - } private static validateSender(sender: string) { if (_.isUndefined(sender) || !addressUtils.isAddress(sender)) { throw new Error(LedgerSubproviderErrors.SenderInvalidOrNotSupplied); diff --git a/packages/subproviders/src/subproviders/redundant_rpc.ts b/packages/subproviders/src/subproviders/redundant_rpc.ts index 80462bbfb..f688061ea 100644 --- a/packages/subproviders/src/subproviders/redundant_rpc.ts +++ b/packages/subproviders/src/subproviders/redundant_rpc.ts @@ -33,6 +33,7 @@ export class RedundantRPCSubprovider extends Subprovider { }); }); } + // tslint:disable-next-line:async-suffix public async handleRequest(payload: JSONRPCPayload, next: () => void, end: (err: Error|null, data?: any) => void): Promise<void> { const rpcsCopy = this.rpcs.slice(); diff --git a/packages/subproviders/src/subproviders/subprovider.ts b/packages/subproviders/src/subproviders/subprovider.ts index 64d97b958..41dde4238 100644 --- a/packages/subproviders/src/subproviders/subprovider.ts +++ b/packages/subproviders/src/subproviders/subprovider.ts @@ -11,7 +11,6 @@ import { */ export class Subprovider { private engine: any; - private currentBlock: any; // Ported from: https://github.com/MetaMask/provider-engine/blob/master/util/random-id.js private static getRandomId() { const extraDigits = 3; @@ -34,9 +33,6 @@ export class Subprovider { } public setEngine(engine: any): void { this.engine = engine; - engine.on('block', (block: any) => { - this.currentBlock = block; - }); } public async emitPayloadAsync(payload: JSONRPCPayload): Promise<any> { const finalPayload = Subprovider.createFinalPayload(payload); diff --git a/packages/subproviders/src/types.ts b/packages/subproviders/src/types.ts index 38dc1e67e..1e7d3eab0 100644 --- a/packages/subproviders/src/types.ts +++ b/packages/subproviders/src/types.ts @@ -1,5 +1,4 @@ import * as _ from 'lodash'; -import * as Web3 from 'web3'; export interface LedgerCommunicationClient { close_async: () => Promise<void>; diff --git a/packages/subproviders/test/integration/ledger_subprovider_test.ts b/packages/subproviders/test/integration/ledger_subprovider_test.ts index 75f6d47fe..ab4ffb19a 100644 --- a/packages/subproviders/test/integration/ledger_subprovider_test.ts +++ b/packages/subproviders/test/integration/ledger_subprovider_test.ts @@ -2,20 +2,16 @@ import * as chai from 'chai'; import promisify = require('es6-promisify'); import * as ethUtils from 'ethereumjs-util'; import * as _ from 'lodash'; -import * as mocha from 'mocha'; import Web3 = require('web3'); import Web3ProviderEngine = require('web3-provider-engine'); import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); import { - ECSignature, ledgerEthereumNodeJsClientFactoryAsync, LedgerSubprovider, } from '../../src'; import { DoneCallback, - LedgerGetAddressResult, - PartialTxParams, } from '../../src/types'; import {chaiSetup} from '../chai_setup'; import {reportCallbackErrors} from '../utils/report_callback_errors'; diff --git a/packages/subproviders/test/unit/ledger_subprovider_test.ts b/packages/subproviders/test/unit/ledger_subprovider_test.ts index 964df5db9..bd4d93325 100644 --- a/packages/subproviders/test/unit/ledger_subprovider_test.ts +++ b/packages/subproviders/test/unit/ledger_subprovider_test.ts @@ -6,14 +6,11 @@ import Web3ProviderEngine = require('web3-provider-engine'); import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); import { - ECSignature, LedgerSubprovider, } from '../../src'; import { DoneCallback, - ECSignatureString, LedgerCommunicationClient, - LedgerGetAddressResult, LedgerSubproviderErrors, } from '../../src/types'; import {chaiSetup} from '../chai_setup'; diff --git a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts index edeb1d5a2..2f1676915 100644 --- a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts +++ b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts @@ -11,6 +11,7 @@ import {chaiSetup} from '../chai_setup'; import {reportCallbackErrors} from '../utils/report_callback_errors'; const expect = chai.expect; +chaiSetup.configure(); describe('RedundantRpcSubprovider', () => { let provider: Web3ProviderEngine; diff --git a/packages/subproviders/test/utils/report_callback_errors.ts b/packages/subproviders/test/utils/report_callback_errors.ts index 8a8f4d966..0aaef3f05 100644 --- a/packages/subproviders/test/utils/report_callback_errors.ts +++ b/packages/subproviders/test/utils/report_callback_errors.ts @@ -1,4 +1,4 @@ -import { DoneCallback } from '../../src/types'; +import {DoneCallback} from '../../src/types'; export const reportCallbackErrors = (done: DoneCallback) => { return (f: (...args: any[]) => void) => { diff --git a/packages/tslint-config/package.json b/packages/tslint-config/package.json index a4b5d4466..888ff675a 100644 --- a/packages/tslint-config/package.json +++ b/packages/tslint-config/package.json @@ -3,6 +3,11 @@ "version": "0.2.1", "description": "Lint rules related to 0xProject for TSLint", "main": "tslint.json", + "scripts": { + "build": "tsc", + "clean": "shx rm -rf lib", + "lint": "tslint --project . 'rules/**/*.ts'" + }, "files": [ "tslint.js", "README.md", @@ -29,10 +34,14 @@ }, "homepage": "https://github.com/0xProject/0x.js/packages/tslint-config/README.md", "devDependencies": { + "@types/lodash": "^4.14.86", + "shx": "^0.2.2", "tslint": "5.8.0", + "tslint-eslint-rules": "^4.1.1", "typescript": "~2.6.1" }, "dependencies": { + "lodash": "^4.17.4", "tslint-react": "^3.2.0" } } diff --git a/packages/tslint-config/rules/asyncSuffixRule.ts b/packages/tslint-config/rules/asyncSuffixRule.ts new file mode 100644 index 000000000..c6ae5189c --- /dev/null +++ b/packages/tslint-config/rules/asyncSuffixRule.ts @@ -0,0 +1,10 @@ +import * as Lint from 'tslint'; +import * as ts from 'typescript'; + +import {AsyncSuffixWalker} from './walkers/async_suffix'; + +export class Rule extends Lint.Rules.AbstractRule { + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new AsyncSuffixWalker(sourceFile, this.getOptions())); + } +} diff --git a/packages/tslint-config/rules/walkers/async_suffix.ts b/packages/tslint-config/rules/walkers/async_suffix.ts new file mode 100644 index 000000000..7fa7a78b8 --- /dev/null +++ b/packages/tslint-config/rules/walkers/async_suffix.ts @@ -0,0 +1,24 @@ +import * as _ from 'lodash'; +import * as Lint from 'tslint'; +import * as ts from 'typescript'; + +export class AsyncSuffixWalker extends Lint.RuleWalker { + public static FAILURE_STRING = 'async functions must have an Async suffix'; + public visitMethodDeclaration(node: ts.MethodDeclaration): void { + const methodNameNode = node.name; + const methodName = methodNameNode.getText(); + if (!_.isUndefined(node.type)) { + if (node.type.kind === ts.SyntaxKind.TypeReference) { + // tslint:disable-next-line:no-unnecessary-type-assertion + const returnTypeName = (node.type as ts.TypeReferenceNode).typeName.getText(); + if (returnTypeName === 'Promise' && !methodName.endsWith('Async')) { + const failure = this.createFailure( + methodNameNode.getStart(), methodNameNode.getWidth(), AsyncSuffixWalker.FAILURE_STRING, + ); + this.addFailure(failure); + } + } + } + super.visitMethodDeclaration(node); + } +} diff --git a/packages/tslint-config/tsconfig.json b/packages/tslint-config/tsconfig.json new file mode 100644 index 000000000..7661a9d07 --- /dev/null +++ b/packages/tslint-config/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ "es2017", "dom"], + "outDir": "lib", + "sourceMap": true, + "declaration": true, + "noImplicitAny": true, + "strictNullChecks": true + }, + "include": [ + "./rules/**/*" + ] +} diff --git a/packages/tslint-config/tslint.json b/packages/tslint-config/tslint.json index 0921a3954..acb6876c3 100644 --- a/packages/tslint-config/tslint.json +++ b/packages/tslint-config/tslint.json @@ -1,12 +1,14 @@ { "extends": [ "tslint:latest", - "tslint-react" + "tslint-react", + "tslint-eslint-rules" ], "rules": { "adjacent-overload-signatures": true, "arrow-parens": [true, "ban-single-arg-parens"], "arrow-return-shorthand": true, + "async-suffix": true, "await-promise": true, "binary-expression-operand-order": true, "callable-types": true, @@ -50,8 +52,10 @@ "no-string-throw": true, "no-submodule-imports": false, "no-unnecessary-type-assertion": true, + "no-unused-variable": [true, {"ignore-pattern": "^_\\d*"}], "no-implicit-dependencies": [true, "dev"], "number-literal-format": true, + "object-curly-spacing": [true, "never"], "object-literal-sort-keys": false, "ordered-imports": [ true, @@ -101,5 +105,6 @@ "jsx-self-close": true, "jsx-wrap-multiline": false, "jsx-no-bind": false - } + }, + "rulesDirectory": "lib" } diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 8d69af63d..3db1aebe1 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -8,6 +8,10 @@ export interface TxData { nonce?: number; } +export interface TxDataPayable extends TxData { + value?: BigNumber; +} + export interface TransactionReceipt { blockHash: string; blockNumber: number; diff --git a/packages/0x.js/src/bignumber_config.ts b/packages/utils/src/bignumber_config.ts index 2d5214e6f..2d5214e6f 100644 --- a/packages/0x.js/src/bignumber_config.ts +++ b/packages/utils/src/bignumber_config.ts diff --git a/packages/0x.js/src/utils/class_utils.ts b/packages/utils/src/class_utils.ts index 04e60ee57..04e60ee57 100644 --- a/packages/0x.js/src/utils/class_utils.ts +++ b/packages/utils/src/class_utils.ts diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index edfd192b2..403bc7236 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,2 +1,5 @@ export {promisify} from './promisify'; export {addressUtils} from './address_utils'; +export {classUtils} from './class_utils'; +export {intervalUtils} from './interval_utils'; +export {bigNumberConfigs} from './bignumber_config'; diff --git a/packages/0x.js/src/utils/interval_utils.ts b/packages/utils/src/interval_utils.ts index 62b79f2f5..62b79f2f5 100644 --- a/packages/0x.js/src/utils/interval_utils.ts +++ b/packages/utils/src/interval_utils.ts diff --git a/packages/website/package.json b/packages/website/package.json index f005668f8..a6703af7e 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,5 +1,5 @@ { - "name": "website", + "name": "@0xproject/website", "version": "0.0.2", "private": true, "description": "Website and 0x portal dapp", @@ -18,7 +18,7 @@ "author": "Fabio Berger", "license": "Apache-2.0", "dependencies": { - "0x.js": "0.27.1", + "0x.js": "~0.27.2", "@0xproject/subproviders": "^0.1.0", "accounting": "^0.4.1", "basscss": "^8.0.3", diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 172ba6b52..331bafa71 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -1,7 +1,6 @@ import { BlockParam, DecodedLogEvent, - ExchangeContractErrs, ExchangeContractEventArgs, ExchangeEvents, IndexedFilterValues, @@ -14,7 +13,6 @@ import { Token as ZeroExToken, TransactionReceiptWithDecodedLogs, ZeroEx, - ZeroExError, } from '0x.js'; import { InjectedWeb3Subprovider, @@ -23,11 +21,8 @@ import { LedgerWalletSubprovider, RedundantRPCSubprovider, } from '@0xproject/subproviders'; -import {promisify} from '@0xproject/utils'; +import {intervalUtils, promisify} from '@0xproject/utils'; import BigNumber from 'bignumber.js'; -import compareVersions = require('compare-versions'); -import ethUtil = require('ethereumjs-util'); -import findVersions = require('find-versions'); import * as _ from 'lodash'; import * as React from 'react'; import contract = require('truffle-contract'); @@ -40,7 +35,6 @@ import { BlockchainCallErrs, BlockchainErrs, ContractInstance, - ContractResponse, EtherscanLinkSuffixes, ProviderType, Side, @@ -60,7 +54,6 @@ import FilterSubprovider = require('web3-provider-engine/subproviders/filters'); import * as MintableArtifacts from '../contracts/Mintable.json'; -const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 45730; const BLOCK_NUMBER_BACK_TRACK = 50; export class Blockchain { @@ -70,12 +63,10 @@ export class Blockchain { private dispatcher: Dispatcher; private web3Wrapper?: Web3Wrapper; private exchangeAddress: string; - private tokenTransferProxy: ContractInstance; - private tokenRegistry: ContractInstance; private userAddress: string; private cachedProvider: Web3.Provider; private ledgerSubprovider: LedgerWalletSubprovider; - private zrxPollIntervalId: number; + private zrxPollIntervalId: NodeJS.Timer; private static async onPageLoadAsync() { if (document.readyState === 'complete') { return; // Already loaded @@ -359,7 +350,7 @@ export class Blockchain { const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); - this.zrxPollIntervalId = window.setInterval(async () => { + this.zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { const [balance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); if (!balance.eq(currBalance)) { this.dispatcher.replaceTokenBalanceByAddress(token.address, balance); @@ -506,8 +497,7 @@ export class Blockchain { await this.fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); // Start a subscription for new logs - const exchangeAddress = this.getExchangeContractAddressIfExists(); - const subscriptionId = this.zeroEx.exchange.subscribe( + this.zeroEx.exchange.subscribe( ExchangeEvents.LogFill, indexFilterValues, async (err: Error, decodedLogEvent: DecodedLogEvent<LogFillContractEventArgs>) => { if (err) { diff --git a/packages/website/ts/components/dialogs/portal_disclaimer_dialog.tsx b/packages/website/ts/components/dialogs/portal_disclaimer_dialog.tsx index 1d90624ee..bfff7fbb5 100644 --- a/packages/website/ts/components/dialogs/portal_disclaimer_dialog.tsx +++ b/packages/website/ts/components/dialogs/portal_disclaimer_dialog.tsx @@ -2,7 +2,6 @@ import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import {colors} from 'material-ui/styles'; import * as React from 'react'; -import {constants} from 'ts/utils/constants'; interface PortalDisclaimerDialogProps { isOpen: boolean; diff --git a/packages/website/ts/components/dialogs/send_dialog.tsx b/packages/website/ts/components/dialogs/send_dialog.tsx index 31afc3386..0f3516993 100644 --- a/packages/website/ts/components/dialogs/send_dialog.tsx +++ b/packages/website/ts/components/dialogs/send_dialog.tsx @@ -2,13 +2,10 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; -import RadioButton from 'material-ui/RadioButton'; -import RadioButtonGroup from 'material-ui/RadioButton/RadioButtonGroup'; import * as React from 'react'; import {AddressInput} from 'ts/components/inputs/address_input'; -import {EthAmountInput} from 'ts/components/inputs/eth_amount_input'; import {TokenAmountInput} from 'ts/components/inputs/token_amount_input'; -import {Side, Token, TokenState} from 'ts/types'; +import {Token, TokenState} from 'ts/types'; interface SendDialogProps { onComplete: (recipient: string, value: BigNumber) => void; diff --git a/packages/website/ts/components/dialogs/track_token_confirmation_dialog.tsx b/packages/website/ts/components/dialogs/track_token_confirmation_dialog.tsx index 70c7d1ab6..2d45009d5 100644 --- a/packages/website/ts/components/dialogs/track_token_confirmation_dialog.tsx +++ b/packages/website/ts/components/dialogs/track_token_confirmation_dialog.tsx @@ -1,14 +1,12 @@ import * as _ from 'lodash'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Blockchain} from 'ts/blockchain'; import {TrackTokenConfirmation} from 'ts/components/track_token_confirmation'; import {trackedTokenStorage} from 'ts/local_storage/tracked_token_storage'; import {Dispatcher} from 'ts/redux/dispatcher'; import {Token, TokenByAddress} from 'ts/types'; -import {constants} from 'ts/utils/constants'; interface TrackTokenConfirmationDialogProps { tokens: Token[]; diff --git a/packages/website/ts/components/fill_order.tsx b/packages/website/ts/components/fill_order.tsx index 77a9cfddb..40a9b87d6 100644 --- a/packages/website/ts/components/fill_order.tsx +++ b/packages/website/ts/components/fill_order.tsx @@ -5,8 +5,6 @@ import * as _ from 'lodash'; import {Card, CardHeader, CardText} from 'material-ui/Card'; import Divider from 'material-ui/Divider'; import RaisedButton from 'material-ui/RaisedButton'; -import TextField from 'material-ui/TextField'; -import * as moment from 'moment'; import * as React from 'react'; import {Link} from 'react-router-dom'; import {Blockchain} from 'ts/blockchain'; @@ -18,18 +16,13 @@ import {Alert} from 'ts/components/ui/alert'; import {EthereumAddress} from 'ts/components/ui/ethereum_address'; import {Identicon} from 'ts/components/ui/identicon'; import {VisualOrder} from 'ts/components/visual_order'; -import {trackedTokenStorage} from 'ts/local_storage/tracked_token_storage'; import {Dispatcher} from 'ts/redux/dispatcher'; import {orderSchema} from 'ts/schemas/order_schema'; import {SchemaValidator} from 'ts/schemas/validator'; import { AlertTypes, BlockchainErrs, - ContractResponse, - ExchangeContractErrs, Order, - OrderToken, - Side, Token, TokenByAddress, TokenStateByAddress, @@ -530,8 +523,6 @@ export class FillOrder extends React.Component<FillOrderProps, FillOrderState> { }); const parsedOrder = this.state.parsedOrder; - const orderHash = parsedOrder.signature.hash; - const unavailableTakerAmount = await this.props.blockchain.getUnavailableTakerAmountAsync(orderHash); const takerFillAmount = this.props.orderFillAmount; if (_.isUndefined(this.props.userAddress)) { diff --git a/packages/website/ts/components/footer.tsx b/packages/website/ts/components/footer.tsx index 5e3c0479a..b26523094 100644 --- a/packages/website/ts/components/footer.tsx +++ b/packages/website/ts/components/footer.tsx @@ -3,11 +3,7 @@ import * as React from 'react'; import { Link, } from 'react-router-dom'; -import {HashLink} from 'react-router-hash-link'; -import { - Link as ScrollLink, -} from 'react-scroll'; -import {Styles, WebsitePaths} from 'ts/types'; +import {WebsitePaths} from 'ts/types'; import {constants} from 'ts/utils/constants'; interface MenuItemsBySection { @@ -229,31 +225,4 @@ export class Footer extends React.Component<FooterProps, FooterState> { </div> ); } - private renderHomepageLink(title: string) { - const hash = title.toLowerCase(); - if (this.props.location.pathname === WebsitePaths.Home) { - return ( - <ScrollLink - style={linkStyle} - to={hash} - smooth={true} - offset={0} - duration={constants.HOME_SCROLL_DURATION_MS} - containerId="home" - > - {title} - </ScrollLink> - ); - } else { - return ( - <HashLink - to={`/#${hash}`} - className="text-decoration-none" - style={linkStyle} - > - {title} - </HashLink> - ); - } - } } diff --git a/packages/website/ts/components/generate_order/asset_picker.tsx b/packages/website/ts/components/generate_order/asset_picker.tsx index 633d6a017..08b4a909e 100644 --- a/packages/website/ts/components/generate_order/asset_picker.tsx +++ b/packages/website/ts/components/generate_order/asset_picker.tsx @@ -1,9 +1,6 @@ import * as _ from 'lodash'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; -import GridList from 'material-ui/GridList/GridList'; -import GridTile from 'material-ui/GridList/GridTile'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Blockchain} from 'ts/blockchain'; import {NewTokenForm} from 'ts/components/generate_order/new_token_form'; @@ -12,15 +9,12 @@ import {TokenIcon} from 'ts/components/ui/token_icon'; import {trackedTokenStorage} from 'ts/local_storage/tracked_token_storage'; import {Dispatcher} from 'ts/redux/dispatcher'; import { - AssetToken, DialogConfigs, - Styles, Token, TokenByAddress, TokenState, TokenVisibility, } from 'ts/types'; -import {utils} from 'ts/utils/utils'; const TOKEN_ICON_DIMENSION = 100; const TILE_DIMENSION = 146; @@ -219,21 +213,6 @@ export class AssetPicker extends React.Component<AssetPickerProps, AssetPickerSt }); } } - private getTitle() { - switch (this.state.assetView) { - case AssetViews.ASSET_PICKER: - return 'Select token'; - - case AssetViews.NEW_TOKEN_FORM: - return 'Add an ERC20 token'; - - case AssetViews.CONFIRM_TRACK_TOKEN: - return 'Tracking confirmation'; - - default: - throw utils.spawnSwitchErr('assetView', this.state.assetView); - } - } private onCustomAssetChosen() { this.setState({ assetView: AssetViews.NEW_TOKEN_FORM, diff --git a/packages/website/ts/components/generate_order/generate_order_form.tsx b/packages/website/ts/components/generate_order/generate_order_form.tsx index 72edf08cf..59970b10c 100644 --- a/packages/website/ts/components/generate_order/generate_order_form.tsx +++ b/packages/website/ts/components/generate_order/generate_order_form.tsx @@ -62,16 +62,7 @@ interface GenerateOrderFormState { signingState: SigningState; } -const style = { - paper: { - display: 'inline-block', - position: 'relative', - textAlign: 'center', - width: '100%', - }, -}; - -export class GenerateOrderForm extends React.Component<GenerateOrderFormProps, any> { +export class GenerateOrderForm extends React.Component<GenerateOrderFormProps, GenerateOrderFormState> { private validator: SchemaValidator; constructor(props: GenerateOrderFormProps) { super(props); @@ -287,7 +278,7 @@ export class GenerateOrderForm extends React.Component<GenerateOrderFormProps, a if (_.isUndefined(exchangeContractAddr)) { this.props.dispatcher.updateShouldBlockchainErrDialogBeOpen(true); this.setState({ - isSigning: false, + signingState: SigningState.UNSIGNED, }); return false; } diff --git a/packages/website/ts/components/generate_order/new_token_form.tsx b/packages/website/ts/components/generate_order/new_token_form.tsx index 7e2c61ae8..1be9f5ece 100644 --- a/packages/website/ts/components/generate_order/new_token_form.tsx +++ b/packages/website/ts/components/generate_order/new_token_form.tsx @@ -9,7 +9,6 @@ import {Alert} from 'ts/components/ui/alert'; import {LifeCycleRaisedButton} from 'ts/components/ui/lifecycle_raised_button'; import {RequiredLabel} from 'ts/components/ui/required_label'; import {AlertTypes, Token, TokenByAddress, TokenState} from 'ts/types'; -import {constants} from 'ts/utils/constants'; interface NewTokenFormProps { blockchain: Blockchain; diff --git a/packages/website/ts/components/inputs/address_input.tsx b/packages/website/ts/components/inputs/address_input.tsx index 40ae722d9..bd9e24c80 100644 --- a/packages/website/ts/components/inputs/address_input.tsx +++ b/packages/website/ts/components/inputs/address_input.tsx @@ -3,7 +3,6 @@ import * as _ from 'lodash'; import {colors} from 'material-ui/styles'; import TextField from 'material-ui/TextField'; import * as React from 'react'; -import {Blockchain} from 'ts/blockchain'; import {RequiredLabel} from 'ts/components/ui/required_label'; interface AddressInputProps { diff --git a/packages/website/ts/components/inputs/identicon_address_input.tsx b/packages/website/ts/components/inputs/identicon_address_input.tsx index 692a092d9..9e4bc58ea 100644 --- a/packages/website/ts/components/inputs/identicon_address_input.tsx +++ b/packages/website/ts/components/inputs/identicon_address_input.tsx @@ -1,7 +1,5 @@ import * as _ from 'lodash'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; -import {Blockchain} from 'ts/blockchain'; import {AddressInput} from 'ts/components/inputs/address_input'; import {Identicon} from 'ts/components/ui/identicon'; import {InputLabel} from 'ts/components/ui/input_label'; diff --git a/packages/website/ts/components/inputs/token_input.tsx b/packages/website/ts/components/inputs/token_input.tsx index 8daa84650..67f697f05 100644 --- a/packages/website/ts/components/inputs/token_input.tsx +++ b/packages/website/ts/components/inputs/token_input.tsx @@ -7,7 +7,7 @@ import {AssetPicker} from 'ts/components/generate_order/asset_picker'; import {InputLabel} from 'ts/components/ui/input_label'; import {TokenIcon} from 'ts/components/ui/token_icon'; import {Dispatcher} from 'ts/redux/dispatcher'; -import {AssetToken, BlockchainErrs, Side, Token, TokenByAddress, TokenState} from 'ts/types'; +import {AssetToken, BlockchainErrs, Side, Token, TokenByAddress} from 'ts/types'; const TOKEN_ICON_DIMENSION = 80; diff --git a/packages/website/ts/components/order_json.tsx b/packages/website/ts/components/order_json.tsx index 073abe419..c499ee9c2 100644 --- a/packages/website/ts/components/order_json.tsx +++ b/packages/website/ts/components/order_json.tsx @@ -1,11 +1,9 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; -import Paper from 'material-ui/Paper'; -import {colors} from 'material-ui/styles'; import TextField from 'material-ui/TextField'; import * as React from 'react'; import {CopyIcon} from 'ts/components/ui/copy_icon'; -import {Order, SideToAssetToken, SignatureData, TokenByAddress, WebsitePaths} from 'ts/types'; +import {SideToAssetToken, SignatureData, TokenByAddress, WebsitePaths} from 'ts/types'; import {configs} from 'ts/utils/configs'; import {constants} from 'ts/utils/constants'; import {errorReporter} from 'ts/utils/error_reporter'; diff --git a/packages/website/ts/components/portal.tsx b/packages/website/ts/components/portal.tsx index 57e75dab3..74b1bdec6 100644 --- a/packages/website/ts/components/portal.tsx +++ b/packages/website/ts/components/portal.tsx @@ -1,7 +1,6 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import Paper from 'material-ui/Paper'; -import RaisedButton from 'material-ui/RaisedButton'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import * as DocumentTitle from 'react-document-title'; @@ -21,17 +20,13 @@ import {Loading} from 'ts/components/ui/loading'; import {GenerateOrderForm} from 'ts/containers/generate_order_form'; import {localStorage} from 'ts/local_storage/local_storage'; import {Dispatcher} from 'ts/redux/dispatcher'; -import {State} from 'ts/redux/reducer'; import {orderSchema} from 'ts/schemas/order_schema'; import {SchemaValidator} from 'ts/schemas/validator'; import { BlockchainErrs, - Fill, HashData, Order, ScreenWidths, - Side, - Styles, Token, TokenByAddress, TokenStateByAddress, @@ -71,28 +66,6 @@ interface PortalAllState { hasAcceptedDisclaimer: boolean; } -const styles: Styles = { - button: { - color: 'white', - }, - headline: { - fontSize: 20, - fontWeight: 400, - marginBottom: 12, - paddingTop: 16, - }, - inkBar: { - background: colors.amber600, - }, - menuItem: { - padding: '0px 16px 0px 48px', - }, - tabItemContainer: { - background: colors.blueGrey500, - borderRadius: '4px 4px 0 0', - }, -}; - export class Portal extends React.Component<PortalAllProps, PortalAllState> { private blockchain: Blockchain; private sharedOrderIfExists: Order; diff --git a/packages/website/ts/components/portal_menu.tsx b/packages/website/ts/components/portal_menu.tsx index db8e3a9f1..822c4d0d7 100644 --- a/packages/website/ts/components/portal_menu.tsx +++ b/packages/website/ts/components/portal_menu.tsx @@ -1,6 +1,5 @@ import * as _ from 'lodash'; import * as React from 'react'; -import {Link} from 'react-router-dom'; import {MenuItem} from 'ts/components/ui/menu_item'; import {WebsitePaths} from 'ts/types'; diff --git a/packages/website/ts/components/send_button.tsx b/packages/website/ts/components/send_button.tsx index da8dd2a9b..b3fd2aeba 100644 --- a/packages/website/ts/components/send_button.tsx +++ b/packages/website/ts/components/send_button.tsx @@ -1,4 +1,3 @@ -import {ZeroEx} from '0x.js'; import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import RaisedButton from 'material-ui/RaisedButton'; @@ -7,7 +6,6 @@ import {Blockchain} from 'ts/blockchain'; import {SendDialog} from 'ts/components/dialogs/send_dialog'; import {Dispatcher} from 'ts/redux/dispatcher'; import {BlockchainCallErrs, Token, TokenState} from 'ts/types'; -import {constants} from 'ts/utils/constants'; import {errorReporter} from 'ts/utils/error_reporter'; import {utils} from 'ts/utils/utils'; diff --git a/packages/website/ts/components/token_balances.tsx b/packages/website/ts/components/token_balances.tsx index 799fecc69..ab232326a 100644 --- a/packages/website/ts/components/token_balances.tsx +++ b/packages/website/ts/components/token_balances.tsx @@ -18,7 +18,6 @@ import { TableRow, TableRowColumn, } from 'material-ui/Table'; -import QueryString = require('query-string'); import * as React from 'react'; import ReactTooltip = require('react-tooltip'); import firstBy = require('thenby'); @@ -553,7 +552,7 @@ export class TokenBalances extends React.Component<TokenBalancesProps, TokenBala private renderDharmaLoanFrame() { if (utils.isUserOnMobile()) { return ( - <h4 style={{ textAlign: 'center' }}> + <h4 style={{textAlign: 'center'}}> We apologize -- Dharma loan requests are not available on mobile yet. Please try again through your desktop browser. </h4> diff --git a/packages/website/ts/components/top_bar.tsx b/packages/website/ts/components/top_bar.tsx index 4398fe667..27de49620 100644 --- a/packages/website/ts/components/top_bar.tsx +++ b/packages/website/ts/components/top_bar.tsx @@ -1,15 +1,9 @@ import * as _ from 'lodash'; -import AppBar from 'material-ui/AppBar'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Link} from 'react-router-dom'; -import {HashLink} from 'react-router-hash-link'; -import { - animateScroll, - Link as ScrollLink, -} from 'react-scroll'; import ReactTooltip = require('react-tooltip'); import {PortalMenu} from 'ts/components/portal_menu'; import {TopBarMenuItem} from 'ts/components/top_bar_menu_item'; @@ -17,10 +11,8 @@ import {DropDownMenuItem} from 'ts/components/ui/drop_down_menu_item'; import {Identicon} from 'ts/components/ui/identicon'; import {DocsInfo} from 'ts/pages/documentation/docs_info'; import {NestedSidebarMenu} from 'ts/pages/shared/nested_sidebar_menu'; -import {DocsMenu, MenuSubsectionsBySection, Styles, TypeDocNode, WebsitePaths} from 'ts/types'; -import {configs} from 'ts/utils/configs'; +import {DocsMenu, MenuSubsectionsBySection, Styles, WebsitePaths} from 'ts/types'; import {constants} from 'ts/utils/constants'; -import {typeDocUtils} from 'ts/utils/typedoc_utils'; const CUSTOM_DARK_GRAY = '#231F20'; const SECTION_HEADER_COLOR = 'rgb(234, 234, 234)'; @@ -132,7 +124,7 @@ export class TopBar extends React.Component<TopBarProps, TopBarState> { className="text-decoration-none" href={constants.GITHUB_URL} > - <MenuItem style={{ fontSize: styles.menuItem.fontSize }} primaryText="GitHub" /> + <MenuItem style={{fontSize: styles.menuItem.fontSize}} primaryText="GitHub" /> </a>, <a key="subMenuItem-whitePaper" diff --git a/packages/website/ts/components/top_bar_menu_item.tsx b/packages/website/ts/components/top_bar_menu_item.tsx index de429fba6..38dc91194 100644 --- a/packages/website/ts/components/top_bar_menu_item.tsx +++ b/packages/website/ts/components/top_bar_menu_item.tsx @@ -1,7 +1,6 @@ import * as _ from 'lodash'; import * as React from 'react'; import {Link} from 'react-router-dom'; -import {Styles} from 'ts/types'; const CUSTOM_DARK_GRAY = '#231F20'; const DEFAULT_STYLE = { diff --git a/packages/website/ts/components/track_token_confirmation.tsx b/packages/website/ts/components/track_token_confirmation.tsx index b9b2ef18a..cd588f239 100644 --- a/packages/website/ts/components/track_token_confirmation.tsx +++ b/packages/website/ts/components/track_token_confirmation.tsx @@ -1,6 +1,4 @@ import * as _ from 'lodash'; -import Dialog from 'material-ui/Dialog'; -import FlatButton from 'material-ui/FlatButton'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Party} from 'ts/components/ui/party'; diff --git a/packages/website/ts/components/ui/badge.tsx b/packages/website/ts/components/ui/badge.tsx index 15d5ea227..cf4396047 100644 --- a/packages/website/ts/components/ui/badge.tsx +++ b/packages/website/ts/components/ui/badge.tsx @@ -1,5 +1,4 @@ import * as _ from 'lodash'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Styles} from 'ts/types'; diff --git a/packages/website/ts/components/ui/drop_down_menu_item.tsx b/packages/website/ts/components/ui/drop_down_menu_item.tsx index 05b88f7ce..041688a9d 100644 --- a/packages/website/ts/components/ui/drop_down_menu_item.tsx +++ b/packages/website/ts/components/ui/drop_down_menu_item.tsx @@ -1,13 +1,7 @@ import * as _ from 'lodash'; import Menu from 'material-ui/Menu'; -import MenuItem from 'material-ui/MenuItem'; import Popover from 'material-ui/Popover'; import * as React from 'react'; -import {Link} from 'react-router-dom'; -import { - Link as ScrollLink, -} from 'react-scroll'; -import {Styles, WebsitePaths} from 'ts/types'; const CHECK_CLOSE_POPOVER_INTERVAL_MS = 300; const CUSTOM_LIGHT_GRAY = '#848484'; diff --git a/packages/website/ts/components/ui/fake_text_field.tsx b/packages/website/ts/components/ui/fake_text_field.tsx index 90bc47f01..8ee4349a2 100644 --- a/packages/website/ts/components/ui/fake_text_field.tsx +++ b/packages/website/ts/components/ui/fake_text_field.tsx @@ -1,4 +1,3 @@ -import {colors} from 'material-ui/styles'; import * as React from 'react'; import {InputLabel} from 'ts/components/ui/input_label'; import {Styles} from 'ts/types'; diff --git a/packages/website/ts/components/ui/lifecycle_raised_button.tsx b/packages/website/ts/components/ui/lifecycle_raised_button.tsx index cba94ca8c..2d668fb82 100644 --- a/packages/website/ts/components/ui/lifecycle_raised_button.tsx +++ b/packages/website/ts/components/ui/lifecycle_raised_button.tsx @@ -1,8 +1,6 @@ import * as _ from 'lodash'; import RaisedButton from 'material-ui/RaisedButton'; import * as React from 'react'; -import {Blockchain} from 'ts/blockchain'; -import {Token} from 'ts/types'; import {utils} from 'ts/utils/utils'; const COMPLETE_STATE_SHOW_LENGTH_MS = 2000; diff --git a/packages/website/ts/components/ui/menu_item.tsx b/packages/website/ts/components/ui/menu_item.tsx index 862f28457..c7ce7439f 100644 --- a/packages/website/ts/components/ui/menu_item.tsx +++ b/packages/website/ts/components/ui/menu_item.tsx @@ -1,9 +1,6 @@ import * as _ from 'lodash'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Link} from 'react-router-dom'; -import {Styles} from 'ts/types'; -import {constants} from 'ts/utils/constants'; interface MenuItemProps { to: string; diff --git a/packages/website/ts/components/ui/party.tsx b/packages/website/ts/components/ui/party.tsx index 5bafa6071..e6b6ea9e2 100644 --- a/packages/website/ts/components/ui/party.tsx +++ b/packages/website/ts/components/ui/party.tsx @@ -7,7 +7,6 @@ import {Identicon} from 'ts/components/ui/identicon'; import {EtherscanLinkSuffixes} from 'ts/types'; import {utils} from 'ts/utils/utils'; -const MIN_ADDRESS_WIDTH = 60; const IMAGE_DIMENSION = 100; const IDENTICON_DIAMETER = 95; const CHECK_MARK_GREEN = 'rgb(0, 195, 62)'; @@ -33,10 +32,7 @@ export class Party extends React.Component<PartyProps, PartyState> { public render() { const label = this.props.label; const address = this.props.address; - const tooltipId = `${label}-${address}-tooltip`; const identiconDiameter = this.props.identiconDiameter; - const addressWidth = identiconDiameter > MIN_ADDRESS_WIDTH ? - identiconDiameter : MIN_ADDRESS_WIDTH; const emptyIdenticonStyles = { width: identiconDiameter, height: identiconDiameter, diff --git a/packages/website/ts/components/ui/simple_loading.tsx b/packages/website/ts/components/ui/simple_loading.tsx index d55d7851d..fa548f996 100644 --- a/packages/website/ts/components/ui/simple_loading.tsx +++ b/packages/website/ts/components/ui/simple_loading.tsx @@ -1,5 +1,4 @@ import CircularProgress from 'material-ui/CircularProgress'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; export interface SimpleLoadingProps { diff --git a/packages/website/ts/components/ui/swap_icon.tsx b/packages/website/ts/components/ui/swap_icon.tsx index 2e6ae89bb..b5d4b0caa 100644 --- a/packages/website/ts/components/ui/swap_icon.tsx +++ b/packages/website/ts/components/ui/swap_icon.tsx @@ -1,7 +1,6 @@ import * as _ from 'lodash'; import {colors} from 'material-ui/styles'; import * as React from 'react'; -import {constants} from 'ts/utils/constants'; interface SwapIconProps { swapTokensFn: () => void; diff --git a/packages/website/ts/components/visual_order.tsx b/packages/website/ts/components/visual_order.tsx index 037a321ff..a7be6f780 100644 --- a/packages/website/ts/components/visual_order.tsx +++ b/packages/website/ts/components/visual_order.tsx @@ -3,7 +3,6 @@ import * as _ from 'lodash'; import * as React from 'react'; import {Party} from 'ts/components/ui/party'; import {AssetToken, Token, TokenByAddress} from 'ts/types'; -import {constants} from 'ts/utils/constants'; import {utils} from 'ts/utils/utils'; const PRECISION = 5; diff --git a/packages/website/ts/containers/connect_documentation.tsx b/packages/website/ts/containers/connect_documentation.tsx index 8ecc1e37c..3b181a814 100644 --- a/packages/website/ts/containers/connect_documentation.tsx +++ b/packages/website/ts/containers/connect_documentation.tsx @@ -1,9 +1,7 @@ -import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as React from 'react'; import {connect} from 'react-redux'; -import {Dispatch, Store as ReduxStore} from 'redux'; -import {Blockchain} from 'ts/blockchain'; +import {Dispatch} from 'redux'; import {DocsInfo} from 'ts/pages/documentation/docs_info'; import { Documentation as DocumentationComponent, diff --git a/packages/website/ts/containers/generate_order_form.tsx b/packages/website/ts/containers/generate_order_form.tsx index 864d2702e..134c84859 100644 --- a/packages/website/ts/containers/generate_order_form.tsx +++ b/packages/website/ts/containers/generate_order_form.tsx @@ -1,8 +1,6 @@ -import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as React from 'react'; import {connect} from 'react-redux'; -import {Dispatch, Store as ReduxStore} from 'redux'; import {Blockchain} from 'ts/blockchain'; import {GenerateOrderForm as GenerateOrderFormComponent} from 'ts/components/generate_order/generate_order_form'; import {Dispatcher} from 'ts/redux/dispatcher'; diff --git a/packages/website/ts/containers/portal.tsx b/packages/website/ts/containers/portal.tsx index 2987764f4..7588a1535 100644 --- a/packages/website/ts/containers/portal.tsx +++ b/packages/website/ts/containers/portal.tsx @@ -2,7 +2,7 @@ import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as React from 'react'; import {connect} from 'react-redux'; -import {Dispatch, Store as ReduxStore} from 'redux'; +import {Dispatch} from 'redux'; import { Portal as PortalComponent, PortalAllProps as PortalComponentAllProps, @@ -12,7 +12,6 @@ import {Dispatcher} from 'ts/redux/dispatcher'; import {State} from 'ts/redux/reducer'; import { BlockchainErrs, - Fill, HashData, Order, ScreenWidths, @@ -22,24 +21,23 @@ import { } from 'ts/types'; import {constants} from 'ts/utils/constants'; -interface MapStateToProps { +interface ConnectedState { blockchainErr: BlockchainErrs; blockchainIsLoaded: boolean; hashData: HashData; networkId: number; nodeVersion: string; - orderFillAmount: number; + orderFillAmount: BigNumber; tokenByAddress: TokenByAddress; tokenStateByAddress: TokenStateByAddress; - userEtherBalance: number; + userEtherBalance: BigNumber; screenWidth: ScreenWidths; shouldBlockchainErrDialogBeOpen: boolean; userAddress: string; userSuppliedOrderCache: Order; + flashMessage?: string|React.ReactNode; } -interface ConnectedState {} - interface ConnectedDispatch { dispatcher: Dispatcher; } diff --git a/packages/website/ts/containers/smart_contracts_documentation.tsx b/packages/website/ts/containers/smart_contracts_documentation.tsx index ea2b19b8c..1f82bda0f 100644 --- a/packages/website/ts/containers/smart_contracts_documentation.tsx +++ b/packages/website/ts/containers/smart_contracts_documentation.tsx @@ -1,7 +1,7 @@ import * as _ from 'lodash'; import * as React from 'react'; import {connect} from 'react-redux'; -import {Dispatch, Store as ReduxStore} from 'redux'; +import {Dispatch} from 'redux'; import {DocsInfo} from 'ts/pages/documentation/docs_info'; import { Documentation as DocumentationComponent, diff --git a/packages/website/ts/containers/zero_ex_js_documentation.tsx b/packages/website/ts/containers/zero_ex_js_documentation.tsx index 58c0ee186..1ce9ba139 100644 --- a/packages/website/ts/containers/zero_ex_js_documentation.tsx +++ b/packages/website/ts/containers/zero_ex_js_documentation.tsx @@ -1,9 +1,7 @@ -import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as React from 'react'; import {connect} from 'react-redux'; -import {Dispatch, Store as ReduxStore} from 'redux'; -import {Blockchain} from 'ts/blockchain'; +import {Dispatch} from 'redux'; import {DocsInfo} from 'ts/pages/documentation/docs_info'; import { Documentation as DocumentationComponent, diff --git a/packages/website/ts/index.tsx b/packages/website/ts/index.tsx index 61cd6c2f5..71565fa4d 100644 --- a/packages/website/ts/index.tsx +++ b/packages/website/ts/index.tsx @@ -6,7 +6,7 @@ import {colors, getMuiTheme, MuiThemeProvider} from 'material-ui/styles'; import * as React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; -import {BrowserRouter as Router, Link, Redirect, Route, Switch} from 'react-router-dom'; +import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'; import * as injectTapEventPlugin from 'react-tap-event-plugin'; import {createStore, Store as ReduxStore} from 'redux'; import {createLazyComponent} from 'ts/lazy_component'; diff --git a/packages/website/ts/pages/about/about.tsx b/packages/website/ts/pages/about/about.tsx index 3af05e8a4..011bbb9d9 100644 --- a/packages/website/ts/pages/about/about.tsx +++ b/packages/website/ts/pages/about/about.tsx @@ -1,15 +1,11 @@ import * as _ from 'lodash'; -import RaisedButton from 'material-ui/RaisedButton'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import * as DocumentTitle from 'react-document-title'; -import {Link} from 'react-router-dom'; import {Footer} from 'ts/components/footer'; import {TopBar} from 'ts/components/top_bar'; import {Profile} from 'ts/pages/about/profile'; -import {Question} from 'ts/pages/faq/question'; import {ProfileInfo, Styles} from 'ts/types'; -import {configs} from 'ts/utils/configs'; import {constants} from 'ts/utils/constants'; import {utils} from 'ts/utils/utils'; @@ -236,7 +232,7 @@ export class About extends React.Component<AboutProps, AboutState> { } private renderProfiles(profiles: ProfileInfo[]) { const numIndiv = profiles.length; - const colSize = utils.getColSize(profiles.length); + const colSize = utils.getColSize(numIndiv); return _.map(profiles, profile => { return ( <div diff --git a/packages/website/ts/pages/about/profile.tsx b/packages/website/ts/pages/about/profile.tsx index 71dbd09b5..86aa788b2 100644 --- a/packages/website/ts/pages/about/profile.tsx +++ b/packages/website/ts/pages/about/profile.tsx @@ -1,9 +1,6 @@ import * as _ from 'lodash'; -import {colors} from 'material-ui/styles'; import * as React from 'react'; -import {Element as ScrollElement} from 'react-scroll'; import {ProfileInfo, Styles} from 'ts/types'; -import {utils} from 'ts/utils/utils'; const IMAGE_DIMENSION = 149; const styles: Styles = { diff --git a/packages/website/ts/pages/documentation/comment.tsx b/packages/website/ts/pages/documentation/comment.tsx index 78bbdc069..9627fdcdc 100644 --- a/packages/website/ts/pages/documentation/comment.tsx +++ b/packages/website/ts/pages/documentation/comment.tsx @@ -22,3 +22,5 @@ export const Comment: React.SFC<CommentProps> = (props: CommentProps) => { </div> ); }; + +Comment.defaultProps = defaultProps; diff --git a/packages/website/ts/pages/documentation/documentation.tsx b/packages/website/ts/pages/documentation/documentation.tsx index be99e77a2..0ca8ae9d3 100644 --- a/packages/website/ts/pages/documentation/documentation.tsx +++ b/packages/website/ts/pages/documentation/documentation.tsx @@ -17,35 +17,27 @@ import {MethodBlock} from 'ts/pages/documentation/method_block'; import {SourceLink} from 'ts/pages/documentation/source_link'; import {Type} from 'ts/pages/documentation/type'; import {TypeDefinition} from 'ts/pages/documentation/type_definition'; -import {AnchorTitle} from 'ts/pages/shared/anchor_title'; import {MarkdownSection} from 'ts/pages/shared/markdown_section'; import {NestedSidebarMenu} from 'ts/pages/shared/nested_sidebar_menu'; import {SectionHeader} from 'ts/pages/shared/section_header'; import {Dispatcher} from 'ts/redux/dispatcher'; import { AddressByContractName, - CustomType, DocAgnosticFormat, - Docs, - DocsInfoConfig, DoxityDocObj, EtherscanLinkSuffixes, Event, - MenuSubsectionsBySection, Networks, Property, SolidityMethod, Styles, TypeDefinitionByName, - TypeDocNode, TypescriptMethod, - WebsitePaths, } from 'ts/types'; import {constants} from 'ts/utils/constants'; import {docUtils} from 'ts/utils/doc_utils'; import {utils} from 'ts/utils/utils'; -const SCROLL_TO_TIMEOUT = 500; const SCROLL_TOP_ID = 'docsScrollTop'; const CUSTOM_PURPLE = '#690596'; const CUSTOM_RED = '#e91751'; diff --git a/packages/website/ts/pages/documentation/enum.tsx b/packages/website/ts/pages/documentation/enum.tsx index 8fcd2c252..b5fbc4bd2 100644 --- a/packages/website/ts/pages/documentation/enum.tsx +++ b/packages/website/ts/pages/documentation/enum.tsx @@ -1,9 +1,6 @@ import * as _ from 'lodash'; import * as React from 'react'; -import {EnumValue, TypeDocNode} from 'ts/types'; -import {utils} from 'ts/utils/utils'; - -const STRING_ENUM_CODE_PREFIX = ' strEnum('; +import {EnumValue} from 'ts/types'; interface EnumProps { values: EnumValue[]; @@ -11,7 +8,6 @@ interface EnumProps { export function Enum(props: EnumProps) { const values = _.map(props.values, (value, i) => { - const isLast = i === props.values.length - 1; const defaultValueIfAny = !_.isUndefined(value.defaultValue) ? ` = ${value.defaultValue}` : ''; return `\n\t${value.name}${defaultValueIfAny},`; }); diff --git a/packages/website/ts/pages/documentation/event_definition.tsx b/packages/website/ts/pages/documentation/event_definition.tsx index 469e6bb37..3c57666e7 100644 --- a/packages/website/ts/pages/documentation/event_definition.tsx +++ b/packages/website/ts/pages/documentation/event_definition.tsx @@ -4,10 +4,7 @@ import {DocsInfo} from 'ts/pages/documentation/docs_info'; import {Type} from 'ts/pages/documentation/type'; import {AnchorTitle} from 'ts/pages/shared/anchor_title'; import {Event, EventArg, HeaderSizes} from 'ts/types'; -import {constants} from 'ts/utils/constants'; -import {utils} from 'ts/utils/utils'; -const KEYWORD_COLOR = '#a81ca6'; const CUSTOM_GREEN = 'rgb(77, 162, 75)'; interface EventDefinitionProps { diff --git a/packages/website/ts/pages/documentation/method_block.tsx b/packages/website/ts/pages/documentation/method_block.tsx index 44e549211..9505f2aa4 100644 --- a/packages/website/ts/pages/documentation/method_block.tsx +++ b/packages/website/ts/pages/documentation/method_block.tsx @@ -1,8 +1,6 @@ import * as _ from 'lodash'; -import {Chip} from 'material-ui/Chip'; import {colors} from 'material-ui/styles'; import * as React from 'react'; -import * as ReactMarkdown from 'react-markdown'; import {Comment} from 'ts/pages/documentation/comment'; import {DocsInfo} from 'ts/pages/documentation/docs_info'; import {MethodSignature} from 'ts/pages/documentation/method_signature'; @@ -14,11 +12,9 @@ import { SolidityMethod, Styles, TypeDefinitionByName, - TypeDocNode, TypescriptMethod, } from 'ts/types'; import {typeDocUtils} from 'ts/utils/typedoc_utils'; -import {utils} from 'ts/utils/utils'; interface MethodBlockProps { method: SolidityMethod|TypescriptMethod; diff --git a/packages/website/ts/pages/documentation/method_signature.tsx b/packages/website/ts/pages/documentation/method_signature.tsx index 846c9fa4f..df3b61814 100644 --- a/packages/website/ts/pages/documentation/method_signature.tsx +++ b/packages/website/ts/pages/documentation/method_signature.tsx @@ -42,6 +42,8 @@ export const MethodSignature: React.SFC<MethodSignatureProps> = (props: MethodSi ); }; +MethodSignature.defaultProps = defaultProps; + function renderParameters( method: TypescriptMethod|SolidityMethod, docsInfo: DocsInfo, typeDefinitionByName?: TypeDefinitionByName, ) { diff --git a/packages/website/ts/pages/documentation/source_link.tsx b/packages/website/ts/pages/documentation/source_link.tsx index 74fc6d4d5..9abf01706 100644 --- a/packages/website/ts/pages/documentation/source_link.tsx +++ b/packages/website/ts/pages/documentation/source_link.tsx @@ -2,7 +2,6 @@ import * as _ from 'lodash'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Source} from 'ts/types'; -import {constants} from 'ts/utils/constants'; interface SourceLinkProps { source: Source; diff --git a/packages/website/ts/pages/documentation/type.tsx b/packages/website/ts/pages/documentation/type.tsx index c564429d0..74b146d91 100644 --- a/packages/website/ts/pages/documentation/type.tsx +++ b/packages/website/ts/pages/documentation/type.tsx @@ -7,7 +7,6 @@ import {DocsInfo} from 'ts/pages/documentation/docs_info'; import {TypeDefinition} from 'ts/pages/documentation/type_definition'; import {Type as TypeDef, TypeDefinitionByName, TypeDocTypes} from 'ts/types'; import {constants} from 'ts/utils/constants'; -import {typeDocUtils} from 'ts/utils/typedoc_utils'; import {utils} from 'ts/utils/utils'; const BUILT_IN_TYPE_COLOR = '#e69d00'; @@ -48,10 +47,8 @@ interface TypeProps { // <Type /> components (e.g when rendering the union type). export function Type(props: TypeProps): any { const type = props.type; - const isIntrinsic = type.typeDocType === TypeDocTypes.Intrinsic; const isReference = type.typeDocType === TypeDocTypes.Reference; const isArray = type.typeDocType === TypeDocTypes.Array; - const isStringLiteral = type.typeDocType === TypeDocTypes.StringLiteral; let typeNameColor = 'inherit'; let typeName: string|React.ReactNode; let typeArgs: React.ReactNode[] = []; diff --git a/packages/website/ts/pages/documentation/type_definition.tsx b/packages/website/ts/pages/documentation/type_definition.tsx index 17b182c70..edcf7bf47 100644 --- a/packages/website/ts/pages/documentation/type_definition.tsx +++ b/packages/website/ts/pages/documentation/type_definition.tsx @@ -9,8 +9,6 @@ import {MethodSignature} from 'ts/pages/documentation/method_signature'; import {Type} from 'ts/pages/documentation/type'; import {AnchorTitle} from 'ts/pages/shared/anchor_title'; import {CustomType, CustomTypeChild, HeaderSizes, KindString, TypeDocTypes} from 'ts/types'; -import {constants} from 'ts/utils/constants'; -import {typeDocUtils} from 'ts/utils/typedoc_utils'; import {utils} from 'ts/utils/utils'; const KEYWORD_COLOR = '#a81ca6'; diff --git a/packages/website/ts/pages/faq/faq.tsx b/packages/website/ts/pages/faq/faq.tsx index c53ed28b8..b3fe21da7 100644 --- a/packages/website/ts/pages/faq/faq.tsx +++ b/packages/website/ts/pages/faq/faq.tsx @@ -1,9 +1,7 @@ import * as _ from 'lodash'; -import RaisedButton from 'material-ui/RaisedButton'; import {colors} from 'material-ui/styles'; import * as React from 'react'; import * as DocumentTitle from 'react-document-title'; -import {Link} from 'react-router-dom'; import {Footer} from 'ts/components/footer'; import {TopBar} from 'ts/components/top_bar'; import {Question} from 'ts/pages/faq/question'; diff --git a/packages/website/ts/pages/landing/landing.tsx b/packages/website/ts/pages/landing/landing.tsx index f3c46b8c7..7992c7a6c 100644 --- a/packages/website/ts/pages/landing/landing.tsx +++ b/packages/website/ts/pages/landing/landing.tsx @@ -6,8 +6,7 @@ import DocumentTitle = require('react-document-title'); import {Link} from 'react-router-dom'; import {Footer} from 'ts/components/footer'; import {TopBar} from 'ts/components/top_bar'; -import {ScreenWidths, Styles, WebsitePaths} from 'ts/types'; -import {configs} from 'ts/utils/configs'; +import {ScreenWidths, WebsitePaths} from 'ts/types'; import {constants} from 'ts/utils/constants'; import {utils} from 'ts/utils/utils'; @@ -269,7 +268,7 @@ export class Landing extends React.Component<LandingProps, LandingState> { const isSmallScreen = this.state.screenWidth === ScreenWidths.SM; const isMediumScreen = this.state.screenWidth === ScreenWidths.MD; const projectList = _.map(projects, (project: Project, i: number) => { - const colWidth = isSmallScreen ? 3 : isMediumScreen ? 4 : 2 - (i % 2); + const colWidth = isSmallScreen ? 3 : (isMediumScreen ? 4 : 2 - (i % 2)); return ( <div key={`project-${project.logoFileName}`} @@ -470,11 +469,6 @@ export class Landing extends React.Component<LandingProps, LandingState> { } private renderBuildingBlocksSection() { const isSmallScreen = this.state.screenWidth === ScreenWidths.SM; - const underlineStyle: React.CSSProperties = { - height: isSmallScreen ? 18 : 23, - lineHeight: 'none', - borderBottom: '2px solid #979797', - }; const descriptionStyle: React.CSSProperties = { fontFamily: 'Roboto Mono', lineHeight: isSmallScreen ? 1.5 : 2, @@ -606,21 +600,6 @@ export class Landing extends React.Component<LandingProps, LandingState> { }); return assets; } - private renderLink(label: string, path: string, color: string, style?: React.CSSProperties) { - return ( - <div - style={{borderBottom: `1px solid ${color}`, paddingBottom: 1, height: 20, lineHeight: 1.7, ...style}} - > - <Link - to={path} - className="text-decoration-none" - style={{color, fontFamily: 'Roboto Mono'}} - > - {label} - </Link> - </div> - ); - } private renderInfoBoxes() { const isSmallScreen = this.state.screenWidth === ScreenWidths.SM; const boxStyle: React.CSSProperties = { @@ -676,7 +655,6 @@ export class Landing extends React.Component<LandingProps, LandingState> { } private renderUseCases() { const isSmallScreen = this.state.screenWidth === ScreenWidths.SM; - const isMediumScreen = this.state.screenWidth === ScreenWidths.MD; const useCases: UseCase[] = [ { diff --git a/packages/website/ts/pages/not_found.tsx b/packages/website/ts/pages/not_found.tsx index 075bcf91e..df505792d 100644 --- a/packages/website/ts/pages/not_found.tsx +++ b/packages/website/ts/pages/not_found.tsx @@ -1,6 +1,5 @@ import * as _ from 'lodash'; import * as React from 'react'; -import {Link} from 'react-router-dom'; import {Footer} from 'ts/components/footer'; import {TopBar} from 'ts/components/top_bar'; import {Styles} from 'ts/types'; diff --git a/packages/website/ts/pages/shared/nested_sidebar_menu.tsx b/packages/website/ts/pages/shared/nested_sidebar_menu.tsx index cbb863f3e..15ec44399 100644 --- a/packages/website/ts/pages/shared/nested_sidebar_menu.tsx +++ b/packages/website/ts/pages/shared/nested_sidebar_menu.tsx @@ -4,9 +4,8 @@ import {colors} from 'material-ui/styles'; import * as React from 'react'; import {Link as ScrollLink} from 'react-scroll'; import {VersionDropDown} from 'ts/pages/shared/version_drop_down'; -import {Docs, MenuSubsectionsBySection, Styles} from 'ts/types'; +import {MenuSubsectionsBySection, Styles} from 'ts/types'; import {constants} from 'ts/utils/constants'; -import {typeDocUtils} from 'ts/utils/typedoc_utils'; import {utils} from 'ts/utils/utils'; interface NestedSidebarMenuProps { diff --git a/packages/website/ts/pages/shared/version_drop_down.tsx b/packages/website/ts/pages/shared/version_drop_down.tsx index 4af9a834f..e63ad19cd 100644 --- a/packages/website/ts/pages/shared/version_drop_down.tsx +++ b/packages/website/ts/pages/shared/version_drop_down.tsx @@ -2,8 +2,6 @@ import * as _ from 'lodash'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import * as React from 'react'; -import {Docs} from 'ts/types'; -import {constants} from 'ts/utils/constants'; interface VersionDropDownProps { selectedVersion: string; diff --git a/packages/website/ts/redux/dispatcher.ts b/packages/website/ts/redux/dispatcher.ts index a0a1da21b..cbcee6599 100644 --- a/packages/website/ts/redux/dispatcher.ts +++ b/packages/website/ts/redux/dispatcher.ts @@ -6,7 +6,6 @@ import { AssetToken, BlockchainErrs, Direction, - Fill, Order, ProviderType, ScreenWidths, diff --git a/packages/website/ts/utils/constants.ts b/packages/website/ts/utils/constants.ts index cae59af5f..fb81dd9a9 100644 --- a/packages/website/ts/utils/constants.ts +++ b/packages/website/ts/utils/constants.ts @@ -2,7 +2,6 @@ import BigNumber from 'bignumber.js'; import { ContractAddresses, Docs, - ExchangeContractErrs, Networks, PublicNodeUrlsByNetworkId, WebsitePaths, diff --git a/packages/website/ts/utils/doc_utils.ts b/packages/website/ts/utils/doc_utils.ts index 594e3bae6..ea210a3fa 100644 --- a/packages/website/ts/utils/doc_utils.ts +++ b/packages/website/ts/utils/doc_utils.ts @@ -1,7 +1,6 @@ import findVersions = require('find-versions'); import * as _ from 'lodash'; import {DoxityDocObj, S3FileObject, TypeDocNode, VersionToFileName} from 'ts/types'; -import {constants} from 'ts/utils/constants'; import {utils} from 'ts/utils/utils'; import convert = require('xml-js'); diff --git a/packages/website/ts/utils/typedoc_utils.ts b/packages/website/ts/utils/typedoc_utils.ts index ff8060781..9d3b9f8d7 100644 --- a/packages/website/ts/utils/typedoc_utils.ts +++ b/packages/website/ts/utils/typedoc_utils.ts @@ -5,21 +5,17 @@ import { CustomTypeChild, DocAgnosticFormat, DocSection, - DocsMenu, IndexSignature, KindString, - MenuSubsectionsBySection, Parameter, Property, SectionsMap, Type, TypeDocNode, TypeDocType, - TypeDocTypes, TypeParameter, TypescriptMethod, } from 'ts/types'; -import {constants} from 'ts/utils/constants'; import {utils} from 'ts/utils/utils'; export const typeDocUtils = { diff --git a/packages/website/ts/utils/utils.ts b/packages/website/ts/utils/utils.ts index 8b23b6a40..abc2fb2d4 100644 --- a/packages/website/ts/utils/utils.ts +++ b/packages/website/ts/utils/utils.ts @@ -1,7 +1,6 @@ import {ExchangeContractErrs, ZeroExError} from '0x.js'; import BigNumber from 'bignumber.js'; import deepEqual = require('deep-equal'); -import ethUtil = require('ethereumjs-util'); import isMobile = require('is-mobile'); import * as _ from 'lodash'; import * as moment from 'moment'; @@ -9,7 +8,6 @@ import { EtherscanLinkSuffixes, Networks, Order, - OrderParty, ScreenWidths, Side, SideToAssetToken, @@ -110,9 +108,9 @@ export const utils = { }, getColSize(items: number) { const bassCssGridSize = 12; // Source: http://basscss.com/#basscss-grid - const colSize = 12 / items; + const colSize = bassCssGridSize / items; if (!_.isInteger(colSize)) { - throw new Error('Number of cols must be divisible by 12'); + throw new Error(`Number of cols must be divisible by ${bassCssGridSize}`); } return colSize; }, diff --git a/packages/website/ts/web3_wrapper.ts b/packages/website/ts/web3_wrapper.ts index b713f8a33..1bf7ffed5 100644 --- a/packages/website/ts/web3_wrapper.ts +++ b/packages/website/ts/web3_wrapper.ts @@ -1,4 +1,4 @@ -import {promisify} from '@0xproject/utils'; +import {intervalUtils, promisify} from '@0xproject/utils'; import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import {Dispatcher} from 'ts/redux/dispatcher'; @@ -9,7 +9,7 @@ export class Web3Wrapper { private web3: Web3; private prevNetworkId: number; private shouldPollUserAddress: boolean; - private watchNetworkAndBalanceIntervalId: number; + private watchNetworkAndBalanceIntervalId: NodeJS.Timer; private prevUserEtherBalanceInEth: BigNumber; private prevUserAddress: string; constructor(dispatcher: Dispatcher, provider: Web3.Provider, networkIdIfExists: number, @@ -98,7 +98,7 @@ export class Web3Wrapper { let prevNodeVersion: string; this.prevUserEtherBalanceInEth = new BigNumber(0); this.dispatcher.updateNetworkId(this.prevNetworkId); - this.watchNetworkAndBalanceIntervalId = window.setInterval(async () => { + this.watchNetworkAndBalanceIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { // Check for network state changes const currentNetworkId = await this.getNetworkIdIfExists(); if (currentNetworkId !== this.prevNetworkId) { |