aboutsummaryrefslogtreecommitdiffstats
path: root/packages/order-watcher
diff options
context:
space:
mode:
Diffstat (limited to 'packages/order-watcher')
-rw-r--r--packages/order-watcher/CHANGELOG.json55
-rw-r--r--packages/order-watcher/CHANGELOG.md16
-rw-r--r--packages/order-watcher/Dockerfile13
-rw-r--r--packages/order-watcher/README.md88
-rw-r--r--packages/order-watcher/package.json40
-rw-r--r--packages/order-watcher/src/index.ts2
-rw-r--r--packages/order-watcher/src/order_watcher/dependent_order_hashes_tracker.ts62
-rw-r--r--packages/order-watcher/src/order_watcher/order_watcher.ts93
-rw-r--r--packages/order-watcher/src/order_watcher/order_watcher_web_socket_server.ts200
-rw-r--r--packages/order-watcher/src/server.ts44
-rw-r--r--packages/order-watcher/src/types.ts66
-rw-r--r--packages/order-watcher/test/order_watcher_test.ts208
-rw-r--r--packages/order-watcher/test/order_watcher_web_socket_server_test.ts312
13 files changed, 1123 insertions, 76 deletions
diff --git a/packages/order-watcher/CHANGELOG.json b/packages/order-watcher/CHANGELOG.json
index b4d7a1501..4cfecd034 100644
--- a/packages/order-watcher/CHANGELOG.json
+++ b/packages/order-watcher/CHANGELOG.json
@@ -1,5 +1,60 @@
[
{
+ "version": "2.4.0",
+ "changes": [
+ {
+ "note": "Add support for `MultiAssetProxy`",
+ "pr": 1363
+ }
+ ]
+ },
+ {
+ "version": "2.3.0",
+ "changes": [
+ {
+ "note":
+ "Added a WebSocket interface to OrderWatcher so that it can be used by a client written in any language",
+ "pr": 1427
+ }
+ ]
+ },
+ {
+ "version": "2.2.8",
+ "changes": [
+ {
+ "note": "Dependencies updated"
+ }
+ ],
+ "timestamp": 1544739608
+ },
+ {
+ "version": "2.2.7",
+ "changes": [
+ {
+ "note": "Dependencies updated"
+ }
+ ],
+ "timestamp": 1544570656
+ },
+ {
+ "timestamp": 1543401373,
+ "version": "2.2.6",
+ "changes": [
+ {
+ "note": "Dependencies updated"
+ }
+ ]
+ },
+ {
+ "timestamp": 1542821676,
+ "version": "2.2.5",
+ "changes": [
+ {
+ "note": "Dependencies updated"
+ }
+ ]
+ },
+ {
"version": "2.2.4",
"changes": [
{
diff --git a/packages/order-watcher/CHANGELOG.md b/packages/order-watcher/CHANGELOG.md
index c7003f759..4e49b4637 100644
--- a/packages/order-watcher/CHANGELOG.md
+++ b/packages/order-watcher/CHANGELOG.md
@@ -5,6 +5,22 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
+## v2.2.8 - _December 13, 2018_
+
+ * Dependencies updated
+
+## v2.2.7 - _December 11, 2018_
+
+ * Dependencies updated
+
+## v2.2.6 - _November 28, 2018_
+
+ * Dependencies updated
+
+## v2.2.5 - _November 21, 2018_
+
+ * Dependencies updated
+
## v2.2.4 - _November 14, 2018_
* Fix the bug when order watcher was throwing an error on order removal when maker token was ZRX (#1259)
diff --git a/packages/order-watcher/Dockerfile b/packages/order-watcher/Dockerfile
new file mode 100644
index 000000000..3ffa1b72f
--- /dev/null
+++ b/packages/order-watcher/Dockerfile
@@ -0,0 +1,13 @@
+FROM node
+
+WORKDIR /order-watcher
+
+COPY package.json .
+RUN npm i
+RUN npm install forever -g
+
+COPY . .
+
+EXPOSE 8080
+
+CMD ["forever", "./lib/src/server.js"]
diff --git a/packages/order-watcher/README.md b/packages/order-watcher/README.md
index c0b99b272..385fe4715 100644
--- a/packages/order-watcher/README.md
+++ b/packages/order-watcher/README.md
@@ -4,6 +4,9 @@ An order watcher daemon that watches for order validity.
#### Read the wiki [article](https://0xproject.com/wiki#0x-OrderWatcher).
+OrderWatcher also comes with a WebSocket server to provide language-agnostic access
+to order watching functionality. We used the [WebSocket Client and Server Implementation for Node](https://www.npmjs.com/package/websocket). The server sends and receives messages that conform to the [JSON RPC specifications](https://www.jsonrpc.org/specification).
+
## Installation
**Install**
@@ -26,6 +29,91 @@ If your project is in [TypeScript](https://www.typescriptlang.org/), add the fol
}
```
+## Using the WebSocket Server
+
+**Setup**
+
+**Environmental Variables**
+Several environmental variables can be set to configure the server:
+
+* `ORDER_WATCHER_HTTP_PORT` specifies the port that the http server will listen on
+ and accept connections from. When this is not set, we default to 8080.
+
+**Requests**
+The server accepts three types of requests: `ADD_ORDER`, `REMOVE_ORDER` and `GET_STATS`. These mirror what the underlying OrderWatcher does. You can read more in the [wiki](https://0xproject.com/wiki#0x-OrderWatcher). Unlike the OrderWatcher, it does not expose any `subscribe` or `unsubscribe` functionality because the WebSocket server keeps a single subscription open for all clients.
+
+The first step for making a request is establishing a connection with the server. In Javascript:
+
+```
+var W3CWebSocket = require('websocket').w3cwebsocket;
+wsClient = new W3CWebSocket('ws://127.0.0.1:8080');
+```
+
+In Python, you could use the [websocket-client library](http://pypi.python.org/pypi/websocket-client/) and run:
+
+```
+from websocket import create_connection
+wsClient = create_connection("ws://127.0.0.1:8080")
+```
+
+With the connection established, you prepare the payload for your request. The payload is a json object with a format established by the [JSON RPC specification](https://www.jsonrpc.org/specification):
+
+* `id`: All requests require you to specify a numerical `id`. When the server responds to the request, the response will have the same `id` as the one supplied with your request.
+* `jsonrpc`: This is always the string `'2.0'`.
+* `method`: This specifies the OrderWatcher method you want to call. I.e., `'ADD_ORDER'`, `'REMOVE_ORDER'` or `'GET_STATS'`.
+* `params`: These contain the parameters needed by OrderWatcher to execute the method you called. For `ADD_ORDER`, provide `{ signedOrder: <your signedOrder> }`. For `REMOVE_ORDER`, provide `{ orderHash: <your orderHash> }`. For `GET_STATS`, no parameters are needed, so you may leave this empty.
+
+Next, convert the payload to a string and send it through the connection.
+In Javascript:
+
+```
+const addOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'ADD_ORDER',
+ params: { signedOrder: <your signedOrder> },
+};
+wsClient.send(JSON.stringify(addOrderPayload));
+```
+
+In Python:
+
+```
+import json
+remove_order_payload = {
+ 'id': 1,
+ 'jsonrpc': '2.0',
+ 'method': 'REMOVE_ORDER',
+ 'params': {'orderHash': '0x6edc16bf37fde79f5012088c33784c730e2f103d9ab1caf73060c386ad107b7e'},
+}
+wsClient.send(json.dumps(remove_order_payload));
+```
+
+**Response**
+The server responds to all requests in a similar format. In the data field, you'll find another object containing the following fields:
+
+* `id`: The id corresponding to the request that the server is responding to. `UPDATE` responses are not based on any requests so the `id` field is omitted`.
+* `jsonrpc`: Always `'2.0'`.
+* `method`: The method the server is responding to. Eg. `ADD_ORDER`. When order states change the server may also initiate a response. In this case, method will be listed as `UPDATE`.
+* `result`: This field varies based on the method. `UPDATE` responses contain the new order state. `GET_STATS` responses contain the current order count. When there are errors, this field is omitted.
+* `error`: When there is an error executing a request, the [JSON RPC](https://www.jsonrpc.org/specification) error object is listed here. When the server responds successfully, this field is omitted.
+
+In Javascript, the responses can be parsed using the `onmessage` callback:
+
+```
+wsClient.onmessage = (msg) => {
+ const responseData = JSON.parse(msg.data);
+ const method = responseData.method
+};
+```
+
+In Python, `recv` is a lightweight way to receive a response:
+
+```
+result = wsClient.recv()
+method = result.method
+```
+
## 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.
diff --git a/packages/order-watcher/package.json b/packages/order-watcher/package.json
index af88a120e..c4a56c982 100644
--- a/packages/order-watcher/package.json
+++ b/packages/order-watcher/package.json
@@ -1,6 +1,6 @@
{
"name": "@0x/order-watcher",
- "version": "2.2.4",
+ "version": "2.2.8",
"description": "An order watcher daemon that watches for order validity",
"keywords": [
"0x",
@@ -33,9 +33,10 @@
"node": ">=6.0.0"
},
"devDependencies": {
- "@0x/dev-utils": "^1.0.17",
- "@0x/migrations": "^2.0.4",
- "@0x/tslint-config": "^1.0.10",
+ "@0x/dev-utils": "^1.0.21",
+ "@0x/migrations": "^2.2.2",
+ "@0x/tslint-config": "^2.0.0",
+ "@0x/subproviders": "^2.1.8",
"@types/bintrees": "^1.0.2",
"@types/lodash": "4.14.104",
"@types/mocha": "^2.2.42",
@@ -57,24 +58,25 @@
"typescript": "3.0.1"
},
"dependencies": {
- "@0x/abi-gen-wrappers": "^1.0.5",
- "@0x/assert": "^1.0.17",
- "@0x/base-contract": "^3.0.6",
- "@0x/contract-addresses": "^1.1.0",
- "@0x/contract-artifacts": "^1.1.0",
- "@0x/contract-wrappers": "^4.0.2",
- "@0x/fill-scenarios": "^1.0.12",
- "@0x/json-schemas": "^2.1.1",
- "@0x/order-utils": "^3.0.2",
- "@0x/types": "^1.2.1",
- "@0x/typescript-typings": "^3.0.4",
- "@0x/utils": "^2.0.5",
- "@0x/web3-wrapper": "^3.1.4",
+ "@0x/abi-gen-wrappers": "^2.0.2",
+ "@0x/assert": "^1.0.20",
+ "@0x/base-contract": "^3.0.10",
+ "@0x/contract-addresses": "^2.0.0",
+ "@0x/contract-artifacts": "^1.1.2",
+ "@0x/contract-wrappers": "^4.1.3",
+ "@0x/fill-scenarios": "^1.0.16",
+ "@0x/json-schemas": "^2.1.4",
+ "@0x/order-utils": "^3.0.7",
+ "@0x/types": "^1.4.1",
+ "@0x/typescript-typings": "^3.0.6",
+ "@0x/utils": "^2.0.8",
+ "@0x/web3-wrapper": "^3.2.1",
"bintrees": "^1.0.2",
- "ethereum-types": "^1.1.2",
+ "ethereum-types": "^1.1.4",
"ethereumjs-blockstream": "6.0.0",
"ethers": "~4.0.4",
- "lodash": "^4.17.5"
+ "lodash": "^4.17.5",
+ "websocket": "^1.0.25"
},
"publishConfig": {
"access": "public"
diff --git a/packages/order-watcher/src/index.ts b/packages/order-watcher/src/index.ts
index 5eeba3e87..1f4e5eff1 100644
--- a/packages/order-watcher/src/index.ts
+++ b/packages/order-watcher/src/index.ts
@@ -1,4 +1,5 @@
export { OrderWatcher } from './order_watcher/order_watcher';
+export { OrderWatcherWebSocketServer } from './order_watcher/order_watcher_web_socket_server';
export { ExpirationWatcher } from './order_watcher/expiration_watcher';
export {
@@ -6,6 +7,7 @@ export {
OrderStateInvalid,
OrderState,
ExchangeContractErrs,
+ ObjectMap,
OrderRelevantState,
Stats,
} from '@0x/types';
diff --git a/packages/order-watcher/src/order_watcher/dependent_order_hashes_tracker.ts b/packages/order-watcher/src/order_watcher/dependent_order_hashes_tracker.ts
index a956a94db..d1085014c 100644
--- a/packages/order-watcher/src/order_watcher/dependent_order_hashes_tracker.ts
+++ b/packages/order-watcher/src/order_watcher/dependent_order_hashes_tracker.ts
@@ -1,6 +1,5 @@
-// tslint:disable:no-unnecessary-type-assertion
import { assetDataUtils, orderHashUtils } from '@0x/order-utils';
-import { AssetProxyId, ERC20AssetData, ERC721AssetData, SignedOrder } from '@0x/types';
+import { AssetProxyId, SignedOrder } from '@0x/types';
import { BigNumber } from '@0x/utils';
import * as _ from 'lodash';
@@ -62,35 +61,18 @@ export class DependentOrderHashesTracker {
return dependentOrderHashes;
}
public addToDependentOrderHashes(signedOrder: SignedOrder): void {
- const decodedMakerAssetData = assetDataUtils.decodeAssetDataOrThrow(signedOrder.makerAssetData);
- if (decodedMakerAssetData.assetProxyId === AssetProxyId.ERC20) {
- this._addToERC20DependentOrderHashes(signedOrder, (decodedMakerAssetData as ERC20AssetData).tokenAddress);
- } else {
- this._addToERC721DependentOrderHashes(
- signedOrder,
- (decodedMakerAssetData as ERC721AssetData).tokenAddress,
- (decodedMakerAssetData as ERC721AssetData).tokenId,
- );
- }
+ this._addAssetDataToDependentOrderHashes(signedOrder, signedOrder.makerAssetData);
this._addToERC20DependentOrderHashes(signedOrder, this._zrxTokenAddress);
this._addToMakerDependentOrderHashes(signedOrder);
}
public removeFromDependentOrderHashes(signedOrder: SignedOrder): void {
- const decodedMakerAssetData = assetDataUtils.decodeAssetDataOrThrow(signedOrder.makerAssetData);
- if (decodedMakerAssetData.assetProxyId === AssetProxyId.ERC20) {
- this._removeFromERC20DependentOrderhashes(
- signedOrder,
- (decodedMakerAssetData as ERC20AssetData).tokenAddress,
- );
- } else {
- this._removeFromERC721DependentOrderhashes(
- signedOrder,
- (decodedMakerAssetData as ERC721AssetData).tokenAddress,
- (decodedMakerAssetData as ERC721AssetData).tokenId,
- );
- }
+ this._removeAssetDataFromDependentOrderHashes(signedOrder, signedOrder.makerAssetData);
// If makerToken === ZRX then we already removed it and we don't need to remove it again.
- if ((decodedMakerAssetData as ERC20AssetData).tokenAddress !== this._zrxTokenAddress) {
+ const decodedMakerAssetData = assetDataUtils.decodeAssetDataOrThrow(signedOrder.makerAssetData);
+ if (
+ assetDataUtils.isERC20AssetData(decodedMakerAssetData) &&
+ decodedMakerAssetData.tokenAddress !== this._zrxTokenAddress
+ ) {
this._removeFromERC20DependentOrderhashes(signedOrder, this._zrxTokenAddress);
}
this._removeFromMakerDependentOrderhashes(signedOrder);
@@ -167,6 +149,18 @@ export class DependentOrderHashesTracker {
tokenId.toString()
].add(orderHash);
}
+ private _addAssetDataToDependentOrderHashes(signedOrder: SignedOrder, assetData: string): void {
+ const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData);
+ if (assetDataUtils.isERC20AssetData(decodedAssetData)) {
+ this._addToERC20DependentOrderHashes(signedOrder, decodedAssetData.tokenAddress);
+ } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) {
+ this._addToERC721DependentOrderHashes(signedOrder, decodedAssetData.tokenAddress, decodedAssetData.tokenId);
+ } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) {
+ _.each(decodedAssetData.nestedAssetData, nestedAssetDataElement =>
+ this._addAssetDataToDependentOrderHashes(signedOrder, nestedAssetDataElement),
+ );
+ }
+ }
private _addToMakerDependentOrderHashes(signedOrder: SignedOrder): void {
const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
if (_.isUndefined(this._orderHashesByMakerAddress[signedOrder.makerAddress])) {
@@ -230,4 +224,20 @@ export class DependentOrderHashesTracker {
delete this._orderHashesByMakerAddress[signedOrder.makerAddress];
}
}
+ private _removeAssetDataFromDependentOrderHashes(signedOrder: SignedOrder, assetData: string): void {
+ const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData);
+ if (assetDataUtils.isERC20AssetData(decodedAssetData)) {
+ this._removeFromERC20DependentOrderhashes(signedOrder, decodedAssetData.tokenAddress);
+ } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) {
+ this._removeFromERC721DependentOrderhashes(
+ signedOrder,
+ decodedAssetData.tokenAddress,
+ decodedAssetData.tokenId,
+ );
+ } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) {
+ _.each(decodedAssetData.nestedAssetData, nestedAssetDataElement =>
+ this._removeAssetDataFromDependentOrderHashes(signedOrder, nestedAssetDataElement),
+ );
+ }
+ }
}
diff --git a/packages/order-watcher/src/order_watcher/order_watcher.ts b/packages/order-watcher/src/order_watcher/order_watcher.ts
index 96c5ca7b4..a06fd0cfe 100644
--- a/packages/order-watcher/src/order_watcher/order_watcher.ts
+++ b/packages/order-watcher/src/order_watcher/order_watcher.ts
@@ -161,14 +161,7 @@ export class OrderWatcher {
this._dependentOrderHashesTracker.addToDependentOrderHashes(signedOrder);
const orderAssetDatas = [signedOrder.makerAssetData, signedOrder.takerAssetData];
- _.each(orderAssetDatas, assetData => {
- const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData);
- if (decodedAssetData.assetProxyId === AssetProxyId.ERC20) {
- this._collisionResistantAbiDecoder.addERC20Token(decodedAssetData.tokenAddress);
- } else if (decodedAssetData.assetProxyId === AssetProxyId.ERC721) {
- this._collisionResistantAbiDecoder.addERC721Token(decodedAssetData.tokenAddress);
- }
- });
+ _.each(orderAssetDatas, assetData => this._addAssetDataToAbiDecoder(assetData));
}
/**
* Removes an order from the orderWatcher
@@ -236,31 +229,71 @@ export class OrderWatcher {
await this._emitRevalidateOrdersAsync([orderHash]);
}
}
+ private _addAssetDataToAbiDecoder(assetData: string): void {
+ const decodedAssetData = assetDataUtils.decodeAssetDataOrThrow(assetData);
+ if (assetDataUtils.isERC20AssetData(decodedAssetData)) {
+ this._collisionResistantAbiDecoder.addERC20Token(decodedAssetData.tokenAddress);
+ } else if (assetDataUtils.isERC721AssetData(decodedAssetData)) {
+ this._collisionResistantAbiDecoder.addERC721Token(decodedAssetData.tokenAddress);
+ } else if (assetDataUtils.isMultiAssetData(decodedAssetData)) {
+ _.each(decodedAssetData.nestedAssetData, nestedAssetDataElement =>
+ this._addAssetDataToAbiDecoder(nestedAssetDataElement),
+ );
+ }
+ }
+ private _deleteLazyStoreBalance(assetData: string, userAddress: string): void {
+ const assetProxyId = assetDataUtils.decodeAssetProxyId(assetData);
+ switch (assetProxyId) {
+ case AssetProxyId.ERC20:
+ case AssetProxyId.ERC721:
+ this._balanceAndProxyAllowanceLazyStore.deleteBalance(assetData, userAddress);
+ break;
+ case AssetProxyId.MultiAsset:
+ const decodedAssetData = assetDataUtils.decodeMultiAssetData(assetData);
+ _.each(decodedAssetData.nestedAssetData, nestedAssetDataElement =>
+ this._deleteLazyStoreBalance(nestedAssetDataElement, userAddress),
+ );
+ break;
+ default:
+ break;
+ }
+ }
+ private _deleteLazyStoreProxyAllowance(assetData: string, userAddress: string): void {
+ const assetProxyId = assetDataUtils.decodeAssetProxyId(assetData);
+ switch (assetProxyId) {
+ case AssetProxyId.ERC20:
+ case AssetProxyId.ERC721:
+ this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(assetData, userAddress);
+ break;
+ case AssetProxyId.MultiAsset:
+ const decodedAssetData = assetDataUtils.decodeMultiAssetData(assetData);
+ _.each(decodedAssetData.nestedAssetData, nestedAssetDataElement =>
+ this._deleteLazyStoreProxyAllowance(nestedAssetDataElement, userAddress),
+ );
+ break;
+ default:
+ break;
+ }
+ }
private _cleanupOrderRelatedState(orderHash: string): void {
const signedOrder = this._orderByOrderHash[orderHash];
this._orderFilledCancelledLazyStore.deleteFilledTakerAmount(orderHash);
this._orderFilledCancelledLazyStore.deleteIsCancelled(orderHash);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.makerAssetData, signedOrder.makerAddress);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(
- signedOrder.makerAssetData,
- signedOrder.makerAddress,
- );
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(signedOrder.takerAssetData, signedOrder.takerAddress);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(
- signedOrder.takerAssetData,
- signedOrder.takerAddress,
- );
+ this._deleteLazyStoreBalance(signedOrder.makerAssetData, signedOrder.makerAddress);
+ this._deleteLazyStoreProxyAllowance(signedOrder.makerAssetData, signedOrder.makerAddress);
+ this._deleteLazyStoreBalance(signedOrder.takerAssetData, signedOrder.takerAddress);
+ this._deleteLazyStoreProxyAllowance(signedOrder.takerAssetData, signedOrder.takerAddress);
const zrxAssetData = this._orderFilledCancelledLazyStore.getZRXAssetData();
if (!signedOrder.makerFee.isZero()) {
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxAssetData, signedOrder.makerAddress);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxAssetData, signedOrder.makerAddress);
+ this._deleteLazyStoreBalance(zrxAssetData, signedOrder.makerAddress);
+ this._deleteLazyStoreProxyAllowance(zrxAssetData, signedOrder.makerAddress);
}
if (!signedOrder.takerFee.isZero()) {
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(zrxAssetData, signedOrder.takerAddress);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(zrxAssetData, signedOrder.takerAddress);
+ this._deleteLazyStoreBalance(zrxAssetData, signedOrder.takerAddress);
+ this._deleteLazyStoreProxyAllowance(zrxAssetData, signedOrder.takerAddress);
}
}
private _onOrderExpired(orderHash: string): void {
@@ -302,7 +335,7 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as ERC20TokenApprovalEventArgs;
const tokenAssetData = assetDataUtils.encodeERC20AssetData(decodedLog.address);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(tokenAssetData, args._owner);
+ this._deleteLazyStoreProxyAllowance(tokenAssetData, args._owner);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._owner,
@@ -315,7 +348,7 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as ERC721TokenApprovalEventArgs;
const tokenAssetData = assetDataUtils.encodeERC721AssetData(decodedLog.address, args._tokenId);
- this._balanceAndProxyAllowanceLazyStore.deleteProxyAllowance(tokenAssetData, args._owner);
+ this._deleteLazyStoreProxyAllowance(tokenAssetData, args._owner);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._owner,
@@ -333,8 +366,8 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as ERC20TokenTransferEventArgs;
const tokenAssetData = assetDataUtils.encodeERC20AssetData(decodedLog.address);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._from);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._to);
+ this._deleteLazyStoreBalance(tokenAssetData, args._from);
+ this._deleteLazyStoreBalance(tokenAssetData, args._to);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._from,
@@ -347,8 +380,8 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as ERC721TokenTransferEventArgs;
const tokenAssetData = assetDataUtils.encodeERC721AssetData(decodedLog.address, args._tokenId);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._from);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._to);
+ this._deleteLazyStoreBalance(tokenAssetData, args._from);
+ this._deleteLazyStoreBalance(tokenAssetData, args._to);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._from,
@@ -375,7 +408,7 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as WETH9DepositEventArgs;
const tokenAssetData = assetDataUtils.encodeERC20AssetData(decodedLog.address);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._owner);
+ this._deleteLazyStoreBalance(tokenAssetData, args._owner);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._owner,
@@ -388,7 +421,7 @@ export class OrderWatcher {
// Invalidate cache
const args = decodedLog.args as WETH9WithdrawalEventArgs;
const tokenAssetData = assetDataUtils.encodeERC20AssetData(decodedLog.address);
- this._balanceAndProxyAllowanceLazyStore.deleteBalance(tokenAssetData, args._owner);
+ this._deleteLazyStoreBalance(tokenAssetData, args._owner);
// Revalidate orders
const orderHashes = this._dependentOrderHashesTracker.getDependentOrderHashesByAssetDataByMaker(
args._owner,
diff --git a/packages/order-watcher/src/order_watcher/order_watcher_web_socket_server.ts b/packages/order-watcher/src/order_watcher/order_watcher_web_socket_server.ts
new file mode 100644
index 000000000..b75b07603
--- /dev/null
+++ b/packages/order-watcher/src/order_watcher/order_watcher_web_socket_server.ts
@@ -0,0 +1,200 @@
+import { ContractAddresses } from '@0x/contract-addresses';
+import { schemas } from '@0x/json-schemas';
+import { OrderStateInvalid, OrderStateValid, SignedOrder } from '@0x/types';
+import { BigNumber, logUtils } from '@0x/utils';
+import { Provider } from 'ethereum-types';
+import * as http from 'http';
+import * as WebSocket from 'websocket';
+
+import { GetStatsResult, OrderWatcherConfig, OrderWatcherMethod, WebSocketRequest, WebSocketResponse } from '../types';
+import { assert } from '../utils/assert';
+
+import { OrderWatcher } from './order_watcher';
+
+const DEFAULT_HTTP_PORT = 8080;
+const JSON_RPC_VERSION = '2.0';
+
+// Wraps the OrderWatcher functionality in a WebSocket server. Motivations:
+// 1) Users can watch orders via non-typescript programs.
+// 2) Better encapsulation so that users can work
+export class OrderWatcherWebSocketServer {
+ private readonly _orderWatcher: OrderWatcher;
+ private readonly _httpServer: http.Server;
+ private readonly _connectionStore: Set<WebSocket.connection>;
+ private readonly _wsServer: WebSocket.server;
+ private readonly _isVerbose: boolean;
+ /**
+ * Recover types lost when the payload is stringified.
+ */
+ private static _parseSignedOrder(rawRequest: any): SignedOrder {
+ const bigNumberFields = [
+ 'salt',
+ 'makerFee',
+ 'takerFee',
+ 'makerAssetAmount',
+ 'takerAssetAmount',
+ 'expirationTimeSeconds',
+ ];
+ for (const field of bigNumberFields) {
+ rawRequest[field] = new BigNumber(rawRequest[field]);
+ }
+ return rawRequest;
+ }
+
+ /**
+ * Instantiate a new WebSocket server which provides OrderWatcher functionality
+ * @param provider Web3 provider to use for JSON RPC calls.
+ * @param networkId NetworkId to watch orders on.
+ * @param contractAddresses Optional contract addresses. Defaults to known
+ * addresses based on networkId.
+ * @param orderWatcherConfig OrderWatcher configurations. isVerbose sets the verbosity for the WebSocket server aswell.
+ * @param isVerbose Whether to enable verbose logging. Defaults to true.
+ */
+ constructor(
+ provider: Provider,
+ networkId: number,
+ contractAddresses?: ContractAddresses,
+ orderWatcherConfig?: Partial<OrderWatcherConfig>,
+ ) {
+ this._isVerbose =
+ orderWatcherConfig !== undefined && orderWatcherConfig.isVerbose !== undefined
+ ? orderWatcherConfig.isVerbose
+ : true;
+ this._orderWatcher = new OrderWatcher(provider, networkId, contractAddresses, orderWatcherConfig);
+ this._connectionStore = new Set();
+ this._httpServer = http.createServer();
+ this._wsServer = new WebSocket.server({
+ httpServer: this._httpServer,
+ // Avoid setting autoAcceptConnections to true as it defeats all
+ // standard cross-origin protection facilities built into the protocol
+ // and the browser.
+ // Source: https://www.npmjs.com/package/websocket#server-example
+ // Also ensures that a request event is emitted by
+ // the server whenever a new WebSocket request is made.
+ autoAcceptConnections: false,
+ });
+
+ this._wsServer.on('request', async (request: any) => {
+ // Designed for usage pattern where client and server are run on the same
+ // machine by the same user. As such, no security checks are in place.
+ const connection: WebSocket.connection = request.accept(null, request.origin);
+ this._log(`${new Date()} [Server] Accepted connection from origin ${request.origin}.`);
+ connection.on('message', this._onMessageCallbackAsync.bind(this, connection));
+ connection.on('close', this._onCloseCallback.bind(this, connection));
+ this._connectionStore.add(connection);
+ });
+ }
+
+ /**
+ * Activates the WebSocket server by subscribing to the OrderWatcher and
+ * starting the WebSocket's HTTP server
+ */
+ public start(): void {
+ // Have the WebSocket server subscribe to the OrderWatcher to receive updates.
+ // These updates are then broadcast to clients in the _connectionStore.
+ this._orderWatcher.subscribe(this._broadcastCallback.bind(this));
+
+ const port = process.env.ORDER_WATCHER_HTTP_PORT || DEFAULT_HTTP_PORT;
+ this._httpServer.listen(port, () => {
+ this._log(`${new Date()} [Server] Listening on port ${port}`);
+ });
+ }
+
+ /**
+ * Deactivates the WebSocket server by stopping the HTTP server from accepting
+ * new connections and unsubscribing from the OrderWatcher
+ */
+ public stop(): void {
+ this._httpServer.close();
+ this._orderWatcher.unsubscribe();
+ }
+
+ private _log(...args: any[]): void {
+ if (this._isVerbose) {
+ logUtils.log(...args);
+ }
+ }
+
+ private async _onMessageCallbackAsync(connection: WebSocket.connection, message: any): Promise<void> {
+ let response: WebSocketResponse;
+ let id: number | null = null;
+ try {
+ assert.doesConformToSchema('message', message, schemas.orderWatcherWebSocketUtf8MessageSchema);
+ const request: WebSocketRequest = JSON.parse(message.utf8Data);
+ id = request.id;
+ assert.doesConformToSchema('request', request, schemas.orderWatcherWebSocketRequestSchema);
+ assert.isString(request.jsonrpc, JSON_RPC_VERSION);
+ response = {
+ id,
+ jsonrpc: JSON_RPC_VERSION,
+ method: request.method,
+ result: await this._routeRequestAsync(request),
+ };
+ } catch (err) {
+ response = {
+ id,
+ jsonrpc: JSON_RPC_VERSION,
+ method: null,
+ error: err.toString(),
+ };
+ }
+ this._log(`${new Date()} [Server] OrderWatcher output: ${JSON.stringify(response)}`);
+ connection.sendUTF(JSON.stringify(response));
+ }
+
+ private _onCloseCallback(connection: WebSocket.connection): void {
+ this._connectionStore.delete(connection);
+ this._log(`${new Date()} [Server] Client ${connection.remoteAddress} disconnected.`);
+ }
+
+ private async _routeRequestAsync(request: WebSocketRequest): Promise<GetStatsResult | undefined> {
+ this._log(`${new Date()} [Server] Request received: ${request.method}`);
+ switch (request.method) {
+ case OrderWatcherMethod.AddOrder: {
+ const signedOrder: SignedOrder = OrderWatcherWebSocketServer._parseSignedOrder(
+ request.params.signedOrder,
+ );
+ await this._orderWatcher.addOrderAsync(signedOrder);
+ break;
+ }
+ case OrderWatcherMethod.RemoveOrder: {
+ this._orderWatcher.removeOrder(request.params.orderHash || 'undefined');
+ break;
+ }
+ case OrderWatcherMethod.GetStats: {
+ return this._orderWatcher.getStats();
+ }
+ default:
+ // Should never reach here. Should be caught by JSON schema check.
+ throw new Error(`Unexpected default case hit for request.method`);
+ }
+ return undefined;
+ }
+
+ /**
+ * Broadcasts OrderState changes to ALL connected clients. At the moment,
+ * we do not support clients subscribing to only a subset of orders. As such,
+ * Client B will be notified of changes to an order that Client A added.
+ */
+ private _broadcastCallback(err: Error | null, orderState?: OrderStateValid | OrderStateInvalid | undefined): void {
+ const method = OrderWatcherMethod.Update;
+ const response =
+ err === null
+ ? {
+ jsonrpc: JSON_RPC_VERSION,
+ method,
+ result: orderState,
+ }
+ : {
+ jsonrpc: JSON_RPC_VERSION,
+ method,
+ error: {
+ code: -32000,
+ message: err.message,
+ },
+ };
+ this._connectionStore.forEach((connection: WebSocket.connection) => {
+ connection.sendUTF(JSON.stringify(response));
+ });
+ }
+}
diff --git a/packages/order-watcher/src/server.ts b/packages/order-watcher/src/server.ts
new file mode 100644
index 000000000..1d31e87ab
--- /dev/null
+++ b/packages/order-watcher/src/server.ts
@@ -0,0 +1,44 @@
+import { getContractAddressesForNetworkOrThrow } from '@0x/contract-addresses';
+import { RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
+import * as _ from 'lodash';
+
+import { OrderWatcherWebSocketServer } from './order_watcher/order_watcher_web_socket_server';
+
+const GANACHE_NETWORK_ID = 50;
+const DEFAULT_RPC_URL = 'http://localhost:8545';
+
+const provider = new Web3ProviderEngine();
+const jsonRpcUrl = process.env.JSON_RPC_URL || DEFAULT_RPC_URL;
+const rpcSubprovider = new RPCSubprovider(jsonRpcUrl);
+provider.addProvider(rpcSubprovider);
+provider.start();
+
+const networkId = process.env.NETWORK_ID !== undefined ? _.parseInt(process.env.NETWORK_ID) : GANACHE_NETWORK_ID;
+
+const contractAddressesString = process.env.contractAddresses;
+const contractAddressesIfExists =
+ contractAddressesString === undefined
+ ? getContractAddressesForNetworkOrThrow(networkId)
+ : JSON.parse(contractAddressesString);
+
+const orderWatcherConfig: any = {
+ isVerbose: process.env.IS_VERBOSE === 'true',
+};
+const orderExpirationCheckingIntervalMs = process.env.ORDER_EXPIRATION_CHECKING_INTERVAL_MS;
+if (orderExpirationCheckingIntervalMs !== undefined) {
+ orderWatcherConfig.orderExpirationCheckingIntervalMs = _.parseInt(orderExpirationCheckingIntervalMs);
+}
+const eventPollingIntervalMs = process.env.EVENT_POLLING_INTERVAL_MS;
+if (eventPollingIntervalMs !== undefined) {
+ orderWatcherConfig.eventPollingIntervalMs = _.parseInt(eventPollingIntervalMs);
+}
+const expirationMarginMs = process.env.EXPIRATION_MARGIN_MS;
+if (expirationMarginMs !== undefined) {
+ orderWatcherConfig.expirationMarginMs = _.parseInt(expirationMarginMs);
+}
+const cleanupJobIntervalMs = process.env.CLEANUP_JOB_INTERVAL_MS;
+if (cleanupJobIntervalMs !== undefined) {
+ orderWatcherConfig.cleanupJobIntervalMs = _.parseInt(cleanupJobIntervalMs);
+}
+const wsServer = new OrderWatcherWebSocketServer(provider, networkId, contractAddressesIfExists, orderWatcherConfig);
+wsServer.start();
diff --git a/packages/order-watcher/src/types.ts b/packages/order-watcher/src/types.ts
index 8078dd971..2b529a939 100644
--- a/packages/order-watcher/src/types.ts
+++ b/packages/order-watcher/src/types.ts
@@ -1,4 +1,4 @@
-import { OrderState } from '@0x/types';
+import { OrderState, SignedOrder } from '@0x/types';
import { LogEntryEvent } from 'ethereum-types';
export enum OrderWatcherError {
@@ -31,3 +31,67 @@ export enum InternalOrderWatcherError {
ZrxNotInTokenRegistry = 'ZRX_NOT_IN_TOKEN_REGISTRY',
WethNotInTokenRegistry = 'WETH_NOT_IN_TOKEN_REGISTRY',
}
+
+export enum OrderWatcherMethod {
+ // Methods initiated by the user.
+ GetStats = 'GET_STATS',
+ AddOrder = 'ADD_ORDER',
+ RemoveOrder = 'REMOVE_ORDER',
+ // These are spontaneous; they are primarily orderstate changes.
+ Update = 'UPDATE',
+ // `subscribe` and `unsubscribe` are methods of OrderWatcher, but we don't
+ // need to expose them to the WebSocket server user because the user implicitly
+ // subscribes and unsubscribes by connecting and disconnecting from the server.
+}
+
+// Users have to create a json object of this format and attach it to
+// the data field of their WebSocket message to interact with the server.
+export type WebSocketRequest = AddOrderRequest | RemoveOrderRequest | GetStatsRequest;
+
+export interface AddOrderRequest {
+ id: number;
+ jsonrpc: string;
+ method: OrderWatcherMethod.AddOrder;
+ params: { signedOrder: SignedOrder };
+}
+
+export interface RemoveOrderRequest {
+ id: number;
+ jsonrpc: string;
+ method: OrderWatcherMethod.RemoveOrder;
+ params: { orderHash: string };
+}
+
+export interface GetStatsRequest {
+ id: number;
+ jsonrpc: string;
+ method: OrderWatcherMethod.GetStats;
+}
+
+// Users should expect a json object of this format in the data field
+// of the WebSocket messages that the server sends out.
+export type WebSocketResponse = SuccessfulWebSocketResponse | ErrorWebSocketResponse;
+
+export interface SuccessfulWebSocketResponse {
+ id: number;
+ jsonrpc: string;
+ method: OrderWatcherMethod;
+ result: OrderState | GetStatsResult | undefined; // result is undefined for ADD_ORDER and REMOVE_ORDER
+}
+
+export interface ErrorWebSocketResponse {
+ id: number | null;
+ jsonrpc: string;
+ method: null;
+ error: JSONRPCError;
+}
+
+export interface JSONRPCError {
+ code: number;
+ message: string;
+ data?: string | object;
+}
+
+export interface GetStatsResult {
+ orderCount: number;
+}
diff --git a/packages/order-watcher/test/order_watcher_test.ts b/packages/order-watcher/test/order_watcher_test.ts
index 271e5dec5..41dc884d5 100644
--- a/packages/order-watcher/test/order_watcher_test.ts
+++ b/packages/order-watcher/test/order_watcher_test.ts
@@ -675,5 +675,213 @@ describe('OrderWatcher', () => {
})().catch(done);
});
});
+ describe('multiAsset', async () => {
+ const tokenId = new BigNumber(42);
+ const [makerErc721TokenAddress] = tokenUtils.getDummyERC721TokenAddresses();
+ const makerErc721AssetData = assetDataUtils.encodeERC721AssetData(makerErc721TokenAddress, tokenId);
+ const fillableErc721Amount = new BigNumber(1);
+ const [makerErc20TokenAddress] = tokenUtils.getDummyERC20TokenAddresses();
+ const makerErc20AssetData = assetDataUtils.encodeERC20AssetData(makerErc20TokenAddress);
+ const fillableErc20Amount = new BigNumber(2);
+ const multiAssetAmounts = [fillableErc721Amount, fillableErc20Amount];
+ const nestedAssetData = [makerErc721AssetData, makerErc20AssetData];
+ const makerMultiAssetData = assetDataUtils.encodeMultiAssetData(multiAssetAmounts, nestedAssetData);
+ it('should emit orderStateInvalid when maker allowance of ERC721 token set to 0 for watched order', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableErc721Amount,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
+ });
+ orderWatcher.subscribe(callback);
+ await contractWrappers.erc721Token.setApprovalAsync(
+ makerErc721TokenAddress,
+ constants.NULL_ADDRESS,
+ tokenId,
+ );
+ })().catch(done);
+ });
+ it('should emit orderStateInvalid when maker allowance for all of ERC721 token set to 0 for watched order', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableErc721Amount,
+ );
+ await contractWrappers.erc721Token.setApprovalAsync(
+ makerErc721TokenAddress,
+ constants.NULL_ADDRESS,
+ tokenId,
+ );
+ let isApproved = true;
+ await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
+ makerErc721TokenAddress,
+ makerAddress,
+ isApproved,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
+ });
+ orderWatcher.subscribe(callback);
+ isApproved = false;
+ await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
+ makerErc721TokenAddress,
+ makerAddress,
+ isApproved,
+ );
+ })().catch(done);
+ });
+ it('should emit orderStateInvalid when maker moves ERC721 backing watched order', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableErc721Amount,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
+ });
+ orderWatcher.subscribe(callback);
+ await contractWrappers.erc721Token.transferFromAsync(
+ makerErc721TokenAddress,
+ coinbase,
+ makerAddress,
+ tokenId,
+ );
+ })().catch(done);
+ });
+ it('should emit orderStateInvalid when maker allowance of ERC20 token set to 0 for watched order', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableErc721Amount,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
+ });
+ orderWatcher.subscribe(callback);
+ await contractWrappers.erc20Token.setProxyAllowanceAsync(
+ makerErc20TokenAddress,
+ makerAddress,
+ new BigNumber(0),
+ );
+ })().catch(done);
+ });
+ it('should not emit an orderState event when irrelevant ERC20 Transfer event received', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableAmount,
+ );
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((_orderState: OrderState) => {
+ throw new Error('OrderState callback fired for irrelevant order');
+ });
+ orderWatcher.subscribe(callback);
+ const notTheMaker = userAddresses[0];
+ const anyRecipient = takerAddress;
+ const transferAmount = new BigNumber(2);
+ await contractWrappers.erc20Token.transferAsync(
+ makerTokenAddress,
+ notTheMaker,
+ anyRecipient,
+ transferAmount,
+ );
+ setTimeout(() => {
+ done();
+ }, TIMEOUT_MS);
+ })().catch(done);
+ });
+ it('should emit orderStateInvalid when makerAddress moves ERC20 balance backing watched order', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableAmount,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
+ });
+ orderWatcher.subscribe(callback);
+ const anyRecipient = takerAddress;
+ const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(
+ makerTokenAddress,
+ makerAddress,
+ );
+ await contractWrappers.erc20Token.transferAsync(
+ makerTokenAddress,
+ makerAddress,
+ anyRecipient,
+ makerBalance,
+ );
+ })().catch(done);
+ });
+ // TODO(abandeali1): The following test will fail until the MAP has been deployed and activated.
+ it.skip('should emit orderStateInvalid when watched order fully filled', (done: DoneCallback) => {
+ (async () => {
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerMultiAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableAmount,
+ );
+ const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ await orderWatcher.addOrderAsync(signedOrder);
+
+ const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
+ expect(orderState.isValid).to.be.false();
+ const invalidOrderState = orderState as OrderStateInvalid;
+ expect(invalidOrderState.orderHash).to.be.equal(orderHash);
+ expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
+ });
+ orderWatcher.subscribe(callback);
+
+ await contractWrappers.exchange.fillOrderAsync(signedOrder, fillableAmount, takerAddress);
+ })().catch(done);
+ });
+ });
});
}); // tslint:disable:max-file-line-count
diff --git a/packages/order-watcher/test/order_watcher_web_socket_server_test.ts b/packages/order-watcher/test/order_watcher_web_socket_server_test.ts
new file mode 100644
index 000000000..36135f65c
--- /dev/null
+++ b/packages/order-watcher/test/order_watcher_web_socket_server_test.ts
@@ -0,0 +1,312 @@
+import { ContractAddresses } from '@0x/contract-addresses';
+import { ContractWrappers } from '@0x/contract-wrappers';
+import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils';
+import { BlockchainLifecycle } from '@0x/dev-utils';
+import { FillScenarios } from '@0x/fill-scenarios';
+import { assetDataUtils, orderHashUtils } from '@0x/order-utils';
+import { ExchangeContractErrs, OrderStateInvalid, SignedOrder } from '@0x/types';
+import { BigNumber, logUtils } from '@0x/utils';
+import { Web3Wrapper } from '@0x/web3-wrapper';
+import * as chai from 'chai';
+import 'mocha';
+import * as WebSocket from 'websocket';
+
+import { OrderWatcherWebSocketServer } from '../src/order_watcher/order_watcher_web_socket_server';
+import { AddOrderRequest, OrderWatcherMethod, RemoveOrderRequest } from '../src/types';
+
+import { chaiSetup } from './utils/chai_setup';
+import { constants } from './utils/constants';
+import { migrateOnceAsync } from './utils/migrate';
+import { provider, web3Wrapper } from './utils/web3_wrapper';
+
+chaiSetup.configure();
+const expect = chai.expect;
+const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
+
+interface WsMessage {
+ data: string;
+}
+
+describe('OrderWatcherWebSocketServer', async () => {
+ let contractWrappers: ContractWrappers;
+ let wsServer: OrderWatcherWebSocketServer;
+ let wsClient: WebSocket.w3cwebsocket;
+ let wsClientTwo: WebSocket.w3cwebsocket;
+ let fillScenarios: FillScenarios;
+ let userAddresses: string[];
+ let makerAssetData: string;
+ let takerAssetData: string;
+ let makerTokenAddress: string;
+ let takerTokenAddress: string;
+ let makerAddress: string;
+ let takerAddress: string;
+ let zrxTokenAddress: string;
+ let signedOrder: SignedOrder;
+ let orderHash: string;
+ let addOrderPayload: AddOrderRequest;
+ let removeOrderPayload: RemoveOrderRequest;
+ let networkId: number;
+ let contractAddresses: ContractAddresses;
+ const decimals = constants.ZRX_DECIMALS;
+ const fillableAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(5), decimals);
+
+ before(async () => {
+ // Set up constants
+ contractAddresses = await migrateOnceAsync();
+ await blockchainLifecycle.startAsync();
+ networkId = constants.TESTRPC_NETWORK_ID;
+ const config = {
+ networkId,
+ contractAddresses,
+ };
+ contractWrappers = new ContractWrappers(provider, config);
+ userAddresses = await web3Wrapper.getAvailableAddressesAsync();
+ zrxTokenAddress = contractAddresses.zrxToken;
+ [makerAddress, takerAddress] = userAddresses;
+ [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses();
+ [makerAssetData, takerAssetData] = [
+ assetDataUtils.encodeERC20AssetData(makerTokenAddress),
+ assetDataUtils.encodeERC20AssetData(takerTokenAddress),
+ ];
+ fillScenarios = new FillScenarios(
+ provider,
+ userAddresses,
+ zrxTokenAddress,
+ contractAddresses.exchange,
+ contractAddresses.erc20Proxy,
+ contractAddresses.erc721Proxy,
+ );
+ signedOrder = await fillScenarios.createFillableSignedOrderAsync(
+ makerAssetData,
+ takerAssetData,
+ makerAddress,
+ takerAddress,
+ fillableAmount,
+ );
+ orderHash = orderHashUtils.getOrderHashHex(signedOrder);
+ addOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: OrderWatcherMethod.AddOrder,
+ params: { signedOrder },
+ };
+ removeOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: OrderWatcherMethod.RemoveOrder,
+ params: { orderHash },
+ };
+ });
+ after(async () => {
+ await blockchainLifecycle.revertAsync();
+ });
+ beforeEach(async () => {
+ // Prepare OrderWatcher WebSocket server
+ const orderWatcherConfig = {
+ isVerbose: true,
+ };
+ wsServer = new OrderWatcherWebSocketServer(provider, networkId, contractAddresses, orderWatcherConfig);
+ wsServer.start();
+ await blockchainLifecycle.startAsync();
+ wsClient = new WebSocket.w3cwebsocket('ws://127.0.0.1:8080/');
+ logUtils.log(`${new Date()} [Client] Connected.`);
+ });
+ afterEach(async () => {
+ wsClient.close();
+ await blockchainLifecycle.revertAsync();
+ wsServer.stop();
+ logUtils.log(`${new Date()} [Client] Closed.`);
+ });
+
+ it('responds to getStats requests correctly', (done: any) => {
+ const payload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'GET_STATS',
+ };
+ wsClient.onopen = () => wsClient.send(JSON.stringify(payload));
+ wsClient.onmessage = (msg: any) => {
+ const responseData = JSON.parse(msg.data);
+ expect(responseData.id).to.be.eq(1);
+ expect(responseData.jsonrpc).to.be.eq('2.0');
+ expect(responseData.method).to.be.eq('GET_STATS');
+ expect(responseData.result.orderCount).to.be.eq(0);
+ done();
+ };
+ });
+
+ it('throws an error when an invalid method is attempted', async () => {
+ const invalidMethodPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'BAD_METHOD',
+ };
+ wsClient.onopen = () => wsClient.send(JSON.stringify(invalidMethodPayload));
+ const errorMsg = await onMessageAsync(wsClient, null);
+ const errorData = JSON.parse(errorMsg.data);
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.id).to.be.null;
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.method).to.be.null;
+ expect(errorData.jsonrpc).to.be.eq('2.0');
+ expect(errorData.error).to.match(/^Error: Expected request to conform to schema/);
+ });
+
+ it('throws an error when jsonrpc field missing from request', async () => {
+ const noJsonRpcPayload = {
+ id: 1,
+ method: 'GET_STATS',
+ };
+ wsClient.onopen = () => wsClient.send(JSON.stringify(noJsonRpcPayload));
+ const errorMsg = await onMessageAsync(wsClient, null);
+ const errorData = JSON.parse(errorMsg.data);
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.method).to.be.null;
+ expect(errorData.jsonrpc).to.be.eq('2.0');
+ expect(errorData.error).to.match(/^Error: Expected request to conform to schema/);
+ });
+
+ it('throws an error when we try to add an order without a signedOrder', async () => {
+ const noSignedOrderAddOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'ADD_ORDER',
+ orderHash: '0x7337e2f2a9aa2ed6afe26edc2df7ad79c3ffa9cf9b81a964f707ea63f5272355',
+ };
+ wsClient.onopen = () => wsClient.send(JSON.stringify(noSignedOrderAddOrderPayload));
+ const errorMsg = await onMessageAsync(wsClient, null);
+ const errorData = JSON.parse(errorMsg.data);
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.id).to.be.null;
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.method).to.be.null;
+ expect(errorData.jsonrpc).to.be.eq('2.0');
+ expect(errorData.error).to.match(/^Error: Expected request to conform to schema/);
+ });
+
+ it('throws an error when we try to add a bad signedOrder', async () => {
+ const invalidAddOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'ADD_ORDER',
+ signedOrder: {
+ makerAddress: '0x0',
+ },
+ };
+ wsClient.onopen = () => wsClient.send(JSON.stringify(invalidAddOrderPayload));
+ const errorMsg = await onMessageAsync(wsClient, null);
+ const errorData = JSON.parse(errorMsg.data);
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.id).to.be.null;
+ // tslint:disable-next-line:no-unused-expression
+ expect(errorData.method).to.be.null;
+ expect(errorData.error).to.match(/^Error: Expected request to conform to schema/);
+ });
+
+ it('executes addOrder and removeOrder requests correctly', async () => {
+ wsClient.onopen = () => wsClient.send(JSON.stringify(addOrderPayload));
+ const addOrderMsg = await onMessageAsync(wsClient, OrderWatcherMethod.AddOrder);
+ const addOrderData = JSON.parse(addOrderMsg.data);
+ expect(addOrderData.method).to.be.eq('ADD_ORDER');
+ expect((wsServer as any)._orderWatcher._orderByOrderHash).to.deep.include({
+ [orderHash]: signedOrder,
+ });
+
+ const clientOnMessagePromise = onMessageAsync(wsClient, OrderWatcherMethod.RemoveOrder);
+ wsClient.send(JSON.stringify(removeOrderPayload));
+ const removeOrderMsg = await clientOnMessagePromise;
+ const removeOrderData = JSON.parse(removeOrderMsg.data);
+ expect(removeOrderData.method).to.be.eq('REMOVE_ORDER');
+ expect((wsServer as any)._orderWatcher._orderByOrderHash).to.not.deep.include({
+ [orderHash]: signedOrder,
+ });
+ });
+
+ it('broadcasts orderStateInvalid message when makerAddress allowance set to 0 for watched order', async () => {
+ // Add the regular order
+ wsClient.onopen = () => wsClient.send(JSON.stringify(addOrderPayload));
+
+ // We register the onMessage callback before calling `setProxyAllowanceAsync` which we
+ // expect will cause a message to be emitted. We do now "await" here, since we want to
+ // check for messages _after_ calling `setProxyAllowanceAsync`
+ const clientOnMessagePromise = onMessageAsync(wsClient, OrderWatcherMethod.Update);
+
+ // Set the allowance to 0
+ await contractWrappers.erc20Token.setProxyAllowanceAsync(makerTokenAddress, makerAddress, new BigNumber(0));
+
+ // We now await the `onMessage` promise to check for the message
+ const orderWatcherUpdateMsg = await clientOnMessagePromise;
+ const orderWatcherUpdateData = JSON.parse(orderWatcherUpdateMsg.data);
+ expect(orderWatcherUpdateData.method).to.be.eq('UPDATE');
+ const invalidOrderState = orderWatcherUpdateData.result as OrderStateInvalid;
+ expect(invalidOrderState.isValid).to.be.false();
+ expect(invalidOrderState.orderHash).to.be.eq(orderHash);
+ expect(invalidOrderState.error).to.be.eq(ExchangeContractErrs.InsufficientMakerAllowance);
+ });
+
+ it('broadcasts to multiple clients when an order backing ZRX allowance changes', async () => {
+ // Prepare order
+ const makerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(2), decimals);
+ const takerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(0), decimals);
+ const nonZeroMakerFeeSignedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
+ makerAssetData,
+ takerAssetData,
+ makerFee,
+ takerFee,
+ makerAddress,
+ takerAddress,
+ fillableAmount,
+ takerAddress,
+ );
+ const nonZeroMakerFeeOrderPayload = {
+ id: 1,
+ jsonrpc: '2.0',
+ method: 'ADD_ORDER',
+ params: {
+ signedOrder: nonZeroMakerFeeSignedOrder,
+ },
+ };
+
+ // Set up a second client and have it add the order
+ wsClientTwo = new WebSocket.w3cwebsocket('ws://127.0.0.1:8080/');
+ logUtils.log(`${new Date()} [Client] Connected.`);
+ wsClientTwo.onopen = () => wsClientTwo.send(JSON.stringify(nonZeroMakerFeeOrderPayload));
+
+ // Setup the onMessage callbacks, but don't await them yet
+ const clientOneOnMessagePromise = onMessageAsync(wsClient, OrderWatcherMethod.Update);
+ const clientTwoOnMessagePromise = onMessageAsync(wsClientTwo, OrderWatcherMethod.Update);
+
+ // Change the allowance
+ await contractWrappers.erc20Token.setProxyAllowanceAsync(zrxTokenAddress, makerAddress, new BigNumber(0));
+
+ // Check that both clients receive the emitted event by awaiting the onMessageAsync promises
+ let updateMsg = await clientOneOnMessagePromise;
+ let updateData = JSON.parse(updateMsg.data);
+ let orderState = updateData.result as OrderStateInvalid;
+ expect(orderState.isValid).to.be.false();
+ expect(orderState.error).to.be.eq('INSUFFICIENT_MAKER_FEE_ALLOWANCE');
+
+ updateMsg = await clientTwoOnMessagePromise;
+ updateData = JSON.parse(updateMsg.data);
+ orderState = updateData.result as OrderStateInvalid;
+ expect(orderState.isValid).to.be.false();
+ expect(orderState.error).to.be.eq('INSUFFICIENT_MAKER_FEE_ALLOWANCE');
+
+ wsClientTwo.close();
+ logUtils.log(`${new Date()} [Client] Closed.`);
+ });
+});
+
+// HACK: createFillableSignedOrderAsync is Promise-based, which forces us
+// to use Promises instead of the done() callbacks for tests.
+// onmessage callback must thus be wrapped as a Promise.
+async function onMessageAsync(client: WebSocket.w3cwebsocket, method: string | null): Promise<WsMessage> {
+ return new Promise<WsMessage>(resolve => {
+ client.onmessage = (msg: WsMessage) => {
+ const data = JSON.parse(msg.data);
+ if (data.method === method) {
+ resolve(msg);
+ }
+ };
+ });
+}