Merge branch 'development'
This commit is contained in:
@@ -5,7 +5,7 @@ jobs:
|
||||
docker:
|
||||
- image: circleci/node:6.12
|
||||
environment:
|
||||
CONTRACTS_COMMIT_HASH: '6bda6a2'
|
||||
CONTRACTS_COMMIT_HASH: '9ed05f5'
|
||||
steps:
|
||||
- checkout
|
||||
- run: echo 'export PATH=$HOME/CIRCLE_PROJECT_REPONAME/node_modules/.bin:$PATH' >> $BASH_ENV
|
||||
|
||||
@@ -42,7 +42,7 @@ We also recommend you read through the tests.
|
||||
|
||||
## Styleguide
|
||||
|
||||
We use `[tslint](https://palantir.github.io/tslint/)` with [custom configs](https://github.com/0xProject/tslint-config-0xproject) to keep our code style consistent.
|
||||
We use [TSLint](https://palantir.github.io/tslint/) with [custom configs](https://github.com/0xProject/tslint-config-0xproject) to keep our code style consistent.
|
||||
|
||||
To lint your code just run: `yarn lint`
|
||||
|
||||
|
||||
78
README.md
78
README.md
@@ -22,21 +22,83 @@ This repository contains all the 0x developer tools written in TypeScript. Our h
|
||||
| Package | Version | Description |
|
||||
|---------|---------|-------------|
|
||||
| [`0x.js`](/packages/0x.js) | [](https://www.npmjs.com/package/0x.js) | A Javascript library for interacting with the 0x protocol |
|
||||
| [`@0xproject/abi-gen`](/packages/abi-gen) | [](https://www.npmjs.com/package/@0xproject/abi-gen) | Tool to generate TS code from ABI |
|
||||
| [`@0xproject/assert`](/packages/assert) | [](https://www.npmjs.com/package/@0xproject/assert) | Standard type and schema assertions |
|
||||
| [`@0xproject/abi-gen`](/packages/abi-gen) | [](https://www.npmjs.com/package/@0xproject/abi-gen) | Tool to generate TS wrappers from smart contract ABIs |
|
||||
| [`@0xproject/assert`](/packages/assert) | [](https://www.npmjs.com/package/@0xproject/assert) | Type and schema assertions used by our packages |
|
||||
| [`@0xproject/connect`](/packages/connect) | [](https://www.npmjs.com/package/@0xproject/connect) | A Javascript library for interacting with the standard relayer api |
|
||||
| [`@0xproject/json-schemas`](/packages/json-schemas) | [](https://www.npmjs.com/package/@0xproject/json-schemas) | 0x-related json schemas |
|
||||
| [`@0xproject/subproviders`](/packages/subproviders) | [](https://www.npmjs.com/package/@0xproject/subproviders) | Web3 subproviders |
|
||||
| [`@0xproject/tslint-config`](/packages/tslint-config) | [](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x project TSLint rules |
|
||||
| [`@0xproject/types`](/packages/types) | [](https://www.npmjs.com/package/@0xproject/types) | Shared types |
|
||||
| [`@0xproject/utils`](/packages/utils) | [](https://www.npmjs.com/package/@0xproject/utils) | Shared utils |
|
||||
| [`@0xproject/subproviders`](/packages/subproviders) | [](https://www.npmjs.com/package/@0xproject/subproviders) | Useful web3 subproviders (e.g LedgerSubprovider) |
|
||||
| [`@0xproject/tslint-config`](/packages/tslint-config) | [](https://www.npmjs.com/package/@0xproject/tslint-config) | Custom 0x development TSLint rules |
|
||||
| [`@0xproject/types`](/packages/types) | [](https://www.npmjs.com/package/@0xproject/types) | Shared type declarations |
|
||||
| [`@0xproject/utils`](/packages/utils) | [](https://www.npmjs.com/package/@0xproject/utils) | Shared utilities |
|
||||
| [`@0xproject/web3-wrapper`](/packages/web3-wrapper) | [](https://www.npmjs.com/package/@0xproject/web3-wrapper) | Web3 wrapper |
|
||||
|
||||
### Private Packages
|
||||
|
||||
| Package | Description |
|
||||
|---------|-------------|
|
||||
| [`@0xproject/contracts`](/packages/contracts) | Smart contracts |
|
||||
| [`@0xproject/contracts`](/packages/contracts) | 0x solidity smart contracts & tests |
|
||||
| [`@0xproject/kovan_faucets`](/packages/kovan-faucets) | A faucet micro-service that dispenses test ERC20 tokens or Ether |
|
||||
| [`@0xproject/monorepo-scripts`](/packages/monorepo-scripts) | Shared monorepo scripts |
|
||||
| [`@0xproject/website`](/packages/website) | 0x website |
|
||||
| [`@0xproject/website`](/packages/website) | 0x website & Portal DApp |
|
||||
|
||||
## Usage
|
||||
|
||||
Dedicated documentation pages:
|
||||
- [0x.js Library](https://0xproject.com/docs/0xjs)
|
||||
- [0x Connect](https://0xproject.com/docs/connect)
|
||||
- [Smart contracts](https://0xproject.com/docs/contracts)
|
||||
- [Standard Relayer API](https://github.com/0xProject/standard-relayer-api/blob/master/README.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](./CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
Build all packages
|
||||
|
||||
```bash
|
||||
yarn lerna:run build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
Lint all packages
|
||||
```bash
|
||||
yarn lerna:run lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
Before running the tests, you will need to spin up a [TestRPC](https://www.npmjs.com/package/ethereumjs-testrpc) instance and deploy all the 0x smart contracts.
|
||||
|
||||
In a separate terminal, start TestRPC (a convenience command is provided as part of this repo)
|
||||
```bash
|
||||
yarn testrpc
|
||||
```
|
||||
|
||||
Then in your main terminal run
|
||||
```
|
||||
cd packages/contracts
|
||||
yarn migrate
|
||||
cd ..
|
||||
```
|
||||
|
||||
And finally from the root project directory run
|
||||
```bash
|
||||
yarn lerna:run test
|
||||
```
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"scripts": {
|
||||
"testrpc": "testrpc -p 8545 --networkId 50 -m \"${npm_package_config_mnemonic}\"",
|
||||
"lerna:run": "lerna run",
|
||||
"lerna:rebuild": "lerna run clean; lerna run build;",
|
||||
"lerna:publish": "yarn install; lerna run clean; lerna run build; lerna publish --registry=https://registry.npmjs.org/"
|
||||
},
|
||||
"config": {
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# CHANGELOG
|
||||
|
||||
v0.28.0 - _December 20, 2017_
|
||||
------------------------
|
||||
* Add `etherTokenAddress` arg to `depositAsync` and `withdrawAsync` methods on `zeroEx.etherToken` (#267)
|
||||
* Removed accidentally included `unsubscribeAll` method from `zeroEx.proxy`, `zeroEx.etherToken` and `zeroEx.tokenRegistry` (#267)
|
||||
* Removed `etherTokenContractAddress` from `ZeroEx` constructor arg `ZeroExConfig` (#267)
|
||||
* Rename `SubscriptionOpts` to `BlockRange` (#272)
|
||||
* Add `zeroEx.etherToken.subscribe`, `zeroEx.etherToken.unsubscribe`, `zeroEx.etherToken.unsubscribeAll` (#277)
|
||||
* Add `zeroEx.etherToken.getLogsAsync` (#277)
|
||||
* Add new public types `BlockParamLiteral`, `EtherTokenEvents`, `EtherTokenContractEventArgs`, `DepositContractEventArgs`, `WithdrawalContractEventArgs` (#277)
|
||||
* Support `Deposit` and `Withdraw` events on etherToken (#277)
|
||||
* Improve the error message when taker is not a string (#278)
|
||||
|
||||
v0.27.1 - _November 28, 2017_
|
||||
------------------------
|
||||
* Export `TransactionOpts` type
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* 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.
|
||||
*/
|
||||
// tslint:disable-next-line:no-unused-variable
|
||||
import {TxData, TxDataPayable} from '@0xproject/types';
|
||||
import {classUtils, promisify} from '@0xproject/utils';
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "0x.js",
|
||||
"version": "0.27.2",
|
||||
"version": "0.28.0",
|
||||
"description": "A javascript library for interacting with the 0x protocol",
|
||||
"keywords": [
|
||||
"0x.js",
|
||||
@@ -45,10 +45,10 @@
|
||||
"node": ">=6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/abi-gen": "^0.0.2",
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/types": "^0.1.0",
|
||||
"@0xproject/dev-utils": "^0.0.1",
|
||||
"@0xproject/abi-gen": "^0.0.3",
|
||||
"@0xproject/dev-utils": "^0.0.2",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@0xproject/types": "^0.1.1",
|
||||
"@types/bintrees": "^1.0.2",
|
||||
"@types/jsonschema": "^1.1.1",
|
||||
"@types/lodash": "^4.14.86",
|
||||
@@ -84,10 +84,10 @@
|
||||
"webpack": "^3.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@0xproject/assert": "^0.0.7",
|
||||
"@0xproject/json-schemas": "^0.6.10",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/web3-wrapper": "^0.1.0",
|
||||
"@0xproject/assert": "^0.0.8",
|
||||
"@0xproject/json-schemas": "^0.7.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"@0xproject/web3-wrapper": "^0.1.1",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"bintrees": "^1.0.2",
|
||||
"bn.js": "^4.11.8",
|
||||
|
||||
@@ -16,7 +16,6 @@ import {zeroExConfigSchema} from './schemas/zero_ex_config_schema';
|
||||
import {
|
||||
ECSignature,
|
||||
Order,
|
||||
OrderStateWatcherConfig,
|
||||
SignedOrder,
|
||||
TransactionReceiptWithDecodedLogs,
|
||||
Web3Provider,
|
||||
@@ -26,7 +25,7 @@ import {
|
||||
import {AbiDecoder} from './utils/abi_decoder';
|
||||
import {assert} from './utils/assert';
|
||||
import {constants} from './utils/constants';
|
||||
import {OrderStateUtils} from './utils/order_state_utils';
|
||||
import {decorators} from './utils/decorators';
|
||||
import {signatureUtils} from './utils/signature_utils';
|
||||
import {utils} from './utils/utils';
|
||||
|
||||
@@ -157,6 +156,7 @@ export class ZeroEx {
|
||||
* @param order An object that conforms to the Order or SignedOrder interface definitions.
|
||||
* @return The resulting orderHash from hashing the supplied order.
|
||||
*/
|
||||
@decorators.syncZeroExErrorHandler
|
||||
public static getOrderHashHex(order: Order|SignedOrder): string {
|
||||
assert.doesConformToSchema('order', order, schemas.orderSchema);
|
||||
const orderHashHex = utils.getOrderHashHex(order);
|
||||
@@ -201,7 +201,7 @@ export class ZeroEx {
|
||||
this._web3Wrapper, config.networkId, config.tokenRegistryContractAddress,
|
||||
);
|
||||
this.etherToken = new EtherTokenWrapper(
|
||||
this._web3Wrapper, config.networkId, this.token, config.etherTokenContractAddress,
|
||||
this._web3Wrapper, config.networkId, this._abiDecoder, this.token,
|
||||
);
|
||||
this.orderStateWatcher = new OrderStateWatcher(
|
||||
this._web3Wrapper, this._abiDecoder, this.token, this.exchange, config.orderWatcherConfig,
|
||||
|
||||
@@ -231,17 +231,51 @@
|
||||
],
|
||||
"name": "Approval",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": true,
|
||||
"name": "_owner",
|
||||
"type": "address"
|
||||
},
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "_value",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "Deposit",
|
||||
"type": "event"
|
||||
},
|
||||
{
|
||||
"anonymous": false,
|
||||
"inputs": [
|
||||
{
|
||||
"indexed": true,
|
||||
"name": "_owner",
|
||||
"type": "address"
|
||||
},
|
||||
{
|
||||
"indexed": false,
|
||||
"name": "_value",
|
||||
"type": "uint256"
|
||||
}
|
||||
],
|
||||
"name": "Withdrawal",
|
||||
"type": "event"
|
||||
}
|
||||
],
|
||||
"networks": {
|
||||
"1": {
|
||||
"address": "0x2956356cd2a2bf3202f771f50d3d14a367b48070"
|
||||
"address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
|
||||
},
|
||||
"3": {
|
||||
"address": "0xc00fd9820cd2898cc4c054b7bf142de637ad129a"
|
||||
},
|
||||
"42": {
|
||||
"address": "0x05d090b51c40b020eab3bfcb6a2dff130df22e9c"
|
||||
"address": "0x653e49e301e508a13237c0ddc98ae7d4cd2667a1"
|
||||
},
|
||||
"50": {
|
||||
"address": "0x871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c"
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as Web3 from 'web3';
|
||||
import {
|
||||
Artifact,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
ContractEventArgs,
|
||||
ContractEvents,
|
||||
EventCallback,
|
||||
@@ -14,7 +15,6 @@ import {
|
||||
InternalZeroExError,
|
||||
LogWithDecodedArgs,
|
||||
RawLog,
|
||||
SubscriptionOpts,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
@@ -50,10 +50,7 @@ export class ContractWrapper {
|
||||
this._onLogAddedSubscriptionToken = undefined;
|
||||
this._onLogRemovedSubscriptionToken = undefined;
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
protected unsubscribeAll(): void {
|
||||
const filterTokens = _.keys(this._filterCallbacks);
|
||||
_.each(filterTokens, filterToken => {
|
||||
this._unsubscribe(filterToken);
|
||||
@@ -86,9 +83,9 @@ export class ContractWrapper {
|
||||
return filterToken;
|
||||
}
|
||||
protected async _getLogsAsync<ArgsType extends ContractEventArgs>(
|
||||
address: string, eventName: ContractEvents, subscriptionOpts: SubscriptionOpts,
|
||||
address: string, eventName: ContractEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, subscriptionOpts);
|
||||
const filter = filterUtils.getFilter(address, eventName, indexFilterValues, abi, blockRange);
|
||||
const logs = await this._web3Wrapper.getLogsAsync(filter);
|
||||
const logsWithDecodedArguments = _.map(logs, this._tryToDecodeLogOrNoop.bind(this));
|
||||
return logsWithDecodedArguments;
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import {schemas} from '@0xproject/json-schemas';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {TransactionOpts, ZeroExError} from '../types';
|
||||
import {
|
||||
BlockRange,
|
||||
EtherTokenContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
EventCallback,
|
||||
IndexedFilterValues,
|
||||
LogWithDecodedArgs,
|
||||
TransactionOpts,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
|
||||
import {ContractWrapper} from './contract_wrapper';
|
||||
@@ -15,26 +26,24 @@ import {TokenWrapper} from './token_wrapper';
|
||||
* The caller can convert ETH into the equivalent number of wrapped ETH ERC20 tokens and back.
|
||||
*/
|
||||
export class EtherTokenWrapper extends ContractWrapper {
|
||||
private _etherTokenContractIfExists?: EtherTokenContract;
|
||||
private _etherTokenContractsByAddress: {[address: string]: EtherTokenContract} = {};
|
||||
private _tokenWrapper: TokenWrapper;
|
||||
private _contractAddressIfExists?: string;
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, tokenWrapper: TokenWrapper,
|
||||
contractAddressIfExists?: string) {
|
||||
super(web3Wrapper, networkId);
|
||||
constructor(web3Wrapper: Web3Wrapper, networkId: number, abiDecoder: AbiDecoder, tokenWrapper: TokenWrapper) {
|
||||
super(web3Wrapper, networkId, abiDecoder);
|
||||
this._tokenWrapper = tokenWrapper;
|
||||
this._contractAddressIfExists = contractAddressIfExists;
|
||||
}
|
||||
/**
|
||||
* Deposit ETH into the Wrapped ETH smart contract and issues the equivalent number of wrapped ETH tokens
|
||||
* to the depositor address. These wrapped ETH tokens can be used in 0x trades and are redeemable for 1-to-1
|
||||
* for ETH.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to deposit.
|
||||
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @param etherTokenAddress EtherToken address you wish to deposit into.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to deposit.
|
||||
* @param depositor The hex encoded user Ethereum address that would like to make the deposit.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async depositAsync(
|
||||
amountInWei: BigNumber, depositor: string, txOpts: TransactionOpts = {},
|
||||
etherTokenAddress: string, amountInWei: BigNumber, depositor: string, txOpts: TransactionOpts = {},
|
||||
): Promise<string> {
|
||||
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
|
||||
await assert.isSenderAddressAsync('depositor', depositor, this._web3Wrapper);
|
||||
@@ -42,7 +51,7 @@ export class EtherTokenWrapper extends ContractWrapper {
|
||||
const ethBalanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(depositor);
|
||||
assert.assert(ethBalanceInWei.gte(amountInWei), ZeroExError.InsufficientEthBalanceForDeposit);
|
||||
|
||||
const wethContract = await this._getEtherTokenContractAsync();
|
||||
const wethContract = await this._getEtherTokenContractAsync(etherTokenAddress);
|
||||
const txHash = await wethContract.deposit.sendTransactionAsync({
|
||||
from: depositor,
|
||||
value: amountInWei,
|
||||
@@ -54,22 +63,22 @@ export class EtherTokenWrapper extends ContractWrapper {
|
||||
/**
|
||||
* Withdraw ETH to the withdrawer's address from the wrapped ETH smart contract in exchange for the
|
||||
* equivalent number of wrapped ETH tokens.
|
||||
* @param etherTokenAddress EtherToken address you wish to withdraw from.
|
||||
* @param amountInWei Amount of ETH in Wei the caller wishes to withdraw.
|
||||
* @param withdrawer The hex encoded user Ethereum address that would like to make the withdrawl.
|
||||
* @param txOpts Transaction parameters.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
public async withdrawAsync(
|
||||
amountInWei: BigNumber, withdrawer: string, txOpts: TransactionOpts = {},
|
||||
etherTokenAddress: string, amountInWei: BigNumber, withdrawer: string, txOpts: TransactionOpts = {},
|
||||
): Promise<string> {
|
||||
assert.isValidBaseUnitAmount('amountInWei', amountInWei);
|
||||
await assert.isSenderAddressAsync('withdrawer', withdrawer, this._web3Wrapper);
|
||||
|
||||
const wethContractAddress = this.getContractAddress();
|
||||
const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(wethContractAddress, withdrawer);
|
||||
const WETHBalanceInBaseUnits = await this._tokenWrapper.getBalanceAsync(etherTokenAddress, withdrawer);
|
||||
assert.assert(WETHBalanceInBaseUnits.gte(amountInWei), ZeroExError.InsufficientWEthBalanceForWithdrawal);
|
||||
|
||||
const wethContract = await this._getEtherTokenContractAsync();
|
||||
const wethContract = await this._getEtherTokenContractAsync(etherTokenAddress);
|
||||
const txHash = await wethContract.withdraw.sendTransactionAsync(amountInWei, {
|
||||
from: withdrawer,
|
||||
gas: txOpts.gasLimit,
|
||||
@@ -78,27 +87,75 @@ export class EtherTokenWrapper extends ContractWrapper {
|
||||
return txHash;
|
||||
}
|
||||
/**
|
||||
* Retrieves the Wrapped Ether token contract address
|
||||
* @return The Wrapped Ether token contract address
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param etherTokenAddress An address of the ether token that emmited the logs.
|
||||
* @param eventName The ether token contract event you would like to subscribe to.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @param indexFilterValues An object where the keys are indexed args returned by the event and
|
||||
* the value is the value you are interested in. E.g `{_owner: aUserAddressHex}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public getContractAddress(): string {
|
||||
const contractAddress = this._getContractAddress(
|
||||
artifacts.EtherTokenArtifact, this._contractAddressIfExists,
|
||||
public async getLogsAsync<ArgsType extends EtherTokenContractEventArgs>(
|
||||
etherTokenAddress: string, eventName: EtherTokenEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.isETHAddressHex('etherTokenAddress', etherTokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, EtherTokenEvents);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues, artifacts.EtherTokenArtifact.abi,
|
||||
);
|
||||
return contractAddress;
|
||||
return logs;
|
||||
}
|
||||
/**
|
||||
* Subscribe to an event type emitted by the Token contract.
|
||||
* @param etherTokenAddress The hex encoded address where the ether token is deployed.
|
||||
* @param eventName The ether token contract event you would like to subscribe to.
|
||||
* @param indexFilterValues An object where the keys are indexed args returned by the event and
|
||||
* the value is the value you are interested in. E.g `{_owner: aUserAddressHex}`
|
||||
* @param callback Callback that gets called when a log is added/removed
|
||||
* @return Subscription token used later to unsubscribe
|
||||
*/
|
||||
public subscribe<ArgsType extends EtherTokenContractEventArgs>(
|
||||
etherTokenAddress: string, eventName: EtherTokenEvents, indexFilterValues: IndexedFilterValues,
|
||||
callback: EventCallback<ArgsType>): string {
|
||||
assert.isETHAddressHex('etherTokenAddress', etherTokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, EtherTokenEvents);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
assert.isFunction('callback', callback);
|
||||
const subscriptionToken = this._subscribe<ArgsType>(
|
||||
etherTokenAddress, eventName, indexFilterValues, artifacts.EtherTokenArtifact.abi, callback,
|
||||
);
|
||||
return subscriptionToken;
|
||||
}
|
||||
/**
|
||||
* Cancel a subscription
|
||||
* @param subscriptionToken Subscription token returned by `subscribe()`
|
||||
*/
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
private _invalidateContractInstance(): void {
|
||||
delete this._etherTokenContractIfExists;
|
||||
this.unsubscribeAll();
|
||||
this._etherTokenContractsByAddress = {};
|
||||
}
|
||||
private async _getEtherTokenContractAsync(): Promise<EtherTokenContract> {
|
||||
if (!_.isUndefined(this._etherTokenContractIfExists)) {
|
||||
return this._etherTokenContractIfExists;
|
||||
private async _getEtherTokenContractAsync(etherTokenAddress: string): Promise<EtherTokenContract> {
|
||||
let etherTokenContract = this._etherTokenContractsByAddress[etherTokenAddress];
|
||||
if (!_.isUndefined(etherTokenContract)) {
|
||||
return etherTokenContract;
|
||||
}
|
||||
const web3ContractInstance = await this._instantiateContractIfExistsAsync(
|
||||
artifacts.EtherTokenArtifact, this._contractAddressIfExists,
|
||||
artifacts.EtherTokenArtifact, etherTokenAddress,
|
||||
);
|
||||
const contractInstance = new EtherTokenContract(web3ContractInstance, this._web3Wrapper.getContractDefaults());
|
||||
this._etherTokenContractIfExists = contractInstance;
|
||||
return this._etherTokenContractIfExists;
|
||||
etherTokenContract = contractInstance;
|
||||
this._etherTokenContractsByAddress[etherTokenAddress] = etherTokenContract;
|
||||
return etherTokenContract;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as Web3 from 'web3';
|
||||
import {artifacts} from '../artifacts';
|
||||
import {
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogArgs,
|
||||
ECSignature,
|
||||
EventCallback,
|
||||
@@ -15,9 +16,7 @@ import {
|
||||
ExchangeContractEventArgs,
|
||||
ExchangeEvents,
|
||||
IndexedFilterValues,
|
||||
LogCancelContractEventArgs,
|
||||
LogErrorContractEventArgs,
|
||||
LogFillContractEventArgs,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
Order,
|
||||
@@ -26,9 +25,7 @@ import {
|
||||
OrderFillRequest,
|
||||
OrderTransactionOpts,
|
||||
OrderValues,
|
||||
RawLog,
|
||||
SignedOrder,
|
||||
SubscriptionOpts,
|
||||
ValidateOrderFillableOpts,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
@@ -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;
|
||||
}
|
||||
/**
|
||||
@@ -165,7 +162,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
@@ -221,7 +218,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrdersUpToAsync(signedOrders: SignedOrder[], fillTakerTokenAmount: BigNumber,
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
@@ -302,7 +299,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchFillOrdersAsync(orderFillRequests: OrderFillRequest[],
|
||||
shouldThrowOnInsufficientBalanceOrAllowance: boolean,
|
||||
takerAddress: string,
|
||||
@@ -375,7 +372,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async fillOrKillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber,
|
||||
takerAddress: string,
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
@@ -420,7 +417,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param orderTransactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchFillOrKillAsync(orderFillRequests: OrderFillRequest[],
|
||||
takerAddress: string,
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
@@ -488,7 +485,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param transactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async cancelOrderAsync(order: Order|SignedOrder,
|
||||
cancelTakerTokenAmount: BigNumber,
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
@@ -529,7 +526,7 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
* @param transactionOpts Optional arguments this method accepts.
|
||||
* @return Transaction hash.
|
||||
*/
|
||||
@decorators.contractCallErrorHandler
|
||||
@decorators.asyncZeroExErrorHandler
|
||||
public async batchCancelOrdersAsync(orderCancellationRequests: OrderCancellationRequest[],
|
||||
orderTransactionOpts: OrderTransactionOpts = {}): Promise<string> {
|
||||
assert.doesConformToSchema('orderCancellationRequests', orderCancellationRequests,
|
||||
@@ -610,23 +607,29 @@ export class ExchangeWrapper extends ContractWrapper {
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
/**
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param eventName The exchange contract event you would like to subscribe to.
|
||||
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @param indexFilterValues An object where the keys are indexed args returned by the event and
|
||||
* the value is the value you are interested in. E.g `{_from: aUserAddressHex}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public async getLogsAsync<ArgsType extends ExchangeContractEventArgs>(
|
||||
eventName: ExchangeEvents, subscriptionOpts: SubscriptionOpts, indexFilterValues: IndexedFilterValues,
|
||||
eventName: ExchangeEvents, blockRange: BlockRange, indexFilterValues: IndexedFilterValues,
|
||||
): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.doesBelongToStringEnum('eventName', eventName, ExchangeEvents);
|
||||
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const exchangeContractAddress = this.getContractAddress();
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
exchangeContractAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.ExchangeArtifact.abi,
|
||||
exchangeContractAddress, eventName, blockRange, indexFilterValues, artifacts.ExchangeArtifact.abi,
|
||||
);
|
||||
return logs;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -5,11 +5,11 @@ import * as _ from 'lodash';
|
||||
|
||||
import {artifacts} from '../artifacts';
|
||||
import {
|
||||
BlockRange,
|
||||
EventCallback,
|
||||
IndexedFilterValues,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
SubscriptionOpts,
|
||||
TokenContractEventArgs,
|
||||
TokenEvents,
|
||||
TransactionOpts,
|
||||
@@ -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
|
||||
@@ -283,24 +281,30 @@ export class TokenWrapper extends ContractWrapper {
|
||||
public unsubscribe(subscriptionToken: string): void {
|
||||
this._unsubscribe(subscriptionToken);
|
||||
}
|
||||
/**
|
||||
* Cancels all existing subscriptions
|
||||
*/
|
||||
public unsubscribeAll(): void {
|
||||
super.unsubscribeAll();
|
||||
}
|
||||
/**
|
||||
* Gets historical logs without creating a subscription
|
||||
* @param tokenAddress An address of the token that emmited the logs.
|
||||
* @param eventName The token contract event you would like to subscribe to.
|
||||
* @param subscriptionOpts Subscriptions options that let you configure the subscription.
|
||||
* @param blockRange Block range to get logs from.
|
||||
* @param indexFilterValues An object where the keys are indexed args returned by the event and
|
||||
* the value is the value you are interested in. E.g `{_from: aUserAddressHex}`
|
||||
* @return Array of logs that match the parameters
|
||||
*/
|
||||
public async getLogsAsync<ArgsType extends TokenContractEventArgs>(
|
||||
tokenAddress: string, eventName: TokenEvents, subscriptionOpts: SubscriptionOpts,
|
||||
tokenAddress: string, eventName: TokenEvents, blockRange: BlockRange,
|
||||
indexFilterValues: IndexedFilterValues): Promise<Array<LogWithDecodedArgs<ArgsType>>> {
|
||||
assert.isETHAddressHex('tokenAddress', tokenAddress);
|
||||
assert.doesBelongToStringEnum('eventName', eventName, TokenEvents);
|
||||
assert.doesConformToSchema('subscriptionOpts', subscriptionOpts, schemas.subscriptionOptsSchema);
|
||||
assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema);
|
||||
assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema);
|
||||
const logs = await this._getLogsAsync<ArgsType>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues, artifacts.TokenArtifact.abi,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues, artifacts.TokenArtifact.abi,
|
||||
);
|
||||
return logs;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export {ZeroEx} from './0x';
|
||||
|
||||
export {
|
||||
Order,
|
||||
BlockParamLiteral,
|
||||
SignedOrder,
|
||||
ECSignature,
|
||||
ZeroExError,
|
||||
@@ -12,7 +13,7 @@ export {
|
||||
ExchangeEvents,
|
||||
TokenEvents,
|
||||
IndexedFilterValues,
|
||||
SubscriptionOpts,
|
||||
BlockRange,
|
||||
BlockParam,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
@@ -23,10 +24,14 @@ export {
|
||||
TransferContractEventArgs,
|
||||
ApprovalContractEventArgs,
|
||||
TokenContractEventArgs,
|
||||
EtherTokenContractEventArgs,
|
||||
WithdrawalContractEventArgs,
|
||||
DepositContractEventArgs,
|
||||
ContractEventArgs,
|
||||
ContractEventArg,
|
||||
Web3Provider,
|
||||
ZeroExConfig,
|
||||
EtherTokenEvents,
|
||||
TransactionReceiptWithDecodedLogs,
|
||||
LogWithDecodedArgs,
|
||||
MethodOpts,
|
||||
|
||||
@@ -5,13 +5,10 @@ import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
BlockParamLiteral,
|
||||
EventCallback,
|
||||
EventWatcherCallback,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
import {assert} from '../utils/assert';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
const DEFAULT_EVENT_POLLING_INTERVAL_MS = 200;
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@ import {BigNumber} from 'bignumber.js';
|
||||
import {RBTree} from 'bintrees';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {ZeroEx} from '../0x';
|
||||
import {SignedOrder, ZeroExError} from '../types';
|
||||
import {ZeroExError} from '../types';
|
||||
import {utils} from '../utils/utils';
|
||||
|
||||
const DEFAULT_EXPIRATION_MARGIN_MS = 0;
|
||||
|
||||
@@ -4,7 +4,6 @@ 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';
|
||||
@@ -13,6 +12,8 @@ import {
|
||||
ApprovalContractEventArgs,
|
||||
BlockParamLiteral,
|
||||
ContractEventArgs,
|
||||
DepositContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
ExchangeContractErrs,
|
||||
ExchangeEvents,
|
||||
LogCancelContractEventArgs,
|
||||
@@ -25,7 +26,7 @@ import {
|
||||
SignedOrder,
|
||||
TokenEvents,
|
||||
TransferContractEventArgs,
|
||||
Web3Provider,
|
||||
WithdrawalContractEventArgs,
|
||||
ZeroExError,
|
||||
} from '../types';
|
||||
import {AbiDecoder} from '../utils/abi_decoder';
|
||||
@@ -245,6 +246,36 @@ export class OrderStateWatcher {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case EtherTokenEvents.Deposit:
|
||||
{
|
||||
// Invalidate cache
|
||||
const args = decodedLog.args as DepositContractEventArgs;
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._owner);
|
||||
// Revalidate orders
|
||||
makerToken = decodedLog.address;
|
||||
makerAddress = args._owner;
|
||||
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
|
||||
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
|
||||
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
|
||||
await this._emitRevalidateOrdersAsync(orderHashes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case EtherTokenEvents.Withdrawal:
|
||||
{
|
||||
// Invalidate cache
|
||||
const args = decodedLog.args as WithdrawalContractEventArgs;
|
||||
this._balanceAndProxyAllowanceLazyStore.deleteBalance(decodedLog.address, args._owner);
|
||||
// Revalidate orders
|
||||
makerToken = decodedLog.address;
|
||||
makerAddress = args._owner;
|
||||
if (!_.isUndefined(this._dependentOrderHashes[makerAddress]) &&
|
||||
!_.isUndefined(this._dependentOrderHashes[makerAddress][makerToken])) {
|
||||
const orderHashes = Array.from(this._dependentOrderHashes[makerAddress][makerToken]);
|
||||
await this._emitRevalidateOrdersAsync(orderHashes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ExchangeEvents.LogFill:
|
||||
{
|
||||
// Invalidate cache
|
||||
|
||||
@@ -8,7 +8,6 @@ export const zeroExConfigSchema = {
|
||||
gasPrice: {$ref: '/Number'},
|
||||
exchangeContractAddress: {$ref: '/Address'},
|
||||
tokenRegistryContractAddress: {$ref: '/Address'},
|
||||
etherTokenContractAddress: {$ref: '/Address'},
|
||||
orderWatcherConfig: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -28,6 +28,7 @@ export enum ZeroExError {
|
||||
export enum InternalZeroExError {
|
||||
NoAbiDecoder = 'NO_ABI_DECODER',
|
||||
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
|
||||
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -146,8 +147,17 @@ export interface ApprovalContractEventArgs {
|
||||
_spender: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export interface DepositContractEventArgs {
|
||||
_owner: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export interface WithdrawalContractEventArgs {
|
||||
_owner: string;
|
||||
_value: BigNumber;
|
||||
}
|
||||
export type TokenContractEventArgs = TransferContractEventArgs|ApprovalContractEventArgs;
|
||||
export type ContractEventArgs = ExchangeContractEventArgs|TokenContractEventArgs;
|
||||
export type EtherTokenContractEventArgs = TokenContractEventArgs|DepositContractEventArgs|WithdrawalContractEventArgs;
|
||||
export type ContractEventArgs = ExchangeContractEventArgs|TokenContractEventArgs|EtherTokenContractEventArgs;
|
||||
export type ContractEventArg = string|BigNumber;
|
||||
|
||||
export interface Order {
|
||||
@@ -201,7 +211,14 @@ export enum TokenEvents {
|
||||
Approval = 'Approval',
|
||||
}
|
||||
|
||||
export type ContractEvents = TokenEvents|ExchangeEvents;
|
||||
export enum EtherTokenEvents {
|
||||
Transfer = 'Transfer',
|
||||
Approval = 'Approval',
|
||||
Deposit = 'Deposit',
|
||||
Withdrawal = 'Withdrawal',
|
||||
}
|
||||
|
||||
export type ContractEvents = TokenEvents|ExchangeEvents|EtherTokenEvents;
|
||||
|
||||
export interface IndexedFilterValues {
|
||||
[index: string]: ContractEventArg;
|
||||
@@ -217,7 +234,7 @@ export enum BlockParamLiteral {
|
||||
|
||||
export type BlockParam = BlockParamLiteral|number;
|
||||
|
||||
export interface SubscriptionOpts {
|
||||
export interface BlockRange {
|
||||
fromBlock: BlockParam;
|
||||
toBlock: BlockParam;
|
||||
}
|
||||
@@ -235,6 +252,7 @@ export interface OrderFillRequest {
|
||||
}
|
||||
|
||||
export type AsyncMethod = (...args: any[]) => Promise<any>;
|
||||
export type SyncMethod = (...args: any[]) => any;
|
||||
|
||||
/**
|
||||
* We re-export the `Web3.Provider` type specified in the Web3 Typescript typings
|
||||
@@ -268,7 +286,6 @@ export interface OrderStateWatcherConfig {
|
||||
* gasPrice: Gas price to use with every transaction
|
||||
* exchangeContractAddress: The address of an exchange contract to use
|
||||
* tokenRegistryContractAddress: The address of a token registry contract to use
|
||||
* etherTokenContractAddress: The address of an ether token contract to use
|
||||
* tokenTransferProxyContractAddress: The address of the token transfer proxy contract to use
|
||||
* orderWatcherConfig: All the configs related to the orderWatcher
|
||||
*/
|
||||
@@ -277,7 +294,6 @@ export interface ZeroExConfig {
|
||||
gasPrice?: BigNumber;
|
||||
exchangeContractAddress?: string;
|
||||
tokenRegistryContractAddress?: string;
|
||||
etherTokenContractAddress?: string;
|
||||
tokenTransferProxyContractAddress?: string;
|
||||
orderWatcherConfig?: OrderStateWatcherConfig;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -6,6 +6,7 @@ export const constants = {
|
||||
MAX_DIGITS_IN_UNSIGNED_256_INT: 78,
|
||||
INVALID_JUMP_PATTERN: 'invalid JUMP at',
|
||||
OUT_OF_GAS_PATTERN: 'out of gas',
|
||||
INVALID_TAKER_FORMAT: 'instance.taker is not of a type(s) string',
|
||||
UNLIMITED_ALLOWANCE_IN_BASE_UNITS: new BigNumber(2).pow(256).minus(1),
|
||||
DEFAULT_BLOCK_POLLING_INTERVAL: 1000,
|
||||
};
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
import * as _ from 'lodash';
|
||||
|
||||
import {AsyncMethod, ZeroExError} from '../types';
|
||||
import {AsyncMethod, SyncMethod, ZeroExError} from '../types';
|
||||
|
||||
import {constants} from './constants';
|
||||
|
||||
export const decorators = {
|
||||
/**
|
||||
* Source: https://stackoverflow.com/a/29837695/3546986
|
||||
*/
|
||||
contractCallErrorHandler(target: object,
|
||||
key: string|symbol,
|
||||
descriptor: TypedPropertyDescriptor<AsyncMethod>,
|
||||
): TypedPropertyDescriptor<AsyncMethod> {
|
||||
type ErrorTransformer = (err: Error) => Error;
|
||||
|
||||
const contractCallErrorTransformer = (error: Error) => {
|
||||
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
|
||||
return new Error(ZeroExError.InvalidJump);
|
||||
}
|
||||
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
|
||||
return new Error(ZeroExError.OutOfGas);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
const schemaErrorTransformer = (error: Error) => {
|
||||
if (_.includes(error.message, constants.INVALID_TAKER_FORMAT)) {
|
||||
// tslint:disable-next-line:max-line-length
|
||||
const errMsg = 'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS';
|
||||
return new Error(errMsg);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
/**
|
||||
* Source: https://stackoverflow.com/a/29837695/3546986
|
||||
*/
|
||||
const asyncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
|
||||
const asyncErrorHandlingDecorator = (
|
||||
target: object, key: string|symbol, descriptor: TypedPropertyDescriptor<AsyncMethod>,
|
||||
) => {
|
||||
const originalMethod = (descriptor.value as AsyncMethod);
|
||||
|
||||
// Do not use arrow syntax here. Use a function expression in
|
||||
@@ -22,16 +42,46 @@ export const decorators = {
|
||||
const result = await originalMethod.apply(this, args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (_.includes(error.message, constants.INVALID_JUMP_PATTERN)) {
|
||||
throw new Error(ZeroExError.InvalidJump);
|
||||
}
|
||||
if (_.includes(error.message, constants.OUT_OF_GAS_PATTERN)) {
|
||||
throw new Error(ZeroExError.OutOfGas);
|
||||
}
|
||||
throw error;
|
||||
const transformedError = errorTransformer(error);
|
||||
throw transformedError;
|
||||
}
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
},
|
||||
};
|
||||
|
||||
return asyncErrorHandlingDecorator;
|
||||
};
|
||||
|
||||
const syncErrorHandlerFactory = (errorTransformer: ErrorTransformer) => {
|
||||
const syncErrorHandlingDecorator = (
|
||||
target: object, key: string|symbol, descriptor: TypedPropertyDescriptor<SyncMethod>,
|
||||
) => {
|
||||
const originalMethod = (descriptor.value as SyncMethod);
|
||||
|
||||
// Do not use arrow syntax here. Use a function expression in
|
||||
// order to use the correct value of `this` in this method
|
||||
// tslint:disable-next-line:only-arrow-functions
|
||||
descriptor.value = function(...args: any[]) {
|
||||
try {
|
||||
const result = originalMethod.apply(this, args);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const transformedError = errorTransformer(error);
|
||||
throw transformedError;
|
||||
}
|
||||
};
|
||||
|
||||
return descriptor;
|
||||
};
|
||||
|
||||
return syncErrorHandlingDecorator;
|
||||
};
|
||||
|
||||
// _.flow(f, g) = f ∘ g
|
||||
const zeroExErrorTransformer = _.flow(schemaErrorTransformer, contractCallErrorTransformer);
|
||||
|
||||
export const decorators = {
|
||||
asyncZeroExErrorHandler: asyncErrorHandlerFactory(zeroExErrorTransformer),
|
||||
syncZeroExErrorHandler: syncErrorHandlerFactory(zeroExErrorTransformer),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import * as _ from 'lodash';
|
||||
import * as uuid from 'uuid/v4';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {ContractEvents, IndexedFilterValues, SubscriptionOpts} from '../types';
|
||||
import {BlockRange, ContractEvents, IndexedFilterValues} from '../types';
|
||||
|
||||
const TOPIC_LENGTH = 32;
|
||||
|
||||
@@ -14,7 +14,7 @@ export const filterUtils = {
|
||||
},
|
||||
getFilter(address: string, eventName: ContractEvents,
|
||||
indexFilterValues: IndexedFilterValues, abi: Web3.ContractAbi,
|
||||
subscriptionOpts?: SubscriptionOpts): Web3.FilterObject {
|
||||
blockRange?: BlockRange): Web3.FilterObject {
|
||||
const eventAbi = _.find(abi, {name: eventName}) as Web3.EventAbi;
|
||||
const eventSignature = filterUtils.getEventSignatureFromAbiByName(eventAbi, eventName);
|
||||
const topicForEventSignature = ethUtil.addHexPrefix(jsSHA3.keccak256(eventSignature));
|
||||
@@ -24,9 +24,9 @@ export const filterUtils = {
|
||||
address,
|
||||
topics,
|
||||
};
|
||||
if (!_.isUndefined(subscriptionOpts)) {
|
||||
if (!_.isUndefined(blockRange)) {
|
||||
filter = {
|
||||
...subscriptionOpts,
|
||||
...blockRange,
|
||||
...filter,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
@@ -82,9 +82,9 @@ describe('ZeroEx library', () => {
|
||||
it('should return true if the signature does pertain to the dataHex & address', async () => {
|
||||
const isValidSignatureLocal = ZeroEx.isValidSignature(dataHex, signature, address);
|
||||
expect(isValidSignatureLocal).to.be.true();
|
||||
const isValidSignatureOnContract = await (zeroEx.exchange as any)
|
||||
._isValidSignatureUsingContractCallAsync(dataHex, signature, address);
|
||||
return expect(isValidSignatureOnContract).to.be.true();
|
||||
return expect(
|
||||
(zeroEx.exchange as any)._isValidSignatureUsingContractCallAsync(dataHex, signature, address),
|
||||
).to.become(true);
|
||||
});
|
||||
});
|
||||
describe('#generateSalt', () => {
|
||||
@@ -152,6 +152,15 @@ describe('ZeroEx library', () => {
|
||||
const orderHash = ZeroEx.getOrderHashHex(order);
|
||||
expect(orderHash).to.be.equal(expectedOrderHash);
|
||||
});
|
||||
it('throws a readable error message if taker format is invalid', async () => {
|
||||
const orderWithInvalidtakerFormat = {
|
||||
...order,
|
||||
taker: null as any as string,
|
||||
};
|
||||
// tslint:disable-next-line:max-line-length
|
||||
const expectedErrorMessage = 'Order taker must be of type string. If you want anyone to be able to fill an order - pass ZeroEx.NULL_ADDRESS';
|
||||
expect(() => ZeroEx.getOrderHashHex(orderWithInvalidtakerFormat)).to.throw(expectedErrorMessage);
|
||||
});
|
||||
});
|
||||
describe('#signOrderHashAsync', () => {
|
||||
let stubs: Sinon.SinonStub[] = [];
|
||||
@@ -244,14 +253,6 @@ describe('ZeroEx library', () => {
|
||||
const zeroExWithWrongExchangeAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
expect(zeroExWithWrongExchangeAddress.exchange.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
|
||||
});
|
||||
it('allows to specify ether token contract address', async () => {
|
||||
const zeroExConfig = {
|
||||
etherTokenContractAddress: ZeroEx.NULL_ADDRESS,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const zeroExWithWrongEtherTokenAddress = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
expect(zeroExWithWrongEtherTokenAddress.etherToken.getContractAddress()).to.be.equal(ZeroEx.NULL_ADDRESS);
|
||||
});
|
||||
it('allows to specify token registry token contract address', async () => {
|
||||
const zeroExConfig = {
|
||||
tokenRegistryContractAddress: ZeroEx.NULL_ADDRESS,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -4,10 +4,25 @@ import * as chai from 'chai';
|
||||
import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {ZeroEx, ZeroExError} from '../src';
|
||||
import {
|
||||
ApprovalContractEventArgs,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
DepositContractEventArgs,
|
||||
EtherTokenEvents,
|
||||
Token,
|
||||
TransferContractEventArgs,
|
||||
WithdrawalContractEventArgs,
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
} from '../src';
|
||||
import {artifacts} from '../src/artifacts';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
import {TokenUtils} from './utils/token_utils';
|
||||
import {web3Factory} from './utils/web3_factory';
|
||||
|
||||
chaiSetup.configure();
|
||||
@@ -23,24 +38,32 @@ const MAX_REASONABLE_GAS_COST_IN_WEI = 62517;
|
||||
describe('EtherTokenWrapper', () => {
|
||||
let web3: Web3;
|
||||
let zeroEx: ZeroEx;
|
||||
let tokens: Token[];
|
||||
let userAddresses: string[];
|
||||
let addressWithETH: string;
|
||||
let wethContractAddress: string;
|
||||
let depositWeiAmount: BigNumber;
|
||||
let decimalPlaces: number;
|
||||
let addressWithoutFunds: string;
|
||||
const gasPrice = new BigNumber(1);
|
||||
const zeroExConfig = {
|
||||
gasPrice,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
};
|
||||
const transferAmount = new BigNumber(42);
|
||||
const allowanceAmount = new BigNumber(42);
|
||||
const depositAmount = new BigNumber(42);
|
||||
const withdrawalAmount = new BigNumber(42);
|
||||
before(async () => {
|
||||
web3 = web3Factory.create();
|
||||
zeroEx = new ZeroEx(web3.currentProvider, zeroExConfig);
|
||||
tokens = await zeroEx.tokenRegistry.getTokensAsync();
|
||||
userAddresses = await zeroEx.getAvailableAddressesAsync();
|
||||
addressWithETH = userAddresses[0];
|
||||
wethContractAddress = zeroEx.etherToken.getContractAddress();
|
||||
wethContractAddress = (zeroEx.etherToken as any)._getContractAddress(artifacts.EtherTokenArtifact);
|
||||
depositWeiAmount = (zeroEx as any)._web3Wrapper.toWei(new BigNumber(5));
|
||||
decimalPlaces = 7;
|
||||
addressWithoutFunds = userAddresses[1];
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -55,7 +78,7 @@ describe('EtherTokenWrapper', () => {
|
||||
expect(preETHBalance).to.be.bignumber.gt(0);
|
||||
expect(preWETHBalance).to.be.bignumber.equal(0);
|
||||
|
||||
const txHash = await zeroEx.etherToken.depositAsync(depositWeiAmount, addressWithETH);
|
||||
const txHash = await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
const postETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -73,7 +96,7 @@ describe('EtherTokenWrapper', () => {
|
||||
const overETHBalanceinWei = preETHBalance.add(extraETHBalance);
|
||||
|
||||
return expect(
|
||||
zeroEx.etherToken.depositAsync(overETHBalanceinWei, addressWithETH),
|
||||
zeroEx.etherToken.depositAsync(wethContractAddress, overETHBalanceinWei, addressWithETH),
|
||||
).to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit);
|
||||
});
|
||||
});
|
||||
@@ -81,7 +104,7 @@ describe('EtherTokenWrapper', () => {
|
||||
it('should successfully withdraw ETH in return for Wrapped ETH tokens', async () => {
|
||||
const ETHBalanceInWei = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
|
||||
await zeroEx.etherToken.depositAsync(depositWeiAmount, addressWithETH);
|
||||
await zeroEx.etherToken.depositAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
|
||||
const expectedPreETHBalance = ETHBalanceInWei.minus(depositWeiAmount);
|
||||
const preETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -90,7 +113,7 @@ describe('EtherTokenWrapper', () => {
|
||||
expect(gasCost).to.be.bignumber.lte(MAX_REASONABLE_GAS_COST_IN_WEI);
|
||||
expect(preWETHBalance).to.be.bignumber.equal(depositWeiAmount);
|
||||
|
||||
const txHash = await zeroEx.etherToken.withdrawAsync(depositWeiAmount, addressWithETH);
|
||||
const txHash = await zeroEx.etherToken.withdrawAsync(wethContractAddress, depositWeiAmount, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
const postETHBalance = await (zeroEx as any)._web3Wrapper.getBalanceInWeiAsync(addressWithETH);
|
||||
@@ -108,8 +131,213 @@ describe('EtherTokenWrapper', () => {
|
||||
const overWETHBalance = preWETHBalance.add(999999999);
|
||||
|
||||
return expect(
|
||||
zeroEx.etherToken.withdrawAsync(overWETHBalance, addressWithETH),
|
||||
zeroEx.etherToken.withdrawAsync(wethContractAddress, overWETHBalance, addressWithETH),
|
||||
).to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal);
|
||||
});
|
||||
});
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
let etherTokenAddress: string;
|
||||
before(() => {
|
||||
const tokenUtils = new TokenUtils(tokens);
|
||||
const etherToken = tokenUtils.getWethTokenOrThrow();
|
||||
etherTokenAddress = etherToken.address;
|
||||
});
|
||||
afterEach(() => {
|
||||
zeroEx.etherToken.unsubscribeAll();
|
||||
});
|
||||
// Hack: Mocha does not allow a test to be both async and have a `done` callback
|
||||
// Since we need to await the receipt of the event in the `subscribe` callback,
|
||||
// we do need both. A hack is to make the top-level async fn w/ a done callback and then
|
||||
// wrap the rest of the test in an async block
|
||||
// Source: https://github.com/mochajs/mocha/issues/2407
|
||||
it('Should receive the Transfer event when tokens are transfered', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<TransferContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
expect(logEvent.log.logIndex).to.be.equal(0);
|
||||
expect(logEvent.log.transactionIndex).to.be.equal(0);
|
||||
expect(logEvent.log.blockNumber).to.be.a('number');
|
||||
const args = logEvent.log.args;
|
||||
expect(args._from).to.be.equal(addressWithETH);
|
||||
expect(args._to).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(transferAmount);
|
||||
done();
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callback);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Approval event when allowance is being set', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._spender).to.be.equal(addressWithoutFunds);
|
||||
expect(args._value).to.be.bignumber.equal(allowanceAmount);
|
||||
done();
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Approval, indexFilterValues, callback);
|
||||
await zeroEx.token.setAllowanceAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, allowanceAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Deposit event when ether is being deposited', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<DepositContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
done();
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Deposit, indexFilterValues, callback);
|
||||
await zeroEx.etherToken.depositAsync(
|
||||
etherTokenAddress, depositAmount, addressWithETH,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should receive the Withdrawal event when ether is being withdrawn', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callback = (err: Error, logEvent: DecodedLogEvent<WithdrawalContractEventArgs>) => {
|
||||
expect(err).to.be.null();
|
||||
expect(logEvent).to.not.be.undefined();
|
||||
expect(logEvent.isRemoved).to.be.false();
|
||||
const args = logEvent.log.args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
done();
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(
|
||||
etherTokenAddress, depositAmount, addressWithETH,
|
||||
);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Withdrawal, indexFilterValues, callback);
|
||||
await zeroEx.etherToken.withdrawAsync(
|
||||
etherTokenAddress, withdrawalAmount, addressWithETH,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('should cancel outstanding subscriptions when ZeroEx.setProvider is called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled,
|
||||
);
|
||||
const callbackToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done();
|
||||
};
|
||||
const newProvider = web3Factory.getRpcProvider();
|
||||
zeroEx.setProvider(newProvider, constants.TESTRPC_NETWORK_ID);
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackToBeCalled,
|
||||
);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
})().catch(done);
|
||||
});
|
||||
it('Should cancel subscription when unsubscribe called', (done: DoneCallback) => {
|
||||
(async () => {
|
||||
const callbackNeverToBeCalled = (err: Error, logEvent: DecodedLogEvent<ApprovalContractEventArgs>) => {
|
||||
done(new Error('Expected this subscription to have been cancelled'));
|
||||
};
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, transferAmount, addressWithETH);
|
||||
const subscriptionToken = zeroEx.etherToken.subscribe(
|
||||
etherTokenAddress, EtherTokenEvents.Transfer, indexFilterValues, callbackNeverToBeCalled);
|
||||
zeroEx.etherToken.unsubscribe(subscriptionToken);
|
||||
await zeroEx.token.transferAsync(
|
||||
etherTokenAddress, addressWithETH, addressWithoutFunds, transferAmount,
|
||||
);
|
||||
done();
|
||||
})().catch(done);
|
||||
});
|
||||
});
|
||||
describe('#getLogsAsync', () => {
|
||||
let etherTokenAddress: string;
|
||||
let tokenTransferProxyAddress: string;
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
let txHash: string;
|
||||
before(() => {
|
||||
addressWithETH = userAddresses[0];
|
||||
const tokenUtils = new TokenUtils(tokens);
|
||||
const etherToken = tokenUtils.getWethTokenOrThrow();
|
||||
etherTokenAddress = etherToken.address;
|
||||
tokenTransferProxyAddress = zeroEx.proxy.getContractAddress();
|
||||
});
|
||||
it('should get logs with decoded args emitted by Approval', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = EtherTokenEvents.Approval;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._spender).to.be.equal(tokenTransferProxyAddress);
|
||||
expect(args._value).to.be.bignumber.equal(zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS);
|
||||
});
|
||||
it('should get logs with decoded args emitted by Deposit', async () => {
|
||||
await zeroEx.etherToken.depositAsync(etherTokenAddress, depositAmount, addressWithETH);
|
||||
const eventName = EtherTokenEvents.Deposit;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<DepositContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
expect(args._value).to.be.bignumber.equal(depositAmount);
|
||||
});
|
||||
it('should only get the logs with the correct event name', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const differentEventName = EtherTokenEvents.Transfer;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync(
|
||||
etherTokenAddress, differentEventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
it('should only get the logs with the correct indexed fields', async () => {
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithETH);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
txHash = await zeroEx.token.setUnlimitedProxyAllowanceAsync(etherTokenAddress, addressWithoutFunds);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = EtherTokenEvents.Approval;
|
||||
const indexFilterValues = {
|
||||
_owner: addressWithETH,
|
||||
};
|
||||
const logs = await zeroEx.etherToken.getLogsAsync<ApprovalContractEventArgs>(
|
||||
etherTokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
expect(args._owner).to.be.equal(addressWithETH);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -5,16 +5,15 @@ import 'mocha';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
ExchangeContractErrs,
|
||||
ExchangeEvents,
|
||||
LogCancelContractEventArgs,
|
||||
LogEvent,
|
||||
LogFillContractEventArgs,
|
||||
OrderCancellationRequest,
|
||||
OrderFillRequest,
|
||||
SignedOrder,
|
||||
SubscriptionOpts,
|
||||
Token,
|
||||
ZeroEx,
|
||||
} from '../src';
|
||||
@@ -761,7 +760,7 @@ describe('ExchangeWrapper', () => {
|
||||
let takerAddress: string;
|
||||
const fillableAmount = new BigNumber(5);
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
const subscriptionOpts: SubscriptionOpts = {
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
@@ -782,7 +781,7 @@ describe('ExchangeWrapper', () => {
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const eventName = ExchangeEvents.LogFill;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.exchange.getLogsAsync(eventName, subscriptionOpts, indexFilterValues);
|
||||
const logs = await zeroEx.exchange.getLogsAsync(eventName, blockRange, indexFilterValues);
|
||||
expect(logs).to.have.length(1);
|
||||
expect(logs[0].event).to.be.equal(eventName);
|
||||
});
|
||||
@@ -796,7 +795,7 @@ describe('ExchangeWrapper', () => {
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
const differentEventName = ExchangeEvents.LogCancel;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.exchange.getLogsAsync(differentEventName, subscriptionOpts, indexFilterValues);
|
||||
const logs = await zeroEx.exchange.getLogsAsync(differentEventName, blockRange, indexFilterValues);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
it('should only get the logs with the correct indexed fields', async () => {
|
||||
@@ -822,7 +821,7 @@ describe('ExchangeWrapper', () => {
|
||||
maker: differentMakerAddress,
|
||||
};
|
||||
const logs = await zeroEx.exchange.getLogsAsync<LogFillContractEventArgs>(
|
||||
eventName, subscriptionOpts, indexFilterValues,
|
||||
eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
import * as _ from 'lodash';
|
||||
@@ -7,19 +6,15 @@ 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 {chaiSetup} from './utils/chai_setup';
|
||||
@@ -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,
|
||||
@@ -67,7 +61,6 @@ describe('OrderStateWatcher', () => {
|
||||
fillScenarios = new FillScenarios(zeroEx, userAddresses, tokens, zrxTokenAddress, exchangeContractAddress);
|
||||
await fillScenarios.initTokenBalancesAsync();
|
||||
[makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
web3Wrapper = (zeroEx as any)._web3Wrapper;
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -142,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');
|
||||
@@ -151,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();
|
||||
@@ -208,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);
|
||||
@@ -242,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);
|
||||
@@ -260,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);
|
||||
@@ -289,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);
|
||||
|
||||
@@ -343,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);
|
||||
@@ -370,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);
|
||||
@@ -401,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) => {
|
||||
@@ -434,7 +412,6 @@ describe('OrderStateWatcher', () => {
|
||||
});
|
||||
zeroEx.orderStateWatcher.subscribe(callback);
|
||||
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
await zeroEx.exchange.cancelOrderAsync(signedOrder, fillableAmount);
|
||||
})().catch(done);
|
||||
});
|
||||
@@ -466,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);
|
||||
|
||||
@@ -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 = {
|
||||
@@ -53,7 +52,6 @@ describe('OrderValidation', () => {
|
||||
const [makerToken, takerToken] = tokenUtils.getDummyTokens();
|
||||
makerTokenAddress = makerToken.address;
|
||||
takerTokenAddress = takerToken.address;
|
||||
orderValidationUtils = new OrderValidationUtils(zeroEx.token, zeroEx.exchange);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await blockchainLifecycle.startAsync();
|
||||
@@ -181,7 +179,6 @@ describe('OrderValidation', () => {
|
||||
});
|
||||
describe('validateCancelOrderAndThrowIfInvalidAsync', () => {
|
||||
let signedOrder: SignedOrder;
|
||||
let orderHashHex: string;
|
||||
const cancelAmount = new BigNumber(3);
|
||||
beforeEach(async () => {
|
||||
[coinbase, makerAddress, takerAddress] = userAddresses;
|
||||
@@ -191,7 +188,6 @@ describe('OrderValidation', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -12,14 +12,12 @@ import {
|
||||
Token,
|
||||
TokenEvents,
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
} from '../src';
|
||||
import {BlockParamLiteral, DoneCallback} from '../src/types';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
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();
|
||||
@@ -31,7 +29,6 @@ describe('SubscriptionTest', () => {
|
||||
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(() => {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {BlockchainLifecycle} from '@0xproject/dev-utils';
|
||||
import {promisify} from '@0xproject/utils';
|
||||
import {Web3Wrapper} from '@0xproject/web3-wrapper';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as chai from 'chai';
|
||||
@@ -8,19 +7,16 @@ import * as Web3 from 'web3';
|
||||
|
||||
import {
|
||||
ApprovalContractEventArgs,
|
||||
ContractEvent,
|
||||
BlockParamLiteral,
|
||||
BlockRange,
|
||||
DecodedLogEvent,
|
||||
LogEvent,
|
||||
LogWithDecodedArgs,
|
||||
SubscriptionOpts,
|
||||
Token,
|
||||
TokenContractEventArgs,
|
||||
TokenEvents,
|
||||
TransferContractEventArgs,
|
||||
ZeroEx,
|
||||
ZeroExError,
|
||||
} from '../src';
|
||||
import {BlockParamLiteral, DoneCallback} from '../src/types';
|
||||
import {DoneCallback} from '../src/types';
|
||||
|
||||
import {chaiSetup} from './utils/chai_setup';
|
||||
import {constants} from './utils/constants';
|
||||
@@ -71,8 +67,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 +349,6 @@ describe('TokenWrapper', () => {
|
||||
});
|
||||
describe('#subscribe', () => {
|
||||
const indexFilterValues = {};
|
||||
const shouldThrowOnInsufficientBalanceOrAllowance = true;
|
||||
let tokenAddress: string;
|
||||
const transferAmount = new BigNumber(42);
|
||||
const allowanceAmount = new BigNumber(42);
|
||||
@@ -440,7 +434,7 @@ describe('TokenWrapper', () => {
|
||||
describe('#getLogsAsync', () => {
|
||||
let tokenAddress: string;
|
||||
let tokenTransferProxyAddress: string;
|
||||
const subscriptionOpts: SubscriptionOpts = {
|
||||
const blockRange: BlockRange = {
|
||||
fromBlock: 0,
|
||||
toBlock: BlockParamLiteral.Latest,
|
||||
};
|
||||
@@ -456,7 +450,7 @@ describe('TokenWrapper', () => {
|
||||
const eventName = TokenEvents.Approval;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
@@ -471,7 +465,7 @@ describe('TokenWrapper', () => {
|
||||
const differentEventName = TokenEvents.Transfer;
|
||||
const indexFilterValues = {};
|
||||
const logs = await zeroEx.token.getLogsAsync(
|
||||
tokenAddress, differentEventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, differentEventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(0);
|
||||
});
|
||||
@@ -485,7 +479,7 @@ describe('TokenWrapper', () => {
|
||||
_owner: coinbase,
|
||||
};
|
||||
const logs = await zeroEx.token.getLogsAsync<ApprovalContractEventArgs>(
|
||||
tokenAddress, eventName, subscriptionOpts, indexFilterValues,
|
||||
tokenAddress, eventName, blockRange, indexFilterValues,
|
||||
);
|
||||
expect(logs).to.have.length(1);
|
||||
const args = logs[0].args;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
export const constants = {
|
||||
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
|
||||
RPC_URL: 'http://localhost:8545',
|
||||
RPC_URL: 'http://localhost:8545/',
|
||||
ROPSTEN_NETWORK_ID: 3,
|
||||
KOVAN_NETWORK_ID: 42,
|
||||
TESTRPC_NETWORK_ID: 50,
|
||||
KOVAN_RPC_URL: 'https://kovan.infura.io',
|
||||
ROPSTEN_RPC_URL: 'https://ropsten.infura.io',
|
||||
KOVAN_RPC_URL: 'https://kovan.infura.io/',
|
||||
ROPSTEN_RPC_URL: 'https://ropsten.infura.io/',
|
||||
ZRX_DECIMALS: 18,
|
||||
GAS_ESTIMATE: 500000,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DoneCallback } from '../../src/types';
|
||||
import {DoneCallback} from '../../src/types';
|
||||
|
||||
export const reportCallbackErrors = (done: DoneCallback) => {
|
||||
return (f: (...args: any[]) => void) => {
|
||||
|
||||
@@ -17,6 +17,13 @@ export class TokenUtils {
|
||||
}
|
||||
return zrxToken;
|
||||
}
|
||||
public getWethTokenOrThrow(): Token {
|
||||
const wethToken = _.find(this.tokens, {symbol: WETH_TOKEN_SYMBOL});
|
||||
if (_.isUndefined(wethToken)) {
|
||||
throw new Error(InternalZeroExError.WethNotInTokenRegistry);
|
||||
}
|
||||
return wethToken;
|
||||
}
|
||||
public getDummyTokens(): Token[] {
|
||||
const dummyTokens = _.filter(this.tokens, token => {
|
||||
return !_.includes([PROTOCOL_TOKEN_SYMBOL, WETH_TOKEN_SYMBOL], token.symbol);
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// we are not running in a browser env.
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
(global as any).XMLHttpRequest = undefined;
|
||||
import * as Web3 from 'web3';
|
||||
import ProviderEngine = require('web3-provider-engine');
|
||||
import RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
|
||||
|
||||
@@ -12,6 +11,13 @@ import {FakeGasEstimateSubprovider} from './subproviders/fake_gas_estimate_subpr
|
||||
|
||||
import {constants} from './constants';
|
||||
|
||||
// HACK: web3 leaks XMLHttpRequest into the global scope and causes requests to hang
|
||||
// because they are using the wrong XHR package.
|
||||
// importing web3 after subproviders fixes this issue
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
// tslint:disable-next-line:ordered-imports
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export const web3Factory = {
|
||||
create(hasAddresses: boolean = true): Web3 {
|
||||
const provider = this.getRpcProvider(hasAddresses);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/abi-gen",
|
||||
"version": "0.0.2",
|
||||
"version": "0.0.3",
|
||||
"description": "Generate contract wrappers from ABI and handlebars templates",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
@@ -33,12 +33,12 @@
|
||||
"yargs": "^10.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@types/glob": "^5.0.33",
|
||||
"@types/handlebars": "^4.0.36",
|
||||
"@types/mkdirp": "^0.5.1",
|
||||
"@types/node": "^8.0.53",
|
||||
"@types/yargs": "^8.0.2",
|
||||
"@types/yargs": "^10.0.0",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"shx": "^0.2.2",
|
||||
"tslint": "5.8.0",
|
||||
|
||||
@@ -1,10 +1,54 @@
|
||||
assert
|
||||
@0xproject/assert
|
||||
------
|
||||
|
||||
Standard type and schema assertions to be used across all 0x projects and packages
|
||||
|
||||
## Install
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @0xproject/assert --save
|
||||
yarn add @0xproject/assert
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import {assert} from '@0xproject/assert';
|
||||
|
||||
assert.isValidBaseUnitAmount('baseUnitAmount', baseUnitAmount);
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/assert",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.8",
|
||||
"description": "Provides a standard way of performing type and schema validation across 0x projects",
|
||||
"main": "lib/src/index.js",
|
||||
"types": "lib/src/index.d.ts",
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/assert/README.md",
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
"@types/valid-url": "^1.0.2",
|
||||
@@ -37,8 +37,8 @@
|
||||
"typescript": "~2.6.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@0xproject/json-schemas": "^0.6.10",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/json-schemas": "^0.7.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"lodash": "^4.17.4",
|
||||
"valid-url": "^1.0.9"
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1 +1,51 @@
|
||||
@0xproject/connect
|
||||
------
|
||||
|
||||
This repository contains a Javascript library that makes it easy to interact with Relayers that conform to the [Standard Relayer API](https://github.com/0xProject/standard-relayer-api)
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
yarn add @0xproject/connect
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
* [Docs](https://0xproject.com/docs/connect)
|
||||
* [Tutorials](https://0xproject.com/wiki#connect)
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/connect",
|
||||
"version": "0.3.0",
|
||||
"version": "0.3.1",
|
||||
"description": "A javascript library for interacting with the standard relayer api",
|
||||
"keywords": [
|
||||
"connect",
|
||||
@@ -36,8 +36,8 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/connect/README.md",
|
||||
"dependencies": {
|
||||
"@0xproject/assert": "^0.0.7",
|
||||
"@0xproject/json-schemas": "^0.6.10",
|
||||
"@0xproject/assert": "^0.0.8",
|
||||
"@0xproject/json-schemas": "^0.7.0",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"lodash": "^4.17.4",
|
||||
@@ -45,7 +45,7 @@
|
||||
"websocket": "^1.0.25"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@types/fetch-mock": "^5.12.1",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as _ from 'lodash';
|
||||
import {
|
||||
OrderbookChannelMessage,
|
||||
OrderbookChannelMessageTypes,
|
||||
SignedOrder,
|
||||
} from '../types';
|
||||
|
||||
import {typeConverters} from './type_converters';
|
||||
|
||||
@@ -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): {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
|
||||
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.11;
|
||||
|
||||
import "./UnlimitedAllowanceToken.sol";
|
||||
import "./../utils/SafeMath.sol";
|
||||
|
||||
contract EtherToken is UnlimitedAllowanceToken, SafeMath {
|
||||
|
||||
string constant public name = "Ether Token";
|
||||
string constant public symbol = "WETH";
|
||||
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);
|
||||
}
|
||||
|
||||
/// @dev Sells tokens in exchange for Ether, exchanging them 1:1.
|
||||
/// @param amount Number of tokens to sell.
|
||||
function withdraw(uint amount)
|
||||
public
|
||||
{
|
||||
balances[msg.sender] = safeSub(balances[msg.sender], amount);
|
||||
totalSupply = safeSub(totalSupply, amount);
|
||||
require(msg.sender.send(amount));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
756
packages/contracts/contracts/tokens/WETH9.sol
Normal file
756
packages/contracts/contracts/tokens/WETH9.sol
Normal file
@@ -0,0 +1,756 @@
|
||||
// Copyright (C) 2015, 2016, 2017 Dapphub
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
pragma solidity ^0.4.18;
|
||||
|
||||
contract WETH9 {
|
||||
string public name = "Wrapped Ether";
|
||||
string public symbol = "WETH";
|
||||
uint8 public decimals = 18;
|
||||
|
||||
event Approval(address indexed src, address indexed guy, uint wad);
|
||||
event Transfer(address indexed src, address indexed dst, uint wad);
|
||||
event Deposit(address indexed dst, uint wad);
|
||||
event Withdrawal(address indexed src, uint wad);
|
||||
|
||||
mapping (address => uint) public balanceOf;
|
||||
mapping (address => mapping (address => uint)) public allowance;
|
||||
|
||||
function() public payable {
|
||||
deposit();
|
||||
}
|
||||
function deposit() public payable {
|
||||
balanceOf[msg.sender] += msg.value;
|
||||
Deposit(msg.sender, msg.value);
|
||||
}
|
||||
function withdraw(uint wad) public {
|
||||
require(balanceOf[msg.sender] >= wad);
|
||||
balanceOf[msg.sender] -= wad;
|
||||
msg.sender.transfer(wad);
|
||||
Withdrawal(msg.sender, wad);
|
||||
}
|
||||
|
||||
function totalSupply() public view returns (uint) {
|
||||
return this.balance;
|
||||
}
|
||||
|
||||
function approve(address guy, uint wad) public returns (bool) {
|
||||
allowance[msg.sender][guy] = wad;
|
||||
Approval(msg.sender, guy, wad);
|
||||
return true;
|
||||
}
|
||||
|
||||
function transfer(address dst, uint wad) public returns (bool) {
|
||||
return transferFrom(msg.sender, dst, wad);
|
||||
}
|
||||
|
||||
function transferFrom(address src, address dst, uint wad)
|
||||
public
|
||||
returns (bool)
|
||||
{
|
||||
require(balanceOf[src] >= wad);
|
||||
|
||||
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
|
||||
require(allowance[src][msg.sender] >= wad);
|
||||
allowance[src][msg.sender] -= wad;
|
||||
}
|
||||
|
||||
balanceOf[src] -= wad;
|
||||
balanceOf[dst] += wad;
|
||||
|
||||
Transfer(src, dst, wad);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
||||
*/
|
||||
@@ -23,12 +23,12 @@ const DEFAULT_GAS_PRICE = ((10 ** 9) * 2).toString();
|
||||
* Compiles all contracts with options passed in through CLI.
|
||||
* @param argv Instance of process.argv provided by yargs.
|
||||
*/
|
||||
async function onCompileCommand(args: CliOptions): Promise<void> {
|
||||
async function onCompileCommand(argv: CliOptions): Promise<void> {
|
||||
const opts: CompilerOptions = {
|
||||
contractsDir: args.contractsDir,
|
||||
networkId: args.networkId,
|
||||
optimizerEnabled: args.shouldOptimize ? 1 : 0,
|
||||
artifactsDir: args.artifactsDir,
|
||||
contractsDir: argv.contractsDir,
|
||||
networkId: argv.networkId,
|
||||
optimizerEnabled: argv.shouldOptimize ? 1 : 0,
|
||||
artifactsDir: argv.artifactsDir,
|
||||
};
|
||||
await commands.compileAsync(opts);
|
||||
}
|
||||
@@ -113,6 +113,7 @@ function deployCommandBuilder(yargsInstance: any) {
|
||||
}
|
||||
|
||||
(() => {
|
||||
const identityCommandBuilder = _.identity;
|
||||
return yargs
|
||||
.option('contracts-dir', {
|
||||
type: 'string',
|
||||
@@ -150,11 +151,11 @@ function deployCommandBuilder(yargsInstance: any) {
|
||||
})
|
||||
.command('compile',
|
||||
'compile contracts',
|
||||
_.noop,
|
||||
identityCommandBuilder,
|
||||
onCompileCommand)
|
||||
.command('migrate',
|
||||
'compile and deploy contracts using migration scripts',
|
||||
_.noop,
|
||||
identityCommandBuilder,
|
||||
onMigrateCommand)
|
||||
.command('deploy',
|
||||
'deploy a single contract with provided arguments',
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
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 = {
|
||||
@@ -21,7 +19,7 @@ export const migrator = {
|
||||
|
||||
const tokenTransferProxy = await deployer.deployAndSaveAsync('TokenTransferProxy');
|
||||
const zrxToken = await deployer.deployAndSaveAsync('ZRXToken');
|
||||
const etherToken = await deployer.deployAndSaveAsync('EtherToken');
|
||||
const etherToken = await deployer.deployAndSaveAsync('WETH9');
|
||||
const tokenReg = await deployer.deployAndSaveAsync('TokenRegistry');
|
||||
|
||||
const exchangeArgs = [zrxToken.address, tokenTransferProxy.address];
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {TxData} from '@0xproject/types';
|
||||
import * as Web3 from 'web3';
|
||||
import * as yargs from 'yargs';
|
||||
|
||||
export enum AbiType {
|
||||
Function = 'function',
|
||||
@@ -32,7 +33,7 @@ export interface SolcErrors {
|
||||
[key: string]: boolean;
|
||||
}
|
||||
|
||||
export interface CliOptions {
|
||||
export interface CliOptions extends yargs.Arguments {
|
||||
artifactsDir: string;
|
||||
contractsDir: string;
|
||||
jsonrpcPort: number;
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
8
packages/contracts/globals.d.ts
vendored
8
packages/contracts/globals.d.ts
vendored
@@ -1,8 +1,5 @@
|
||||
declare module 'bn.js';
|
||||
declare module 'ethereumjs-abi';
|
||||
declare module 'chai-bignumber';
|
||||
declare module 'dirty-chai';
|
||||
declare module 'yargs';
|
||||
|
||||
// HACK: In order to merge the bignumber declaration added by chai-bignumber to the chai Assertion
|
||||
// interface we must use `namespace` as the Chai definitelyTyped definition does. Since we otherwise
|
||||
@@ -31,6 +28,11 @@ declare module 'web3-eth-abi' {
|
||||
export function encodeParameters(typesArray: string[], parameters: any[]): string;
|
||||
}
|
||||
|
||||
declare module 'ethereumjs-abi' {
|
||||
const soliditySHA3: (argTypes: string[], args: any[]) => Buffer;
|
||||
const methodID: (name: string, types: string[]) => Buffer;
|
||||
}
|
||||
|
||||
// Truffle injects the following into the global scope
|
||||
declare var artifacts: any;
|
||||
declare var contract: any;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
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);
|
||||
|
||||
@@ -34,8 +33,6 @@ module.exports = (deployer: any, network: string, accounts: string[]) => {
|
||||
return deployer.deploy(TokenRegistry);
|
||||
}).then(() => {
|
||||
return deployer.deploy(EtherToken);
|
||||
}).then(() => {
|
||||
return deployer.deploy(EtherTokenV2);
|
||||
});
|
||||
} else {
|
||||
deployer.deploy([
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "contracts",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"description": "Smart contract components of 0x protocol",
|
||||
"main": "index.js",
|
||||
"directories": {
|
||||
@@ -29,14 +29,14 @@
|
||||
},
|
||||
"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",
|
||||
"@0xproject/dev-utils": "^0.0.2",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@0xproject/types": "^0.1.1",
|
||||
"@types/bluebird": "^3.5.3",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/node": "^8.0.53",
|
||||
"@types/request-promise-native": "^1.0.2",
|
||||
"@types/yargs": "^8.0.2",
|
||||
"@types/yargs": "^10.0.0",
|
||||
"chai": "^4.0.1",
|
||||
"chai-as-promised": "^7.1.0",
|
||||
"chai-as-promised-typescript-typings": "^0.0.3",
|
||||
@@ -55,10 +55,10 @@
|
||||
"yargs": "^10.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"0x.js": "~0.27.2",
|
||||
"@0xproject/json-schemas": "^0.6.10",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/web3-wrapper": "^0.1.0",
|
||||
"0x.js": "^0.28.0",
|
||||
"@0xproject/json-schemas": "^0.7.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"@0xproject/web3-wrapper": "^0.1.1",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"bluebird": "^3.5.0",
|
||||
"bn.js": "^4.11.8",
|
||||
|
||||
@@ -28,7 +28,6 @@ contract('EtherToken', (accounts: string[]) => {
|
||||
etherTokenAddress = EtherToken.address;
|
||||
zeroEx = new ZeroEx(web3.currentProvider, {
|
||||
gasPrice,
|
||||
etherTokenContractAddress: etherTokenAddress,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
});
|
||||
});
|
||||
@@ -45,7 +44,7 @@ contract('EtherToken', (accounts: string[]) => {
|
||||
const initEthBalance = await getEthBalanceAsync(account);
|
||||
const ethToDeposit = initEthBalance.plus(1);
|
||||
|
||||
return expect(zeroEx.etherToken.depositAsync(ethToDeposit, account))
|
||||
return expect(zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account))
|
||||
.to.be.rejectedWith(ZeroExError.InsufficientEthBalanceForDeposit);
|
||||
});
|
||||
|
||||
@@ -55,7 +54,7 @@ contract('EtherToken', (accounts: string[]) => {
|
||||
|
||||
const ethToDeposit = new BigNumber(web3.toWei(1, 'ether'));
|
||||
|
||||
const txHash = await zeroEx.etherToken.depositAsync(ethToDeposit, account);
|
||||
const txHash = await zeroEx.etherToken.depositAsync(etherTokenAddress, ethToDeposit, account);
|
||||
const receipt = await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
const ethSpentOnGas = gasPrice.times(receipt.gasUsed);
|
||||
@@ -72,7 +71,7 @@ contract('EtherToken', (accounts: string[]) => {
|
||||
const initEthTokenBalance = await zeroEx.token.getBalanceAsync(etherTokenAddress, account);
|
||||
const ethTokensToWithdraw = initEthTokenBalance.plus(1);
|
||||
|
||||
return expect(zeroEx.etherToken.withdrawAsync(ethTokensToWithdraw, account))
|
||||
return expect(zeroEx.etherToken.withdrawAsync(etherTokenAddress, ethTokensToWithdraw, account))
|
||||
.to.be.rejectedWith(ZeroExError.InsufficientWEthBalanceForWithdrawal);
|
||||
});
|
||||
|
||||
@@ -81,7 +80,7 @@ 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(etherTokenAddress, ethTokensToWithdraw, account, {
|
||||
gasLimit: constants.MAX_ETHERTOKEN_WITHDRAW_GAS,
|
||||
});
|
||||
const receipt = await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
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(ethToDeposit);
|
||||
});
|
||||
});
|
||||
|
||||
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 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 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(ethTokensToWithdraw);
|
||||
});
|
||||
});
|
||||
|
||||
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));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -748,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);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
|
||||
@@ -29,8 +29,8 @@ contract('ZRXToken', (accounts: string[]) => {
|
||||
exchangeContractAddress: Exchange.address,
|
||||
networkId: constants.TESTRPC_NETWORK_ID,
|
||||
});
|
||||
zrxAddress = zeroEx.exchange.getZRXTokenAddress();
|
||||
zrx = await ZRXToken.at(zrxAddress);
|
||||
zrx = await ZRXToken.new();
|
||||
zrxAddress = zrx.address;
|
||||
MAX_UINT = zeroEx.token.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
|
||||
});
|
||||
|
||||
@@ -94,15 +94,12 @@ 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,
|
||||
{gasLimit: constants.MAX_TOKEN_APPROVE_GAS});
|
||||
const 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),
|
||||
{gasLimit: constants.MAX_TOKEN_APPROVE_GAS});
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
});
|
||||
|
||||
it('should return false if spender has insufficient allowance', async () => {
|
||||
@@ -127,17 +124,17 @@ contract('ZRXToken', (accounts: string[]) => {
|
||||
const initOwnerBalance = await zeroEx.token.getBalanceAsync(zrxAddress, owner);
|
||||
const amountToTransfer = initOwnerBalance;
|
||||
const initSpenderAllowance = MAX_UINT;
|
||||
let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance);
|
||||
let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance, {
|
||||
gasLimit: constants.MAX_TOKEN_APPROVE_GAS,
|
||||
});
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer,
|
||||
{gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS});
|
||||
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);
|
||||
expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance);
|
||||
// Restore balance
|
||||
txHash = await zeroEx.token.transferAsync(zrxAddress, spender, owner, amountToTransfer);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
});
|
||||
|
||||
it('should transfer the correct balances if spender has sufficient allowance', async () => {
|
||||
@@ -147,8 +144,9 @@ 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,
|
||||
{gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS});
|
||||
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);
|
||||
@@ -161,11 +159,11 @@ contract('ZRXToken', (accounts: string[]) => {
|
||||
it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => {
|
||||
const initOwnerBalance = await zeroEx.token.getBalanceAsync(zrxAddress, owner);
|
||||
const amountToTransfer = initOwnerBalance;
|
||||
const initSpenderAllowance = initOwnerBalance;
|
||||
let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, initSpenderAllowance);
|
||||
let txHash = await zeroEx.token.setAllowanceAsync(zrxAddress, owner, spender, amountToTransfer);
|
||||
await zeroEx.awaitTransactionMinedAsync(txHash);
|
||||
txHash = await zeroEx.token.transferFromAsync(zrxAddress, owner, spender, spender, amountToTransfer,
|
||||
{gasLimit: constants.MAX_TOKEN_TRANSFERFROM_GAS});
|
||||
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);
|
||||
|
||||
@@ -8,7 +8,6 @@ export class Artifacts {
|
||||
public DummyToken: any;
|
||||
public DummyTokenV2: any;
|
||||
public EtherToken: any;
|
||||
public EtherTokenV2: any;
|
||||
public MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress: any;
|
||||
public MaliciousToken: any;
|
||||
constructor(artifacts: any) {
|
||||
@@ -20,8 +19,7 @@ export class Artifacts {
|
||||
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.EtherToken = artifacts.require('WETH9');
|
||||
this.MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress = artifacts.require(
|
||||
'MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress');
|
||||
this.MaliciousToken = artifacts.require('MaliciousToken');
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import {BigNumber} from 'bignumber.js';
|
||||
import BN = require('bn.js');
|
||||
import ABI = require('ethereumjs-abi');
|
||||
import ethUtil = require('ethereumjs-util');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/dev-utils",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.2",
|
||||
"description": "0x dev TS utils",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
@@ -19,14 +19,14 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/dev-utils/README.md",
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.0",
|
||||
"@0xproject/tslint-config": "^0.3.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"
|
||||
"types-ethereumjs-util": "0xProject/types-ethereumjs-util",
|
||||
"typescript": "~2.6.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"bignumber.js": "~4.1.0",
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as request from 'request-promise-native';
|
||||
|
||||
export class RPC {
|
||||
private url: string;
|
||||
private port: number;
|
||||
private id: number;
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# CHANGELOG
|
||||
|
||||
v0.6.7 - _Nov. 14, 2017_
|
||||
v0.7.0 - _December 20, 2017_
|
||||
------------------------
|
||||
* Rename `subscriptionOptsSchema` to `blockRangeSchema` (#272)
|
||||
|
||||
v0.6.7 - _November 14, 2017_
|
||||
------------------------
|
||||
* Re-publish JSON-schema previously published under NPM package 0x-json-schemas
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
json-schemas
|
||||
------------
|
||||
@0xproject/json-schemas
|
||||
------
|
||||
|
||||
Contains 0x-related json schemas
|
||||
|
||||
## Install:
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @0xproject/json-schemas --save
|
||||
yarn add @0xproject/json-schemas
|
||||
```
|
||||
|
||||
## Usage:
|
||||
```
|
||||
## Usage
|
||||
|
||||
```javascript
|
||||
import {SchemaValidator, ValidatorResult, schemas} from '@0xproject/json-schemas';
|
||||
|
||||
const {orderSchema} = schemas;
|
||||
@@ -22,3 +23,39 @@ const order = {
|
||||
const validatorResult: ValidatorResult = validator.validate(order, orderSchema); // Contains all errors
|
||||
const isValid: boolean = validator.isValid(order, orderSchema); // Only returns boolean
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly encourage that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/json-schemas",
|
||||
"version": "0.6.10",
|
||||
"version": "0.7.0",
|
||||
"description": "0x-related json schemas",
|
||||
"main": "lib/src/index.js",
|
||||
"types": "lib/src/index.d.ts",
|
||||
@@ -27,8 +27,8 @@
|
||||
"lodash.values": "^4.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"@types/lodash.foreach": "^4.5.3",
|
||||
"@types/lodash.values": "^4.3.3",
|
||||
"@types/mocha": "^2.2.42",
|
||||
|
||||
@@ -10,8 +10,8 @@ export const blockParamSchema = {
|
||||
],
|
||||
};
|
||||
|
||||
export const subscriptionOptsSchema = {
|
||||
id: '/SubscriptionOpts',
|
||||
export const blockRangeSchema = {
|
||||
id: '/BlockRange',
|
||||
properties: {
|
||||
fromBlock: {$ref: '/BlockParam'},
|
||||
toBlock: {$ref: '/BlockParam'},
|
||||
@@ -2,6 +2,10 @@ import {
|
||||
addressSchema,
|
||||
numberSchema,
|
||||
} from '../schemas/basic_type_schemas';
|
||||
import {
|
||||
blockParamSchema,
|
||||
blockRangeSchema,
|
||||
} from '../schemas/block_range_schema';
|
||||
import {
|
||||
ecSignatureParameterSchema,
|
||||
ecSignatureSchema,
|
||||
@@ -55,10 +59,6 @@ import {
|
||||
import {
|
||||
signedOrdersSchema,
|
||||
} from '../schemas/signed_orders_schema';
|
||||
import {
|
||||
blockParamSchema,
|
||||
subscriptionOptsSchema,
|
||||
} from '../schemas/subscription_opts_schema';
|
||||
import {
|
||||
tokenSchema,
|
||||
} from '../schemas/token_schema';
|
||||
@@ -81,7 +81,7 @@ export const schemas = {
|
||||
signedOrderSchema,
|
||||
signedOrdersSchema,
|
||||
blockParamSchema,
|
||||
subscriptionOptsSchema,
|
||||
blockRangeSchema,
|
||||
tokenSchema,
|
||||
jsNumber,
|
||||
txDataSchema,
|
||||
|
||||
@@ -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,
|
||||
@@ -25,7 +23,7 @@ const {
|
||||
signedOrderSchema,
|
||||
signedOrdersSchema,
|
||||
blockParamSchema,
|
||||
subscriptionOptsSchema,
|
||||
blockRangeSchema,
|
||||
tokenSchema,
|
||||
jsNumber,
|
||||
txDataSchema,
|
||||
@@ -172,21 +170,21 @@ describe('Schema', () => {
|
||||
validateAgainstSchema(testCases, blockParamSchema, shouldFail);
|
||||
});
|
||||
});
|
||||
describe('#subscriptionOptsSchema', () => {
|
||||
describe('#blockRangeSchema', () => {
|
||||
it('should validate valid subscription opts', () => {
|
||||
const testCases = [
|
||||
{fromBlock: 42, toBlock: 'latest'},
|
||||
{fromBlock: 42},
|
||||
{},
|
||||
];
|
||||
validateAgainstSchema(testCases, subscriptionOptsSchema);
|
||||
validateAgainstSchema(testCases, blockRangeSchema);
|
||||
});
|
||||
it('should fail for invalid subscription opts', () => {
|
||||
const testCases = [
|
||||
{fromBlock: '42'},
|
||||
];
|
||||
const shouldFail = true;
|
||||
validateAgainstSchema(testCases, subscriptionOptsSchema, shouldFail);
|
||||
validateAgainstSchema(testCases, blockRangeSchema, shouldFail);
|
||||
});
|
||||
});
|
||||
describe('#tokenSchema', () => {
|
||||
|
||||
@@ -1,22 +1,35 @@
|
||||
Test Ether Faucet
|
||||
----------------------
|
||||
@0xproject/kovan_faucets
|
||||
------
|
||||
|
||||
This faucet dispenses 0.1 test ether to one recipient per second. It has a max queue size of 1000.
|
||||
This faucet dispenses 0.1 test ether to one recipient per second and 0.1 test ZRX every 5 seconds. It has a max queue size of 1000.
|
||||
|
||||
## Installation
|
||||
|
||||
## Install
|
||||
This is a private package and therefore is not published to npm. In order to build and run this package locally, see the [Install Dependencies](#Install-Dependencies) section and onwards below.
|
||||
|
||||
Install project dependencies:
|
||||
## Contributing
|
||||
|
||||
```
|
||||
npm install
|
||||
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
## Start
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Start
|
||||
|
||||
Set the following environment variables:
|
||||
|
||||
```
|
||||
```bash
|
||||
export FAUCET_ENVIRONMENT=development
|
||||
export DISPENSER_ADDRESS=0x5409ed021d9299bf6814279a6a1411a7e866a631
|
||||
export DISPENSER_PRIVATE_KEY=f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d
|
||||
@@ -28,11 +41,11 @@ 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
|
||||
```bash
|
||||
yarn dev
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
### Endpoints
|
||||
|
||||
```GET /ether/:recipient```
|
||||
|
||||
@@ -42,15 +55,7 @@ Where recipient_address is a hex encoded Ethereum address prefixed with `0x`.
|
||||
|
||||
Where recipient_address is a hex encoded Ethereum address prefixed with `0x`.
|
||||
|
||||
|
||||
```javascript
|
||||
{
|
||||
"full": false,
|
||||
"size": 0
|
||||
}
|
||||
```
|
||||
|
||||
## Docker configs
|
||||
### Docker configs
|
||||
|
||||
```
|
||||
docker run -d \
|
||||
@@ -64,3 +69,9 @@ docker run -d \
|
||||
-e FAUCET_ENVIRONMENT=production \
|
||||
kovan-faucets
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@0xproject/kovan_faucets",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"description": "A faucet micro-service that dispenses test ERC20 tokens or Ether",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -14,8 +14,8 @@
|
||||
"author": "Fabio Berger",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"0x.js": "~0.27.2",
|
||||
"0x.js": "^0.28.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"bignumber.js": "~4.1.0",
|
||||
"body-parser": "^1.17.1",
|
||||
"ethereumjs-tx": "^1.3.3",
|
||||
@@ -26,7 +26,7 @@
|
||||
"web3-provider-engine": "^13.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@types/body-parser": "^1.16.1",
|
||||
"@types/express": "^4.0.35",
|
||||
"@types/lodash": "^4.14.86",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as express from 'express';
|
||||
import * as fs from 'fs';
|
||||
import rollbar = require('rollbar');
|
||||
|
||||
import {configs} from './configs';
|
||||
|
||||
@@ -13,7 +13,7 @@ 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
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
// tslint:disable-next-line:ordered-imports
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ 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
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
// tslint:disable-next-line:ordered-imports
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import * as express from 'express';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
export const utils = {
|
||||
consoleLog(message: string) {
|
||||
/* tslint:disable */
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {ZeroEx} from '0x.js';
|
||||
import {promisify} from '@0xproject/utils';
|
||||
import BigNumber from 'bignumber.js';
|
||||
import * as _ from 'lodash';
|
||||
|
||||
@@ -10,7 +9,7 @@ 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
|
||||
// Filed issue: https://github.com/ethereum/web3.js/issues/844
|
||||
// tslint:disable-next-line:ordered-imports
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
|
||||
51
packages/monorepo-scripts/README.md
Normal file
51
packages/monorepo-scripts/README.md
Normal file
@@ -0,0 +1,51 @@
|
||||
Mono repo scripts
|
||||
------
|
||||
|
||||
This repository contains a few helpful scripts for working with this mono repo.
|
||||
|
||||
## Usage
|
||||
|
||||
#### Dependency versions
|
||||
In order to reduce the size of this repo, we try and use the same versions of dependencies between packages. To make it easier to discover version discrepancies between packages, you can run:
|
||||
|
||||
```bash
|
||||
yarn deps_versions
|
||||
```
|
||||
|
||||
This will list out any dependencies that differ in versions between packages.
|
||||
|
||||
## Contributing
|
||||
|
||||
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
Then install dependencies
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Clean
|
||||
|
||||
```bash
|
||||
yarn clean
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/monorepo-scripts",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"description": "Helper scripts for the monorepo",
|
||||
"scripts": {
|
||||
@@ -19,7 +19,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/0xProject/0x.js/packages/monorepo-scripts/README.md",
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@types/glob": "^5.0.33",
|
||||
"@types/node": "^8.0.53",
|
||||
"shx": "^0.2.2",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# CHANGELOG
|
||||
|
||||
vx.x.x
|
||||
v0.2.0 - _December 20, 2017_
|
||||
------------------------
|
||||
* Improve the performance of address fetching (#271)
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
Subproviders
|
||||
-----------
|
||||
@0xproject/subproviders
|
||||
--------
|
||||
|
||||
A few useful subproviders.
|
||||
A few useful web3 subproviders including a LedgerSubprovider useful for adding Ledger Nano S support.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
npm install @0xproject/subproviders --save
|
||||
yarn add @0xproject/subproviders
|
||||
```
|
||||
|
||||
## Subproviders
|
||||
## Usage
|
||||
|
||||
Simply import the subprovider you are interested in using:
|
||||
|
||||
```javascript
|
||||
import {
|
||||
ledgerEthereumBrowserClientFactoryAsync as ledgerEthereumClientFactoryAsync,
|
||||
LedgerSubprovider,
|
||||
} from '@0xproject/subproviders';
|
||||
|
||||
const ledgerSubprovider = new LedgerSubprovider(
|
||||
networkId,
|
||||
ledgerEthereumClientFactoryAsync,
|
||||
);
|
||||
|
||||
const accounts = await ledgerSubprovider.getAccountsAsync();
|
||||
```
|
||||
|
||||
### Subproviders
|
||||
|
||||
#### Ledger Nano S subprovider
|
||||
|
||||
@@ -23,7 +41,50 @@ A subprovider which attempts to send an RPC call to a list of RPC endpoints sequ
|
||||
|
||||
A subprovider that relays all signing related requests to a particular provider (in our case the provider injected onto the web page), while sending all other requests to a different provider (perhaps your own backing Ethereum node or Infura).
|
||||
|
||||
### Integration tests
|
||||
## Contributing
|
||||
|
||||
We strongly recommend that the community help us make improvements and determine the future direction of the protocol. To report bugs within this package, please create an issue in this repository.
|
||||
|
||||
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
|
||||
```bash
|
||||
yarn config set workspaces-experimental true
|
||||
```
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
```
|
||||
|
||||
### Clean
|
||||
|
||||
```bash
|
||||
yarn clean
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Run tests
|
||||
|
||||
#### Unit tests
|
||||
|
||||
```bash
|
||||
yarn run test:unit
|
||||
```
|
||||
|
||||
#### Integration tests
|
||||
|
||||
In order to run the integration tests, make sure you have a Ledger Nano S available.
|
||||
|
||||
@@ -37,3 +98,9 @@ Then run:
|
||||
```
|
||||
yarn test:integration
|
||||
```
|
||||
|
||||
#### All tests
|
||||
|
||||
```bash
|
||||
yarn run test:all
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@0xproject/subproviders",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"main": "lib/src/index.js",
|
||||
"types": "lib/src/index.d.ts",
|
||||
"license": "Apache-2.0",
|
||||
@@ -17,12 +17,13 @@
|
||||
"test:integration": "run-s clean build run_mocha_integration"
|
||||
},
|
||||
"dependencies": {
|
||||
"@0xproject/assert": "^0.0.7",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/assert": "^0.0.8",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"bn.js": "^4.11.8",
|
||||
"es6-promisify": "^5.0.0",
|
||||
"ethereumjs-tx": "^1.3.3",
|
||||
"ethereumjs-util": "^5.1.1",
|
||||
"hdkey": "^0.7.1",
|
||||
"ledgerco": "0xProject/ledger-node-js-api",
|
||||
"lodash": "^4.17.4",
|
||||
"semaphore-async-await": "^1.5.1",
|
||||
@@ -30,8 +31,8 @@
|
||||
"web3-provider-engine": "^13.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@0xproject/tslint-config": "^0.2.1",
|
||||
"@0xproject/utils": "^0.1.0",
|
||||
"@0xproject/tslint-config": "^0.3.0",
|
||||
"@0xproject/utils": "^0.1.1",
|
||||
"@types/lodash": "^4.14.86",
|
||||
"@types/mocha": "^2.2.42",
|
||||
"@types/node": "^8.0.53",
|
||||
|
||||
13
packages/subproviders/src/globals.d.ts
vendored
13
packages/subproviders/src/globals.d.ts
vendored
@@ -48,7 +48,7 @@ declare module 'ledgerco' {
|
||||
public comm: comm;
|
||||
constructor(comm: comm);
|
||||
public getAddress_async(path: string, display?: boolean, chaincode?: boolean):
|
||||
Promise<{publicKey: string; address: string}>;
|
||||
Promise<{publicKey: string; address: string; chainCode: string}>;
|
||||
public signTransaction_async(path: string, rawTxHex: string): Promise<ECSignatureString>;
|
||||
public getAppConfiguration_async(): Promise<{ arbitraryDataEnabled: number; version: string }>;
|
||||
public signPersonalMessage_async(path: string, messageHex: string): Promise<ECSignature>;
|
||||
@@ -91,3 +91,14 @@ declare module 'web3-provider-engine' {
|
||||
}
|
||||
export = Web3ProviderEngine;
|
||||
}
|
||||
|
||||
// hdkey declarations
|
||||
declare module 'hdkey' {
|
||||
class HDNode {
|
||||
public publicKey: Buffer;
|
||||
public chainCode: Buffer;
|
||||
public constructor();
|
||||
public derive(path: string): HDNode;
|
||||
}
|
||||
export = HDNode;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
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 HDNode = require('hdkey');
|
||||
import * as _ from 'lodash';
|
||||
import Semaphore from 'semaphore-async-await';
|
||||
import Web3 = require('web3');
|
||||
@@ -22,8 +21,7 @@ import {Subprovider} from './subprovider';
|
||||
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;
|
||||
const SHOULD_GET_CHAIN_CODE = true;
|
||||
|
||||
export class LedgerSubprovider extends Subprovider {
|
||||
private _nonceLock: Semaphore;
|
||||
@@ -34,18 +32,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);
|
||||
@@ -142,21 +128,30 @@ export class LedgerSubprovider extends Subprovider {
|
||||
public async getAccountsAsync(): Promise<string[]> {
|
||||
this._ledgerClientIfExists = await this.createLedgerClientAsync();
|
||||
|
||||
// TODO: replace with generating addresses without hitting Ledger
|
||||
let ledgerResponse;
|
||||
try {
|
||||
ledgerResponse = await this._ledgerClientIfExists.getAddress_async(
|
||||
this._derivationPath, this._shouldAlwaysAskForConfirmation, SHOULD_GET_CHAIN_CODE,
|
||||
);
|
||||
} finally {
|
||||
await this.destoryLedgerClientAsync();
|
||||
}
|
||||
|
||||
const hdKey = new HDNode();
|
||||
hdKey.publicKey = new Buffer(ledgerResponse.publicKey, 'hex');
|
||||
hdKey.chainCode = new Buffer(ledgerResponse.chainCode, 'hex');
|
||||
|
||||
const accounts = [];
|
||||
for (let i = 0; i < NUM_ADDRESSES_TO_FETCH; i++) {
|
||||
try {
|
||||
const derivationPath = `${this._derivationPath}/${i + this._derivationPathIndex}`;
|
||||
const result = await this._ledgerClientIfExists.getAddress_async(
|
||||
derivationPath, this._shouldAlwaysAskForConfirmation, SHOULD_GET_CHAIN_CODE,
|
||||
);
|
||||
accounts.push(result.address.toLowerCase());
|
||||
} catch (err) {
|
||||
await this.destoryLedgerClientAsync();
|
||||
throw err;
|
||||
}
|
||||
const derivedHDNode = hdKey.derive(`m/${i + this._derivationPathIndex}`);
|
||||
const derivedPublicKey = derivedHDNode.publicKey;
|
||||
const shouldSanitizePublicKey = true;
|
||||
const ethereumAddressUnprefixed = ethUtil.publicToAddress(
|
||||
derivedPublicKey, shouldSanitizePublicKey,
|
||||
).toString('hex');
|
||||
const ethereumAddressPrefixed = ethUtil.addHexPrefix(ethereumAddressUnprefixed);
|
||||
accounts.push(ethereumAddressPrefixed.toLowerCase());
|
||||
}
|
||||
await this.destoryLedgerClientAsync();
|
||||
return accounts;
|
||||
}
|
||||
public async signTransactionAsync(txParams: PartialTxParams): Promise<string> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as _ from 'lodash';
|
||||
import * as Web3 from 'web3';
|
||||
|
||||
export interface LedgerCommunicationClient {
|
||||
close_async: () => Promise<void>;
|
||||
@@ -11,8 +10,10 @@ export interface LedgerCommunicationClient {
|
||||
* NodeJs and Browser communication are supported.
|
||||
*/
|
||||
export interface LedgerEthereumClient {
|
||||
// shouldGetChainCode is defined as `true` instead of `boolean` because other types rely on the assumption
|
||||
// that we get back the chain code and we don't have dependent types to express it properly
|
||||
getAddress_async: (derivationPath: string, askForDeviceConfirmation: boolean,
|
||||
shouldGetChainCode: boolean) => Promise<LedgerGetAddressResult>;
|
||||
shouldGetChainCode: true) => Promise<LedgerGetAddressResult>;
|
||||
signPersonalMessage_async: (derivationPath: string, messageHex: string) => Promise<ECSignature>;
|
||||
signTransaction_async: (derivationPath: string, txHex: string) => Promise<ECSignatureString>;
|
||||
comm: LedgerCommunicationClient;
|
||||
@@ -64,6 +65,8 @@ export interface SignatureData {
|
||||
|
||||
export interface LedgerGetAddressResult {
|
||||
address: string;
|
||||
publicKey: string;
|
||||
chainCode: string;
|
||||
}
|
||||
|
||||
export interface LedgerWalletSubprovider {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
@@ -21,7 +18,7 @@ import {reportCallbackErrors} from '../utils/report_callback_errors';
|
||||
|
||||
chaiSetup.configure();
|
||||
const expect = chai.expect;
|
||||
const FAKE_ADDRESS = '0x9901c66f2d4b95f7074b553da78084d708beca70';
|
||||
const FAKE_ADDRESS = '0xb088a3bc93f71b4de97b9de773e9647645983688';
|
||||
|
||||
describe('LedgerSubprovider', () => {
|
||||
const networkId: number = 42;
|
||||
@@ -31,8 +28,14 @@ describe('LedgerSubprovider', () => {
|
||||
// tslint:disable:no-object-literal-type-assertion
|
||||
const ledgerEthClient = {
|
||||
getAddress_async: async () => {
|
||||
// tslint:disable-next-line:max-line-length
|
||||
const publicKey = '04f428290f4c5ed6a198f71b8205f488141dbb3f0840c923bbfa798ecbee6370986c03b5575d94d506772fb48a6a44e345e4ebd4f028a6f609c44b655d6d3e71a1';
|
||||
const chainCode = 'ac055a5537c0c7e9e02d14a197cad6b857836da2a12043b46912a37d959b5ae8';
|
||||
const address = '0xBa388BA5e5EEF2c6cE42d831c2B3A28D3c99bdB1';
|
||||
return {
|
||||
address: FAKE_ADDRESS,
|
||||
publicKey,
|
||||
address,
|
||||
chainCode,
|
||||
};
|
||||
},
|
||||
signPersonalMessage_async: async () => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user