Skip to content
This repository has been archived by the owner on Dec 13, 2019. It is now read-only.

Commit

Permalink
Merge branch 'master' into liam/appInstanceAdjudicator
Browse files Browse the repository at this point in the history
  • Loading branch information
snario committed Nov 29, 2018
2 parents 8d383f6 + 5a1fe09 commit bee407c
Show file tree
Hide file tree
Showing 58 changed files with 2,050 additions and 783 deletions.
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"build": "lerna run build --sort",
"clean": "lerna run clean --parallel --no-bail",
"test": "lerna run test --stream",
"ganache": "ganache-cli --networkId ${npm_package_config_ganacheNetworkID} --verbose --gasLimit ${npm_package_config_ganacheGasLimit} --gasPrice ${npm_package_config_ganacheGasPrice} --port ${npm_package_config_ganachePort} --deterministic --account=\"${npm_package_config_unlockedAccount0},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount1},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount2},${npm_package_config_etherBalance}\" &> /dev/null &",
"ganache:ci": "ganache-cli --networkId ${npm_package_config_ganacheNetworkID} --verbose --gasLimit ${npm_package_config_ganacheGasLimit} --gasPrice ${npm_package_config_ganacheGasPrice} --port ${npm_package_config_ganachePort} --deterministic --account=\"${npm_package_config_unlockedAccount0},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount1},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount2},${npm_package_config_etherBalance}\"",
"ganache": "ganache-cli --networkId ${npm_package_config_ganacheNetworkID} --verbose --gasLimit ${npm_package_config_ganacheGasLimit} --gasPrice ${npm_package_config_ganacheGasPrice} --port ${npm_package_config_ganachePort} --deterministic --account=\"${npm_package_config_unlockedAccount0},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount1},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount2},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount3},${npm_package_config_etherBalance}\" &> /dev/null &",
"ganache:ci": "ganache-cli --networkId ${npm_package_config_ganacheNetworkID} --verbose --gasLimit ${npm_package_config_ganacheGasLimit} --gasPrice ${npm_package_config_ganacheGasPrice} --port ${npm_package_config_ganachePort} --deterministic --account=\"${npm_package_config_unlockedAccount0},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount1},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount2},${npm_package_config_etherBalance}\" --account=\"${npm_package_config_unlockedAccount3},${npm_package_config_etherBalance}\"",
"ganache:stop": "ps aux | grep ganache-cli | grep -v grep | awk '{print $2}' | xargs kill -9",
"lint": "lerna run lint --parallel --no-bail",
"lint:fix": "lerna run lint:fix --parallel --no-bail"
Expand All @@ -18,9 +18,10 @@
"ganachePort": 9545,
"ganacheGasLimit": "0xfffffffffff",
"ganacheGasPrice": "0x01",
"unlockedAccount0": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d",
"unlockedAccount1": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257e",
"unlockedAccount2": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257f",
"unlockedAccount0": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257a",
"unlockedAccount1": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257b",
"unlockedAccount2": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257c",
"unlockedAccount3": "0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d",
"etherBalance": "1000000000000000000000000"
},
"keywords": [
Expand Down
44 changes: 30 additions & 14 deletions packages/cf.js/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@
- `on(eventType, callback: Function)`
- `install`
- [Node event](#event-install)
- Params: `(appInstance: AppInstance)`
- Callback Params: `(appInstance: AppInstance)`
- `rejectInstall`
- [Node event](#event-rejectinstall)
- Params: `(appInstance: AppInstance)`
- Callback Params: `(appInstance: AppInstance)`
- `updateState`
- [Node event](#event-rejectinstall)
- Params: `(appInstance: AppInstance, oldState: AppState, newState: AppState)`
- Callback Params: `(appInstance: AppInstance, oldState: AppState, newState: AppState)`
- `proposeState`
- [Node event](#event-proposestate)
- Params: `(appInstance: AppInstance, oldState: AppState, newState: AppState)`
- Callback Params: `(appInstance: AppInstance, oldState: AppState, newState: AppState)`
- `rejectState`
- [Node event](#event-rejectstate)
- Params: `(appInstance: AppInstance, state: AppState)`
- Callback Params: `(appInstance: AppInstance, state: AppState)`
- `uninstall`
- [Node event](#event-uninstall)
- Params: `(appInstance: AppInstance, finalState: AppState, myPayout: BigNumber, peerPayout: BigNumber)`
- Callback Params: `(appInstance: AppInstance, finalState: AppState, myPayout: BigNumber, peerPayout: BigNumber)`
- `AppFactory`
- Properties
- `provider: Provider`
Expand Down Expand Up @@ -100,18 +100,34 @@
Node Protocol
=============

Message Format
--------------

Messages in the Node Protocol have the following fields:

- `type: string`
- Name of the Method or Event that this message represents e.g. "getAppInstances", "install"
- `requestId?: string`
- Unique ID for a Method request.
- Only required for Methods. Leave empty for Events.
- `data: { [key: string]: any }`
- Data payload for this message.
- See "Result" section of a Method and "Data" section of an Event for details.

Public Methods
--------------

### Method: `getAppInstances`

Returns **all** app instances currently installed on the Node.
Returns all app instances currently installed on the Node.

**NOTE**: This is terrible from a security perspective. In the future this method will be changed or deprecated to fix the security flaw.
NOTE: This is terrible from a security perspective. In the future this method will be changed or deprecated to fix the security flaw.

Params: `[]`
Params: None

Result: list of [`AppInstanceInfo`](#data-type-appinstanceinfo)
Result:
- `appInstances:`[`AppInstanceInfo`](#data-type-appinstanceinfo)`[]`
- All the app instances installed on the Node

### Method: `proposeInstall`

Expand Down Expand Up @@ -254,23 +270,23 @@ Events

Fired if new app instance was successfully installed.

Params:
Data:
- `appInstance:`[`AppInstanceInfo`](#data-type-appinstanceinfo)
- Newly installed app instance

### Event: `rejectInstall`

Fired if installation of a new app instance was rejected.

Params:
Data:
- `appInstance:`[`AppInstanceInfo`](#data-type-appinstanceinfo)
- Rejected app instance

### Event: `updateState`

Fired if app state is successfully updated.

Params:
Data:
- `appInstanceId: string`
- Unique ID of app instance
- `newState:`[`AppState`](#data-type-appstate)
Expand All @@ -282,7 +298,7 @@ Params:

Fired if app instance is successfully uninstalled

Params:
Data:
- `appInstance:`[`AppInstanceInfo`](#data-type-appinstanceinfo)
- Uninstalled app instance
- `myPayout: BigNumber`
Expand Down
1 change: 0 additions & 1 deletion packages/cf.js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
},
"dependencies": {
"@counterfactual/contracts": "0.0.2",
"@counterfactual/node-provider": "0.0.1",
"cuid": "^2.1.4",
"ethers": "^4.0.4"
},
Expand Down
9 changes: 7 additions & 2 deletions packages/cf.js/src/app-factory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { AppDefinition } from "./structs";
import { Provider } from "./provider";
import { Address, AppABIEncodings } from "./types";

export class AppFactory {
constructor(readonly appDefinition: AppDefinition) {}
constructor(
readonly provider: Provider,
readonly appId: Address,
readonly encodings: AppABIEncodings
) {}
}
7 changes: 5 additions & 2 deletions packages/cf.js/src/app-instance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { AppInstanceID } from "./simple-types";
import { AppInstanceID, AppInstanceInfo } from "./types";

export class AppInstance {
constructor(readonly id: AppInstanceID) {}
readonly id: AppInstanceID;
constructor(readonly info: AppInstanceInfo) {
this.id = info.id;
}
}
6 changes: 6 additions & 0 deletions packages/cf.js/src/legacy/utils/free-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,10 @@ export class FreeBalance {
readonly timeout: number,
readonly dependencyNonce: Nonce
) {}

public balanceOfAddress(address: Address): ethers.utils.BigNumber {
if (address === this.alice) return this.aliceBalance;
if (address === this.bob) return this.bobBalance;
throw Error(`address ${address} not in free balance`);
}
}
4 changes: 0 additions & 4 deletions packages/cf.js/src/legacy/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ export type Bytes32 = string;
export type Address = string; // ethereum address (i.e. rightmost 20 bytes of keccak256 of ECDSA pubkey)
export type H256 = string; // a bytes32 which is the output of the keccak256 hash function

export async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

export async function mineOneBlock(provider: ethers.providers.JsonRpcProvider) {
return provider.send("evm_mine", []);
}
Expand Down
89 changes: 40 additions & 49 deletions packages/cf.js/src/provider.ts
Original file line number Diff line number Diff line change
@@ -1,91 +1,82 @@
import {
INodeProvider,
NodeMessage,
NodeMessageType,
NodeQueryData,
QueryType
} from "@counterfactual/node-provider";

import cuid from "cuid";

import { AppFactory } from "./app-factory";
import { AppInstance } from "./app-instance";
import { AppDefinition } from "./structs";
import { INodeProvider, Node } from "./types";

export enum CounterfactualEventType {
INSTALL = "cf_install",
PROPOSE_INSTALL = "cf_proposeInstall",
REJECT_INSTALL = "cf_rejectInstall"
}
export import DappEventType = Node.EventName;

export interface CounterfactualEvent {
readonly eventType: CounterfactualEventType;
export interface DappEvent {
readonly type: DappEventType;
readonly data: any; // TODO
}

const NODE_REQUEST_TIMEOUT = 1500;

export class Provider {
private readonly requestListeners: {
[requestId: string]: (msg: NodeMessage) => void;
[requestId: string]: (msg: Node.Message) => void;
} = {};

constructor(readonly nodeProvider: INodeProvider) {
this.nodeProvider.onMessage(this.onNodeMessage.bind(this));
}

async getAppInstances(): Promise<AppInstance[]> {
const response = await this.sendNodeRequest(NodeMessageType.QUERY, {
queryType: QueryType.GET_APP_INSTANCES
});
return (response.data as NodeQueryData).appInstances!.map(
({ id }) => new AppInstance(id)
const response = await this.callNodeMethod(
Node.MethodName.GET_APP_INSTANCES,
{}
);
const result = response.result as Node.GetAppInstancesResult;
return result.appInstances.map(info => new AppInstance(info));
}

createAppFactory(appDefinition: AppDefinition): AppFactory {
return new AppFactory(appDefinition);
}

on(
eventType: CounterfactualEventType,
callback: (e: CounterfactualEvent) => void
) {
on(eventName: DappEventType, callback: (e: DappEvent) => void) {
// TODO: support notification observers
}

private async sendNodeRequest(
messageType: NodeMessageType,
data: any
): Promise<NodeMessage> {
private async callNodeMethod(
methodName: Node.MethodName,
params: Node.MethodParams
): Promise<Node.MethodResponse> {
const requestId = cuid();
return new Promise<NodeMessage>((resolve, reject) => {
this.requestListeners[requestId] = msg => {
if (msg.messageType === NodeMessageType.ERROR) {
return reject(msg);
return new Promise<Node.MethodResponse>((resolve, reject) => {
this.requestListeners[requestId] = response => {
if (response.type === Node.ErrorType.ERROR) {
return reject(response.data);
}
if (response.type !== methodName) {
return reject({
errorName: "unexpected_message_type",
message: `Unexpected response type. Expected ${methodName}, got ${
response.type
}`
});
}
resolve(msg);
resolve(response as Node.MethodResponse);
};
setTimeout(() => {
if (this.requestListeners[requestId] !== undefined) {
reject(new Error(`Request timed out: ${requestId}`));
delete this.requestListeners[requestId];
}
}, NODE_REQUEST_TIMEOUT);
this.nodeProvider.postMessage({
this.nodeProvider.sendMessage({
requestId,
messageType,
data
params,
type: methodName
});
});
}

private onNodeMessage(message: NodeMessage) {
const { requestId } = message;
if (this.requestListeners[requestId]) {
this.requestListeners[requestId](message);
delete this.requestListeners[requestId];
private onNodeMessage(message: Node.Message) {
const requestId = (message as Node.MethodResponse).requestId;
if (requestId) {
if (this.requestListeners[requestId]) {
this.requestListeners[requestId](message);
delete this.requestListeners[requestId];
}
} else {
// TODO: notify observers
}
// TODO: notify observers
}
}
7 changes: 0 additions & 7 deletions packages/cf.js/src/structs.ts

This file was deleted.

2 changes: 0 additions & 2 deletions packages/cf.js/src/types.ts

This file was deleted.

30 changes: 30 additions & 0 deletions packages/cf.js/src/types/data-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// https://github.com/counterfactual/monorepo/blob/master/packages/cf.js/API_REFERENCE.md#data-types
import { BigNumber } from "ethers/utils";

import { ABIEncoding, Address } from "./simple-types";

export interface AppInstanceInfo {
id: string;
appId: Address;
abiEncodings: AppABIEncodings;
asset: BlockchainAsset;
myDeposit: BigNumber;
peerDeposit: BigNumber;
timeout: BigNumber;
}

export interface AppABIEncodings {
stateEncoding: ABIEncoding;
actionEncoding?: ABIEncoding;
}

export enum AssetType {
ETH = 0,
ERC20 = 1,
Other = 2
}

export interface BlockchainAsset {
assetType: AssetType;
token?: Address;
}
32 changes: 32 additions & 0 deletions packages/cf.js/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {
ABIEncoding,
Address,
AppAction,
AppInstanceID,
AppState,
Bytes32
} from "./simple-types";

import {
AppABIEncodings,
AppInstanceInfo,
AssetType,
BlockchainAsset
} from "./data-types";

import { INodeProvider, Node } from "./node-protocol";

export {
INodeProvider,
Node,
AssetType,
AppABIEncodings,
BlockchainAsset,
AppInstanceInfo,
ABIEncoding,
Address,
AppAction,
AppInstanceID,
AppState,
Bytes32
};
Loading

0 comments on commit bee407c

Please sign in to comment.