Commit 7f053fe2 authored by SilentCicero's avatar SilentCicero

version 0.0.1 -- basic docs, coverage etc

parents
root = true
[*]
end_of_line = lf
insert_final_newline = false
indent_style = space
indent_size = 2
# From https://github.com/Danimoth/gitattributes/blob/master/Web.gitattributes
# Handle line endings automatically for files detected as text
# and leave all files detected as binary untouched.
* text=auto
#
# The above will handle all files NOT found below
#
#
## These files are text and should be normalized (Convert crlf => lf)
#
# source code
*.php text
*.css text
*.sass text
*.scss text
*.less text
*.styl text
*.js text eol=lf
*.coffee text
*.json text
*.htm text
*.html text
*.xml text
*.svg text
*.txt text
*.ini text
*.inc text
*.pl text
*.rb text
*.py text
*.scm text
*.sql text
*.sh text
*.bat text
# templates
*.ejs text
*.hbt text
*.jade text
*.haml text
*.hbs text
*.dot text
*.tmpl text
*.phtml text
# server config
.htaccess text
# git config
.gitattributes text
.gitignore text
.gitconfig text
# code analysis config
.jshintrc text
.jscsrc text
.jshintignore text
.csslintrc text
# misc config
*.yaml text
*.yml text
.editorconfig text
# build config
*.npmignore text
*.bowerrc text
# Heroku
Procfile text
.slugignore text
# Documentation
*.md text
LICENSE text
AUTHORS text
#
## These files are binary and should be left untouched
#
# (binary is a macro for -text -diff)
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.mov binary
*.mp4 binary
*.mp3 binary
*.flv binary
*.fla binary
*.swf binary
*.gz binary
*.zip binary
*.7z binary
*.ttf binary
*.eot binary
*.woff binary
*.pyc binary
*.pdf binary
# Contributing to ethjs-provider-http
Love ethjs-provider-http and want to help? Thanks so much, there's something to do for everybody!
Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved.
Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features.
## Using the issue tracker
The [issue tracker](https://github.com/ethjs/ethjs-provider-http/issues) is
the preferred channel for [bug reports](#bugs), [features requests](#features)
and [submitting pull requests](#pull-requests).
<a name="bugs"></a>
## Bug reports
A bug is a _demonstrable problem_ that is caused by the code in the repository.
Good bug reports are extremely helpful - thank you!
Guidelines for bug reports:
1. **Use the GitHub issue search** &mdash; check if the issue has already been reported.
2. **Check if the issue has been fixed** &mdash; try to reproduce it using the latest `master` or development branch in the repository.
3. **Isolate the problem** &mdash;
A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and OS
experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs.
Example:
> Short and descriptive example bug report title
>
> A summary of the issue and the browser/OS environment in which it occurs. If
> suitable, include the steps required to reproduce the bug.
>
> 1. This is the first step
> 2. This is the second step
> 3. Further steps, etc.
>
> `<url>` - a link to the reduced test case
>
> Any other information you want to share that is relevant to the issue being
> reported. This might include the lines of code that you have identified as
> causing the bug, and potential solutions (and your opinions on their
> merits).
<a name="features"></a>
## Feature requests
Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible.
<a name="pull-requests"></a>
## Pull requests
Good pull requests - patches, improvements, new features - are a fantastic
help. They should remain focused in scope and avoid containing unrelated
commits.
**Please ask first** before embarking on any significant pull request (e.g.
implementing features, refactoring code, porting to a different language),
otherwise you risk spending a lot of time working on something that the
project's developers might not want to merge into the project.
Please adhere to the coding conventions used throughout a project (indentation,
accurate comments, etc.) and any other requirements (such as test coverage).
Adhering to the following process is the best way to get your work
included in the project:
1. [Fork](https://help.github.com/articles/fork-a-repo/) the project, clone your fork, and configure the remotes:
```bash
# Clone your fork of the repo into the current directory
git clone https://github.com/<your-username>/default.git
# Navigate to the newly cloned directory
cd default
# Assign the original repo to a remote called "upstream"
git remote add upstream https://github.com/ethjs/ethjs-provider-http.git
```
2. If you cloned a while ago, get the latest changes from upstream:
```bash
git checkout master
git pull upstream master
```
3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix:
```bash
git checkout -b <topic-branch-name>
```
4. Commit your changes in logical chunks. Please adhere to these [git commit message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) or your code is unlikely be merged into the main project. Use Git's [interactive rebase](https://help.github.com/articles/about-git-rebase/) feature to tidy up your commits before making them public.
5. Locally merge (or rebase) the upstream development branch into your topic branch:
```bash
git pull [--rebase] upstream master
```
6. Push your topic branch up to your fork:
```bash
git push origin <topic-branch-name>
```
7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
with a clear title and description.
**DESIGN NOTE**: default follows the UNIX programming philosophy. Please consider this before contributing, keep your commits/modules concise and to the point.
Read more here:
http://www.catb.org/esr/writings/taoup/html/ch01s06.html
**IMPORTANT**: By submitting a patch, you agree to allow the project
owners to license your work under the terms of the [MIT License](LICENSE.txt).
# ethjs-provider-http
Before opening a new issue, please take a moment to review our [**community guidelines**](https://github.com/ethjs/ethjs-provider-http/blob/master/.github/CONTRIBUTING.md) to make the contribution process easy and effective for everyone involved.
**Before opening a new issue, you may find an answer in already closed issues**:
https://github.com/ethjs/ethjs-provider-http/issues?q=is%3Aissue+is%3Aclosed
## Issue Type
- [ ] Bug (https://github.com/ethjs/ethjs-provider-http/blob/master/.github/CONTRIBUTING.md#bug-reports)
- [ ] Feature (https://github.com/ethjs/ethjs-provider-http/blob/master/.github/CONTRIBUTING.md#feature-requests)
## Description
(Add images if possible)
## Steps to reproduce
(Add link to a demo on https://jsfiddle.net or similar if possible)
# Versions
- Node/NPM:
- Browser:
## ethjs-provider-http
Thank you for contributing! Please take a moment to review our [**contributing guidelines**](https://github.com/ethjs/ethjs-provider-http/blob/master/.github/CONTRIBUTING.md)
to make the process easy and effective for everyone involved.
**Please open an issue** before embarking on any significant pull request, especially those that
add a new library or change existing tests, otherwise you risk spending a lot of time working
on something that might not end up being merged into the project.
Before opening a pull request, please ensure:
- [ ] You have followed our [**contributing guidelines**](https://github.com/ethjs/ethjs-provider-http/blob/master/.github/CONTRIBUTING.md)
- [ ] Pull request has tests (we are going for 100% coverage!)
- [ ] Code is well-commented, linted and follows project conventions
- [ ] Documentation is updated (if necessary)
- [ ] Internal code generators and templates are updated (if necessary)
- [ ] Description explains the issue/use-case resolved and auto-closes related issues
Be kind to code reviewers, please try to keep pull requests as small and focused as possible :)
**IMPORTANT**: By submitting a patch, you agree to allow the project
owners to license your work under the terms of the [MIT License](https://github.com/ethjs/ethjs-provider-http/blob/master/LICENSE.md).
# Don't check auto-generated stuff into git
node_modules
coverage
# Cruft
.DS_Store
npm-debug.log
sudo: true
language: node_js
node_js:
- "6"
compiler:
- gcc
- clang
install:
env:
- CXX=g++-4.8
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
- clang
after_success: npm run coveralls
# 0.0.1 -- ethjs-provider-signer
1. Basic testing
2. Basic docs
3. License
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project maintainer at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/
The MIT License
Copyright (c) 2016 Nick Dodson. nickdodson.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## ethjs-provider-signer
<div>
<!-- Dependency Status -->
<a href="https://david-dm.org/ethjs/ethjs-provider-signer">
<img src="https://david-dm.org/ethjs/ethjs-provider-signer.svg"
alt="Dependency Status" />
</a>
<!-- devDependency Status -->
<a href="https://david-dm.org/ethjs/ethjs-provider-signer#info=devDependencies">
<img src="https://david-dm.org/ethjs/ethjs-provider-signer/dev-status.svg" alt="devDependency Status" />
</a>
<!-- Build Status -->
<a href="https://travis-ci.org/ethjs/ethjs-provider-signer">
<img src="https://travis-ci.org/ethjs/ethjs-provider-signer.svg"
alt="Build Status" />
</a>
<!-- NPM Version -->
<a href="https://www.npmjs.org/package/ethjs-provider-signer">
<img src="http://img.shields.io/npm/v/ethjs-provider-signer.svg"
alt="NPM version" />
</a>
<!-- Test Coverage -->
<a href="https://coveralls.io/r/ethjs/ethjs-provider-signer">
<img src="https://coveralls.io/repos/github/ethjs/ethjs-provider-signer/badge.svg" alt="Test Coverage" />
</a>
<!-- Javascript Style -->
<a href="http://airbnb.io/javascript/">
<img src="https://img.shields.io/badge/code%20style-airbnb-brightgreen.svg" alt="js-airbnb-style" />
</a>
</div>
<br />
A simple web3 standard provider that signs sendTransaction payloads.
## Install
```
npm install --save ethjs-provider-signer
```
## Usage
```js
const SignerProvider = require('ethjs-provider-signer');
const Eth = require('ethjs-query');
const provider = new SignerProvider('http://ropsten.infura.io', {
privateKey: (account, cb) => cb(null, '0x...privateKey...'),
});
const eth = new Eth(provider);
eth.sendTransaction({
from: '0x407d73d8a49eeb85d32cf465507dd71d507100c1',
gas: 300000,
data: '0x...',
}, cb);
// results null 0x... (transaction hash)
```
## About
A simple wrapper module for `ethjs-provider-http` which allows you to sign sendTransaction payloads. It simply takes the sendTransaction data, signs it, and changes the payload method from `eth_sendTransaction` to `eth_sendRawTransaction`, then sends the payload.
The `privateKey` method is called everytime a payload must be signed. It provides the account address in question. The return should be a single privateKey string.
## Contributing
Please help better the ecosystem by submitting issues and pull requests to default. We need all the help we can get to build the absolute best linting standards and utilities. We follow the AirBNB linting standard and the unix philosophy.
## Guides
You'll find more detailed information on using `ethjs-provider-signer` and tailoring it to your needs in our guides:
- [User guide](docs/user-guide.md) - Usage, configuration, FAQ and complementary tools.
- [Developer guide](docs/developer-guide.md) - Contributing to `ethjs-provider-signer` and writing your own code and coverage.
## Help out
There is always a lot of work to do, and will have many rules to maintain. So please help out in any way that you can:
- Create, enhance, and debug ethjs rules (see our guide to ["Working on rules"](./github/CONTRIBUTING.md)).
- Improve documentation.
- Chime in on any open issue or pull request.
- Open new issues about your ideas for making `ethjs-provider-signer` better, and pull requests to show us how your idea works.
- Add new tests to *absolutely anything*.
- Create or contribute to ecosystem tools, like modules for encoding or contracts.
- Spread the word.
Please consult our [Code of Conduct](CODE_OF_CONDUCT.md) docs before helping out.
We communicate via [issues](https://github.com/ethjs/ethjs-provider-signer/issues) and [pull requests](https://github.com/ethjs/ethjs-provider-signer/pulls).
## Important documents
- [Changelog](CHANGELOG.md)
- [Code of Conduct](CODE_OF_CONDUCT.md)
- [License](https://raw.githubusercontent.com/ethjs/ethjs-provider-signer/master/LICENSE)
## Licence
This project is licensed under the MIT license, Copyright (c) 2016 Nick Dodson. For more information see LICENSE.md.
```
The MIT License
Copyright (c) 2016 Nick Dodson. nickdodson.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
# Documentation
## Table of Contents
- [General](general)
- [**Developer Guide**](developer-guide.md)
- [**User Guide**](user-guide.md)
## Overview
### Structure
The [`src/`](../../../tree/master/src) directory contains your entire application code, including JavaScript, and tests.
The rest of the folders and files only exist to make your life easier, and
should not need to be touched.
For more in-depth structure, see the developer-guide.md.
*(If they do have to be changed, please [submit an issue](https://github.com/ethjs/ethjs-provider-http/issues)!)*
### Testing
For a thorough explanation of the testing procedure, see the
[testing documentation](./developer-guide/README.md)!
#### Unit testing
Unit tests live in `src/tests/` directories right next to the components being tested
and are run with `npm test`.
# Developer Guide
All information regarding contributing to and progressing `ethjs-provider-signer` module can be found in this document.
## Install
```
npm install --save ethjs-provider-signer
```
## Install from Source
```
git clone http://github.com/ethjs/ethjs-provider-signer
npm install
```
## Test
```
npm test
```
## Travis-ci and Coveralls Testing
Note, this will generate the coveralls report locally.
```
npm run test-travis
```
## Folder Structure
All module source code is found in the `src` directory. All module helper scripts can be found in the `scripts` folder. These will not need to be touched, and are purely configuration for this repository.
```
./ethjs-provider-signer
./.github
./coverage
./docs
./src
./tests
```
## Dependancies
- "xhr2": "0.1.3" -- https://www.npmjs.com/package/xhr2
## NPM Practice
Across all `ethjs-` repos, we enforce version hardening (i.e. "0.0.3" not "^0.0.3"). We want to reduce potential hazardous install changes from dependancies as much as possible to ensure package preformace, testing, security and design. Please make sure all your commits and PR's are version hardend if you are installing or removing new packages.
## Chanelog
All relevant changes are notated in the `CHANGELOG.md` file, moniter this file for changes to this repository.
## Travis-ci and Coveralls Practice
Across all `ethjs-` repos, we enforce mandatory travis-ci and coveralls testing. We never `commit to master`. As a general policy, Coveralls.io results must always be above 95% for any `ethjs-` PR or commit. We want to ensure complete coverage across the board.
## Contributing
Please help better the ecosystem by submitting issues and pull requests to default. We need all the help we can get to build the absolute best linting standards and utilities. We follow the AirBNB linting standard. Please read more about contributing to `ethjs-provider-signer` in the `.github/CONTRIBUTING.md`.
## Licence
This project is licensed under the MIT license, Copyright (c) 2016 weifund. For more information see LICENSE.
# User Guide
All information for developers using `ethjs-provider-signer` should consult this document.
## Install
```
npm install --save ethjs-provider-signer
```
## Usage
```js
const SignerProvider = require('ethjs-provider-signer');
const Eth = require('ethjs-query');
const provider = new SignerProvider('http://ropsten.infura.io', {
privateKey: (account, cb) => cb(null, '0x...privateKey...'),
});
const eth = new Eth(provider);
eth.sendTransaction({
from: '0x407d73d8a49eeb85d32cf465507dd71d507100c1',
gas: 300000,
data: '0x...',
}, cb);
// results null 0x... (transaction hash)
```
## API Design
### constructor
[index.js:ethjs-provider-signer](../../../blob/master/src/index.js "Source code on GitHub")
Intakes a `provider` URL specified as a string, and an options object where the `privateKey` method is specified.
**Parameters**
- `provider` **String** the URL path to your local Http RPC enabled Ethereum node (e.g. `http://localhost:8545`) or a service node system like [Infura.io](http://infura.io) (e.g. `http://ropsten.infura.io`).
- `options` **Object** the options object where the `privateKey` method and `timeout` property is specified.
Example options **Object**:
```js
const options = {
privateKey: (account, cb) => {
if (account) {
cb(null, '0x...privateKey...');
} else {
cb('some error');
}
},
timeout: 400,
};
```
Result `SignerProvider` **Object**.
```js
const SignerProvider = require('ethjs-provider-signer');
const Eth = require('ethjs-query');
const provider = new SignerProvider('http://ropsten.infura.io', {
privateKey: (account, cb) => cb(null, '0x...privateKey...'),
});
const eth = new Eth(provider);
eth.sendTransaction({
from: '0x407d73d8a49eeb85d32cf465507dd71d507100c1',
gas: 300000,
data: '0x...',
}, cb);
// results null 0x... (transaction hash)
```
## Other Awesome Modules, Tools and Frameworks
- [web3.js](https://github.com/ethereum/web3.js) -- the original Ethereum swiss army knife **Ethereum Foundation**
- [ethereumjs](https://github.com/ethereumjs) -- critical ethereumjs infrastructure **Ethereum Foundation**
- [browser-solidity](https://ethereum.github.io/browser-solidity) -- an in browser Solidity IDE **Ethereum Foundation**
- [wafr](https://github.com/silentcicero/wafr) -- a super simple Solidity testing framework
- [truffle](https://github.com/ConsenSys/truffle) -- a solidity/js dApp framework
- [embark](https://github.com/iurimatias/embark-framework) -- a solidity/js dApp framework
- [dapple](https://github.com/nexusdev/dapple) -- a solidity dApp framework
- [chaitherium](https://github.com/SafeMarket/chaithereum) -- a JS web3 unit testing framework
- [contest](https://github.com/DigixGlobal/contest) -- a JS testing framework for contracts
## Our Relationship with Ethereum & EthereumJS
We would like to mention that we are not in any way affiliated with the Ethereum Foundation or `ethereumjs`. However, we love the work they do and work with them often to make Ethereum great! Our aim is to support the Ethereum ecosystem with a policy of diversity, modularity, simplicity, transparency, clarity, optimization and extensibility.
Many of our modules use code from `web3.js` and the `ethereumjs-` repositories. We thank the authors where we can in the relevant repositories. We use their code carefully, and make sure all test coverage is ported over and where possible, expanded on.
{
"name": "ethjs-provider-http",
"version": "0.0.1",
"description": "A simple Http provider that follows the web3 spec.",
"main": "src/index.js",
"scripts": {
"start": "npm test",
"test": "mocha src/tests/**/*.js -R spec --timeout 2000000",
"release": "npmpub",
"pretest": "npm run lint",
"lint": "npm run lint:js",
"lint:eslint": "eslint --ignore-path .gitignore",
"lint:js": "npm run lint:eslint -- . ",
"lint:staged": "lint-staged",
"test-travis": "node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- src/tests/**/*.js -R spec --timeout 2000000",
"coveralls": "npm run test-travis && cat ./coverage/lcov.info | coveralls"
},
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/ethjs/ethjs-provider-http.git"
},
"dependencies": {
"ethereumjs-tx": "1.1.4",
"ethjs-util": "0.0.4",
"ethjs-provider-http": "0.0.1"
},
"devDependencies": {
"web3": "0.17.0-beta",
"ethereumjs-testrpc": "3.0.2",
"ethjs-contract": "0.1.0",
"ethjs-query": "0.0.5",
"babel-eslint": "7.1.0",
"chai": "3.5.0",
"coveralls": "2.11.9",
"eslint": "2.10.1",
"eslint-config-airbnb": "9.0.1",
"eslint-import-resolver-webpack": "0.2.4",
"eslint-plugin-import": "1.8.0",
"eslint-plugin-jsx-a11y": "1.2.0",
"eslint-plugin-react": "5.1.1",
"eventsource-polyfill": "0.9.6",
"istanbul": "0.4.5",
"lint-staged": "1.0.1",
"mocha": "3.1.2",
"pre-commit": "1.1.3"
},
"engines": {
"npm": ">=3",
"node": ">=6.5.0"
},
"keywords": [
"ethereum",
"events",
"rpc"
],
"author": "Nick Dodson <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/ethjs/ethjs-provider-http/issues"
},
"homepage": "https://github.com/ethjs/ethjs-provider-http#readme",
"babel": {
"presets": [
"es2015"
],
"plugins": [
[
"module-resolver",
{
"root": [
"./src"
]
}
]
]
},
"lint-staged": {
"lint:eslint": "*.js"
},
"eslintConfig": {
"parser": "babel-eslint",
"extends": "airbnb",
"env": {
"node": true,
"mocha": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"import/no-unresolved": 2,
"comma-dangle": [
2,
"always-multiline"
],
"indent": [
2,
2,
{
"SwitchCase": 1
}
],
"no-console": 1,
"max-len": 0,
"prefer-template": 2,
"no-use-before-define": 0,
"newline-per-chained-call": 0,
"arrow-body-style": [
2,
"as-needed"
]
}
},
"pre-commit": "lint:staged"
}
const Tx = require('ethereumjs-tx');
const ethUtil = require('ethjs-util');
const HTTPProvider = require('ethjs-provider-http');
module.exports = SignerProvider;
function SignerProvider(path, options) {
if (!(this instanceof SignerProvider)) { throw new Error('[ethjs-provider-signer] the SignerProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new SignerProvider(...));`).'); }
if (typeof options !== 'object') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'privateKey' property specified, you provided type ${typeof options}.`); }
if (typeof options.privateKey !== 'function') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'privateKey' property specified, you provided type ${typeof options.privateKey} (e.g. 'const eth = new Eth(new SignerProvider("http://ropsten.infura.io", { privateKey: (account, cb) => cb(null, 'some private key') }));').`); }
const self = this;
self.options = options;
self.timeout = options.timeout || 0;
self.provider = new HTTPProvider(path, self.timeout);
}
// fix ethereumjs-tx rawTx object
function shimEthereumJSTxObject(rawTx) {
const rawTxMutation = Object.assign({}, rawTx);
// fix rawTx gaslimit
if (typeof rawTxMutation.gas === 'string') {
rawTxMutation.gasLimit = rawTxMutation.gas;
delete rawTxMutation.gas;
}
// return new mutated raw tx object
return rawTxMutation;
}
SignerProvider.prototype.sendAsync = function (payload, callback) { // eslint-disable-line
const self = this;
if (payload.method === 'eth_sendTransaction') {
self.options.privateKey(payload.params[0].from, (keyError, privateKey) => { // eslint-disable-line
if (!keyError) {
try {
// create new output payload
const outputPayload = Object.assign({}, {
id: payload.id,
jsonrpc: payload.jsonrpc,
method: 'eth_sendRawTransaction',
params: [],
});
// format raw tx data
const rawTx = Object.assign({}, shimEthereumJSTxObject(payload.params[0]));
// sign tx object, serilize, convert to hex, privateKey not stored in temp data
const signedHexPayload = new Tx(rawTx);
signedHexPayload.sign(new Buffer(ethUtil.stripHexPrefix(privateKey), 'hex'));
// ensure hex is prefixed
outputPayload.params = [`0x${signedHexPayload.serialize().toString('hex')}`];
// send payload
self.provider.sendAsync(outputPayload, callback);
} catch (errorWhileSigning) {
return callback(new Error(`[ethjs-provider-signer] while signing your sendTransaction payload: ${JSON.stringify(errorWhileSigning)}`), null);
}
} else {
return callback(new Error(`[ethjs-provider-signer] while signing your sendTransaction payload: ${JSON.stringify(keyError)}`), null);
}
});
} else {
self.provider.sendAsync(payload, callback);
}
};
const assert = require('chai').assert;
const HTTPProvider = require('ethjs-provider-http'); // eslint-disable-line
const SignerProvider = require('../index.js'); // eslint-disable-line
const Eth = require('ethjs-query'); // eslint-disable-line
const Web3 = require('web3'); // eslint-disable-line
const TestRPC = require('ethereumjs-testrpc');
const server = TestRPC.server({
accounts: [{
secretKey: '0xc55c58355a32c095c7074837467382924180748768422589f5f75a384e6f3b33',
balance: '0x0000000000000056bc75e2d63100000',
}],
});
server.listen(5001);
describe('SignerProvider', () => {
describe('constructor', () => {
it('should construct properly', (done) => {
const provider = new SignerProvider('http://localhost:5001', {
privateKey: (account, cb) => cb(null, '0xc55c58355a32c095c7074837467382924180748768422589f5f75a384e6f3b33'),
});
assert.equal(typeof provider, 'object');
assert.equal(typeof provider.options, 'object');
assert.equal(typeof provider.options.privateKey, 'function');
assert.equal(provider.timeout, 0);
setTimeout(() => {
done();
}, 3000);
});
it('should throw errors when improperly constructed', () => {
assert.throws(() => SignerProvider('http://localhost:5001', {}), Error); // eslint-disable-line
assert.throws(() => new SignerProvider('http://localhost:5001', 22), Error);
assert.throws(() => new SignerProvider('http://localhost:5001', {}), Error);
assert.throws(() => new SignerProvider('http://localhost:5001'), Error);
});
});
describe('functionality', () => {
it('should perform normally for calls', (done) => {
const provider = new SignerProvider('http://localhost:5001', {
privateKey: (account, cb) => cb(null, '0xc55c58355a32c095c7074837467382924180748768422589f5f75a384e6f3b33'),
});
const eth = new Eth(provider);
eth.accounts((accountsError, accounts) => {
assert.equal(accountsError, null);
assert.equal(typeof accounts, 'object');
assert.equal(Array.isArray(accounts), true);
eth.getBalance(accounts[0], (balanceError, balanceResult) => {
assert.equal(balanceError, null);
assert.equal(typeof balanceResult, 'object');
done();
});
});
});
it('should reconstruct sendTransaction as sendRawTransaction', (done) => {
const provider = new SignerProvider('http://localhost:5001', {
privateKey: (account, cb) => cb(null, '0xc55c58355a32c095c7074837467382924180748768422589f5f75a384e6f3b33'),
});
const eth = new Eth(provider);
eth.accounts((accountsError, accounts) => {
assert.equal(accountsError, null);
assert.equal(Array.isArray(accounts), true);
eth.sendTransaction({
from: accounts[0],
to: '0xc55c58355a32c095c70748374673829241807487',
data: '0x',
gas: 300000,
}, (txError, txHash) => {
assert.equal(txError, null);
assert.equal(typeof txHash, 'string');
setTimeout(() => {
eth.getBalance('0xc55c58355a32c095c70748374673829241807487')
.then((balanceResult) => {
assert.equal(typeof balanceResult, 'object');
done();
});
}, 500);
});
});
});
it('should throw an error when key is invalid', (done) => {
const provider = new SignerProvider('http://localhost:5001', {
privateKey: (account, cb) => cb(null, '0xc23c58355132c025c707483746738294180748768422589f5f75a384e6f3b33'),
});
const eth = new Eth(provider);
eth.accounts((accountsError, accounts) => {
assert.equal(accountsError, null);
assert.equal(Array.isArray(accounts), true);
eth.sendTransaction({
from: accounts[0],
to: '0xc55c58355a32c095c70748374673829241807487',
data: '0x',
gas: 300000,
}).catch((txError) => {
assert.equal(typeof txError, 'object');
done();
});
});
});
it('should throw an error when key error is provided', (done) => {
const provider = new SignerProvider('http://localhost:5001', {
privateKey: (account, cb) => cb(new Error('account does not have permission')),
});
const eth = new Eth(provider);
eth.accounts((accountsError, accounts) => {
assert.equal(accountsError, null);
assert.equal(Array.isArray(accounts), true);
eth.sendTransaction({
from: accounts[0],
to: '0xc55c58355a32c095c70748374673829241807487',
data: '0x',
gas: 300000,
}).catch((txError) => {
assert.equal(typeof txError, 'object');
done();
});
});
});
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment