GithubHelp home page GithubHelp logo

counterfactual / monorepo Goto Github PK

View Code? Open in Web Editor NEW
186.0 15.0 44.0 27.68 MB

Home for all packages related to the Counterfactual project

Home Page: https://counterfactual.com

License: MIT License

JavaScript 1.86% Solidity 7.23% TypeScript 88.01% Shell 0.35% HTML 0.13% CSS 1.37% Makefile 0.10% Python 0.88% Dockerfile 0.07%
ethereum state-channels solidity counterfactual

monorepo's Introduction

NOTE: This repository has been moved. Work is continuing under the @statechannels organization as part of statechannels.org project to unify state channels initiatives.


Counterfactual
Counterfactual

Simple off-chain applications framework for Ethereum.

circleci license


Counterfactual is a simple off-chain framework for building state channel applications on top of the Ethereum blockchain. It aims to make it simpler to build permissionless applications that have instant finality with zero-fee transactions.

You can learn more about what state channels are by reading our whitepaper or a less technical written description. Further, if you want to dive into the specifications of the Counterfactual protocol you can read them here.

Packages

Solidity Packages

Package Version Description
@counterfactual/cf-funding-protocol-contracts npm Contracts implementation of the Counterfactual funding protocol
@counterfactual/cf-adjudicator-contracts npm Contracts implementation of an AppInstance Adjudicator

Typescript/Javascript Packages

Counterfactual-specific packages

Package Version Description
@counterfactual/node npm The core state channels client that a user runs
@counterfactual/cf.js npm A JS API for interacting with off-chain apps
@counterfactual/node-provider npm Wrapper around API calls to a Node

Utilities

Package Version Description
@counterfactual/types npm Shared type declarations
@counterfactual/typescript-typings npm Shims for external library typings

Contributing

Ethereum Networks

The Playground currently only supports the Kovan network.

Installing dependencies

Make sure you have Yarn v1.19.0 installed. For easy management of specific Yarn versions, we recommend using Yarn Version Manager (YVM).

To install the dependencies:

yarn

Building packages

It is recommended (optional) that you installed solc compiler binary on your machine (installation guide) and specify the following in your .env under cf-funding-protocol-contracts and apps

NATIVE_SOLC=true

To build all packages:

yarn build

Clean

To clean all packages:

yarn clean

Lint

To lint all packages:

yarn lint

To also apply automatic fixes:

yarn lint:fix

Tests

To run all tests:

yarn test

To run E2E tests:

  • If you're using E2E tests for the first time or have done recent changes to the code, run:
yarn test:e2e:setup
  • If you're re-running tests or writing new scenarios, run:
NODE_EXTENDED_PRIVATE_KEY="..." yarn test:e2e

See the "Funding the Hub Account for Playground Testing" section on the Simple Hub Server package for more information about NODE_EXTENDED_PRIVATE_KEY.

Patches

We generate patches using the patch-package tool with a workaround described in this issue for yarn workspaces.

monorepo's People

Contributors

adklempner avatar alonski avatar alxiong avatar arjunbhuptani avatar armaniferrante avatar briarsweetbriar avatar cf19drofxots avatar dependabot[bot] avatar ebryn avatar emansipater avatar greenkeeper[bot] avatar igort avatar jjmstark avatar joelalejandro avatar jtakalai avatar kosecki123 avatar kthomas avatar laynehaber avatar ldct avatar mitchelljustin avatar nikeshnazareth avatar noahmarconi avatar nrryuya avatar renovate[bot] avatar rhlsthrm avatar snario avatar spersico avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

monorepo's Issues

[machine] CfOperations tests should use a ProxyFactory instead of manually linking bytcode

// TODO: Truffle migrate does not auto-link the bytecode in the build folder,
// so we have to do it manually. Will fix later of course :)
const multisig = await new ethers.ContractFactory(
MinimumViableMultisigJson.abi,
devEnvNetworkContext7777777.linkBytecode(MinimumViableMultisigJson.bytecode),
ethersMasterWallet
).deploy();

[machine] AppChannelInfo interface shouldn't be aware of any StateChannelInfo instance

export interface AppChannelInfo {
// cf address
id: H256;
// used to generate cf address
uniqueId: number;
peerA: PeerBalance;
peerB: PeerBalance;
// ephemeral keys
keyA?: Address;
keyB?: Address;
encodedState: any;
appState?: any;
appStateHash?: H256;
localNonce: number;
timeout: number;
terms: Terms;
cfApp: CfAppInterface;
dependencyNonce: CfNonce;
// TODO: Move this into a method that is outside the data structure
stateChannel?: StateChannelInfo;
}

[machine] Commitments interface shouldn't use a Map for storing commitments

public serialize(): string {
// FIXME: This is absurd, we shouldn't even be using a Map for this use case
// considering that the keys are all strings anyway.
// https://stackoverflow.com/a/29085474/2680092
const pairs: [ActionName, Transaction][] = [];
this.commitments.forEach((v, k) => {
pairs.push([k, v]);
});
return JSON.stringify(pairs);
}

[machine] KeyGenerator.generate() must assign ephemeral keys

public static generate(message: InternalMessage, next: Function) {
const wallet = ethers.Wallet.createRandom();
const installData = message.clientMessage.data;
// FIXME: properly assign ephemeral keys
// if (installData.peerA.address === message.clientMessage.fromAddress) {
// installData.keyA = wallet.address;
// } else {
// installData.keyB = wallet.address;
// }
// return wallet;
}

[machine] Attempts to make a commitment with a missing counterparty signature shouldn't throw an unhandled error

const counterpartySignature = incomingMessage!.signature;
if (
counterpartySignature === undefined ||
signature.toString() === counterpartySignature.toString()
) {
// FIXME: these errors should be handled more gracefully
throw Error(
`Cannot make commitment for operation ${action}.
The counterparty hasn't signed the commitment.`
);
}

[machine] getLastResult() should return a nullable value

/**
* @returns the last received client message for this protocol. If the
* protocol just started, then we haven't received a message from
* our peer, so just return our starting message. Otherwise, return
* the last message from our peer (from IO_WAIT).
*/
public static lastClientMsg(
internalMessage: InternalMessage,
context: Context
) {
const res = getLastResult(Instruction.IO_WAIT, context.results);
// TODO: make getLastResult's return value nullable
return JSON.stringify(res) === JSON.stringify({})
? internalMessage.clientMessage
: res.value;
}

[machine] Several integration test functions lack nonce + uniqueId validation

cf-operations.spec.ts

validateNoAppsAndFreeBalance()

/**
* Validates the correctness of walletAs free balance *not* walletBs.
*/
function validateNoAppsAndFreeBalance(
multisigAddr: string,
walletA: TestResponseSink,
walletB: TestResponseSink,
amountAgiven: ethers.utils.BigNumber,
amountBgiven: ethers.utils.BigNumber
) {
// todo: add nonce and uniqueId params and check them
const state = walletA.vm.cfState;

validateUninstalledAndFreeBalance()

/**
* Validates the correctness of walletA's free balance *not* walletB's.
*/
function validateUninstalledAndFreeBalance(
multisigAddr: string,
cfAddr: string,
walletA: TestResponseSink,
walletB: TestResponseSink,
amountAgiven: ethers.utils.BigNumber,
amountBgiven: ethers.utils.BigNumber
) {
// TODO: add nonce and uniqueId params and check them
const state = walletA.vm.cfState;

lifecycle.spec.ts

validateUninstall()

public static validateUninstall(
cfAddr: string,
peerA: TestResponseSink,
peerB: TestResponseSink,
amountA: ethers.utils.BigNumber,
amountB: ethers.utils.BigNumber
) {
// TODO: add nonce and uniqueId params and check them
const state = peerA.vm.cfState;
const canon = PeerBalance.balances(
peerA.signingKey.address!,
amountA,
peerB.signingKey.address!,
amountB
);

test-setup.ts

validateWallet()

/**
* Validates the correctness of walletAs free balance *not* walletBs.
*/
public static validateWallet(
peerA: TestResponseSink,
peerB: TestResponseSink,
amountA: ethers.utils.BigNumber,
amountB: ethers.utils.BigNumber
) {
// TODO: add nonce and uniqueId params and check them
const state = peerA.vm.cfState;
const canon = PeerBalance.balances(
peerA.signingKey.address,
amountA,
peerB.signingKey.address,
amountB
);

[machine] Signing keys creation shouldn't take care of sorting such keys

private static newSigningKeys(context: Context, data: InstallData): string[] {
const lastResult = getLastResult(Instruction.IO_WAIT, context.results);
let signingKeys;
if (lastResult && lastResult.value && lastResult.value.data) {
signingKeys = [lastResult.value.data.keyA, lastResult.value.data.keyB];
} else {
signingKeys = [data.keyA!, data.keyB!];
}
// TODO: Feels like this is the wrong place for this sorting...
signingKeys.sort((addrA: Address, addrB: Address) => {
return new ethers.utils.BigNumber(addrA).lt(addrB) ? -1 : 1;
});
return signingKeys;
}

[machine] NetworkContext shouldn't link contract byte-code relying on dynamic references and object inspection

export class NetworkContext {
// FIXME: This is just bad practice :S
private contractToVar = {
Registry: "registryAddr",
PaymentApp: "paymentAppAddr",
ConditionalTransaction: "conditionalTransactionAddr",
MultiSend: "multiSendAddr",
NonceRegistry: "nonceRegistryAddr",
Signatures: "signaturesAddr",
StaticCall: "staticCallAddr",
ETHBalanceRefundApp: "ethBalanceRefundAppAddr"
};
constructor(
readonly registryAddr: Address,
readonly paymentAppAddr: Address,
readonly conditionalTransactionAddr: Address,
readonly multiSendAddr: Address,
readonly nonceRegistryAddr: Address,
readonly signaturesAddr: Address,
readonly staticCallAddr: Address,
readonly ethBalanceRefundAppAddr: Address
) {}

[machine] Resolver code shouldn't be part of the contractInterface() method

public static contractInterface(ctx: NetworkContext): CfAppInterface {
const address = ctx.paymentAppAddr;
const applyAction = "0x00000000"; // not used
const resolver = new ethers.utils.Interface([
// TODO: Put this somewhere eh
"resolve(tuple(address,address,uint256,uint256),tuple(uint8,uint256,address))"
]).functions.resolve.sighash;
const turn = "0x00000000"; // not used
const isStateTerminal = "0x00000000"; // not used
return new CfAppInterface(
address,
applyAction,
resolver,
turn,
isStateTerminal,
"tuple(address alice, address bob, uint256 aliceBalance, uint256 bobBalance)"
);
}

Explore 0x's AssetProxy paradigm further to see if it is compatible

As it stands right now, transactions are either ETH, ERC20, or "Other" in the Transfer.Transaction objects implementation. Of course this means we can encode the data off-chain for arbitrary transactions to be made that distribute state, but there are limitations when we want to apply restrictions (e.g., limiting the scope of a resolution to "max 10 ETH" or, "max 10 DAI", or perhaps something more complicated like "only this specific CryptoKitty"). These limitations have to be encoded on-chain. Thus, there are probably some similarities in the implementation of 0x's AssetProxy that we could re-use.

[machine] Return a better error mesage if no middleware is found (instead of `cannot read property '0' of undefined`)

public async run(msg: InternalMessage, context: Context) {
let counter = 0;
const middlewares = this.middlewares;
const opCode = msg.opCode;
this.executeAllMiddlewares(msg, context);
async function callback() {
if (counter === middlewares[opCode].length - 1) {
return Promise.resolve(null);
}
// This is hacky, prevents next from being called more than once
counter += 1;
const middleware = middlewares[opCode][counter];
if (opCode === Instruction.ALL || middleware.scope === opCode) {
return middleware.method(msg, callback, context);
}
return callback();
}
// TODO: Document or throw error about the fact that you _need_ to have
// a middleware otherwise this will error with:
// `TypeError: Cannot read property '0' of undefined`
return this.middlewares[opCode][0].method(msg, callback, context);
}

[machine] TestCommitmentStore.addCommitment() shouldn't allow any other action other than UPDATE if there are any actions in `commitments` collection

public async addCommitment(
action: ActionName,
cfOperation: CfOperation,
signatures: Signature[]
) {
const commitment = cfOperation.transaction(signatures);
if (action !== ActionName.UPDATE && this.commitments.has(action)) {
return;
// FIXME: we should never non-maliciously get to this state
throw Error("Can't reset setup/install/uninstall commitments");
}
this.commitments.set(action, commitment);
}

[contracts] Set up Typechain to set up typings for contracts in tests

It would be nice to have typings for the contracts when we test them in the contracts package.

I spent some time trying this out, but there were a few limitations that will have to be considered before we fully integrate it into the code base.

  1. At the moment the set of typings in the related package truffle-typings are fairly limited. For example, there is no address property on a TruffleContract object. We still use TruffleContract objects in the repo, for example when we use artifacts.require. We'll need to extend that package or just extend our own package( packages/typescript-typings).

  2. In many places, we actually don't even use the TruffleContract object, we actually use ethers.Contract. Thus, we need to wait until this pull request is merged into Typechain adding support for ethers.js as a "target".

[machine] Execution of Instruction.ALL should do middleware cascading instead of plain iteration

/**
* Runs the middlewares for Instruction.ALL.
*/
// TODO: currently this method seems to be passing null as the middleware callback and
// just iterating through all the middlewares. We should pass the callback similarly to how
// run does it, and rely on that for middleware cascading
private executeAllMiddlewares(msg, context) {
const all = this.middlewares[Instruction.ALL];
if (all && all.length > 0) {
all.forEach(middleware => {
middleware.method(msg, null, context);
});
}
}
}

[machine] Remove timeout from CfMultisendOp.dependencyNonceInput()

public dependencyNonceInput(): MultisigInput {
const timeout = 0; // FIXME: new NonceRegistryJson design will obviate timeout
const to = this.networkContext.nonceRegistryAddr;
const val = 0;
const data = new ethers.utils.Interface(
NonceRegistryJson.abi
).functions.setNonce.encode([
timeout,
this.dependencyNonce.salt,
this.dependencyNonce.nonceValue
]);
const op = Operation.Call;
return new MultisigInput(to, val, data, op);
}

Can not run `yarn test`

hello

I git clone this Repositories and Run yarn ganache in a separate terminal

but when I type yarn test ,it gose wrong:

ubuntu@ip-172-31-15-69:~/counterfactual$ yarn test
yarn run v1.9.4
$ yarn ganache &> ganache.log & yarn build:pre && yarn build:packages && wsrun test $PKG --exclude-missing && yarn build:post
$ ./bin/prebuild
$ ganache-cli --gasLimit 0xfffffffffff --port 9545 --account="${npm_package_config_unlockedAccount}" -m "${npm_package_config_mnemonic}"
$ wsrun build $PKG --fast-exit -r --serial --exclude-missing
@counterfactual/configs has no  build script, skipping missing
@counterfactual/run-with-ganache has no  build script, skipping missing
@counterfactual/typescript-typings has no  build script, skipping missing
@counterfactual/test-utils
$ tsc --project tsconfig.json.modified
 | error TS5014: Failed to parse file 'packages/test-utils/tsconfig.json.modified/tsconfig.json': Unexpected token u in JSON at position 0.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
`yarn build` failed with exit code 1
Stopping 1 active children
Aborted execution due to previous error
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ubuntu@ip-172-31-15-69:~/counterfactual$ Ganache CLI v6.1.7 (ganache-core: 2.2.0)
Error: listen EADDRINUSE 127.0.0.1:9545
    at Server.setupListenHandle [as _listen2] (net.js:1336:14)
    at listenInCluster (net.js:1384:12)
    at doListen (net.js:1510:7)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

system configuration

ubuntu@ip-172-31-15-69:~/counterfactual$ uname -a 
Linux ip-172-31-15-69 4.4.0-1061-aws #70-Ubuntu SMP Fri May 25 21:47:34 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@ip-172-31-15-69:~/counterfactual$ node -v
v10.8.0
ubuntu@ip-172-31-15-69:~/counterfactual$ nodejs -v
v8.11.3
ubuntu@ip-172-31-15-69:~/counterfactual$ yarn -v
1.9.4
ubuntu@ip-172-31-15-69:~/counterfactual$ 

NEED HELP!

[machine] Initcode encoding shouldn't have a hardcoded timeout

const initcode = new ethers.utils.Interface(
AppInstanceJson.abi
).deployFunction.encode(
devEnvNetworkContext7777777.linkBytecode(AppInstanceJson.bytecode),
[
multisig.address,
signingKeys,
app.hash(),
terms.hash(),
// TODO: Don't hard-code the timeout, make it dependant on some
// function(blockchain) to in the future check for congestion... :)
100
]
);

[machine] CfFreeBalance requires implementation changes on the contracts layer

/**
* The state of a free balance object. Passing this into an install or uninstall
* will update the free balance object to the values given here.
*/
export class CfFreeBalance {
public static terms(): Terms {
// FIXME: Change implementation of free balance on contracts layer
return new Terms(
0, // 0 means ETH
ethers.utils.parseEther("0.001"), // FIXME: un-hardcode
ethers.constants.AddressZero
);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.