Giter Site home page Giter Site logo

ethrpc's Introduction

ethrpc

Build Status Coverage Status npm version

JavaScript RPC communication with the Ethereum network.

Usage

ethrpc can be installed using npm:

npm install ethrpc

After installing, to use it with Node, require it and call connect:

var rpc = require("ethrpc");
var connectionConfiguration = {
  httpAddresses: ["http://localhost:8545"], // optional, default empty array
  wsAddresses: [], // optional, default empty array
  ipcAddresses: [], // optional, default empty array
  networkID: 3, // optional, used to verify connection to the intended network (blockchain)
  connectionTimeout: 3000, // optional, default 3000
  errorHandler: function (err) { /* out-of-band error */ }, // optional, used for errors that can't be correlated back to a request
};
rpc.connect(connectionConfiguration, function (err) {
  if (err) {
    console.error("Failed to connect to Ethereum node.");
  } else {
    console.log("Connected to Ethereum node!");
  }
});

A minified, browserified file dist/ethrpc.min.js is included for use in the browser. Including this file simply attaches an ethrpc object to window:

<script src="dist/ethrpc.min.js" type="text/javascript"></script>

Basic RPC

The raw method allows you to send in commands that won't be parsed/mangled by ethrpc. (Similar to sending RPC requests with cURL.)

rpc.raw("net_peerCount");
"0x10"

Almost all commands listed in the Ethereum JSON RPC wiki page have named wrappers:

rpc.net.peerCount();
"0x10"

rpc.eth.blockNumber();
"0x35041"

Block and Log Notifications

If you want to subscribe to new blocks or new logs you can get access to a block and log streamer via:

var blockStream = rpc.getBlockStream();

With that, you can then subscribe to new blocks, subscribe to new logs, add log filters (by default you will receive no logs) and subscribe to be notified when blocks/logs are removed as well.

var onBlock = function (block) { /* block party! */ };
var onLog = function (log) { /* log party... */ };
var onBlockAddedSubscriptionToken = blockStream.subscribeToOnBlockAdded(onBlock);
var onLogAddedSubscriptionToken = blockStream.subscribeToOnLogAdded(onLog);
var onBlockRemovedSubscriptionToken = blockStream.subscribeToOnBlockRemoved(onBlock);
var onLogRemovedSubscriptionToken = blockStream.subscribeToOnLogRemoved(onLog);
var logFilterToken = blockStream.addLogFilter({
  address: "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  topics: ["0xbadf00dbadf00dbadf00dbadf00dbadf00dbadf00dbadf00dbadf00dbaadf00d"]
});
blockStream.unsubscribeFromOnBlockAdded(onBlockAddedSubscriptionToken);
blockStream.unsubscribeFromOnBlockRemoved(onBlockRemovedSubscriptionToken);
blockStream.unsubscribeFromOnLogAdded(onLogAddedSubscriptionToken);
blockStream.unsubscribeFromOnLogRemoved(onLogRemovedSubscriptionToken);
blockStream.removeLogFilter(logFilterToken);

Contract upload and download

publish broadcasts (uploads) a compiled contract to the network:

var txHash = rpc.publish("0x603980600b6000396044567c01000000000000000000000000000000000000000000000000000000006000350463643ceff9811415603757600a60405260206040f35b505b6000f3");
// txHash:
"0x6a532c807eb49d78bf0fb7962743c7f155a4b2fc1258b749df85c88b66fc3316"

// To get the contract's address, after the transaction is sealed (mined), get its receipt:
var address = rpc.eth.getTransactionReceipt(txHash).contractAddress;
// address:
"0x86fb6d1f1bd78cc13c6354b6436b6ea0c144de2e"

getCode downloads code from a contract already on the Ethereum network:

var contractCode = rpc.eth.getCode("0x86fb6d1f1bd78cc13c6354b6436b6ea0c144de2e");
// contractCode:
"0x7c010000000000000000000000000000000000000000000000000000000060003504636ffa1caa81141560415760043560405260026040510260605260206060f35b50"

Contract methods: call and sendTransaction

The callOrSendTransaction method executes a method in a contract already on the network. It can broadcast transactions to the network and/or capture return values by calling the contract method(s) locally.

// The method called here doubles its input argument.
var payload = {
  to: "0x5204f18c652d1c31c6a5968cb65e011915285a50",
  name: "double",
  signature: ["int256"],
  params: ["0x5669"], // parameter value(s)
  send: false,
  returns: "int"
};
rpc.callOrSendTransaction(payload);
// returns:
44242

The transaction payload is structured as follows:

Required:

  • to: <contract address> (hexstring)
  • name: <function name> (string)
  • signature: <function signature, e.g. ["int256", "bytes", "int256[]"]> (array)
  • params: <parameters passed to the function>

Optional:

  • send: <true to sendTransaction, false to call (default)>
  • from: <sender's address> (hexstring; defaults to the coinbase account)
  • returns: <"int256" (default), "int", "number", "int256[]", "number[]", or "string">

The params and signature fields are required if your function accepts parameters; otherwise, these fields can be excluded. The returns field is used only to format the output, and does not affect the actual RPC request.

Tests

Unit tests are included in test/ethrpc.js, and can be run using npm:

npm test

Alternatively, you can run the tests inside of a docker container. Docker layer caching is leveraged to make it so the build is very fast after the first time (unless you change dependencies):

docker build -t ethrpc . && docker run --rm ethrpc

Internal Architecture

Upon calling connect, a Transporter will be instantiated with the supplied addresses to connect to. A Transport will be created for each of the supplied addresses plus one for web3. Once they have all either successfully connected or failed to connect, Transporter will choose the first address for each transport type (HTTP, WS, IPC, Web3) that connected successfully and use that as the Transport for that transport type. The transport will be chosen automatically based on a preference of Web3 > IPC > WS > HTTP. If no transports are available, the request will fail. The Transports each have their own internal queue of work and if they lose a connection they will queue up incoming requests until a connection can be re-established. Once it is, the queue will be pumped until empty.

ethrpc's People

Contributors

adrake33 avatar amousa11 avatar bthaile avatar canuc avatar epheph avatar fanatid avatar holgerd77 avatar johndanz avatar justinbarry avatar micahzoltu avatar nuevoalex avatar petong avatar pgebheim avatar priecint avatar randomnetcat avatar roshanr95 avatar ryanberckmans avatar stephensprinkle avatar stephensprinkle-zz avatar tinybike 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ethrpc's Issues

[NPM AUDIT] Please update lodash dependency

Running Node 8.10.0, npm 6.4.1 on Ubuntu 18.04, after pulling latest version of ethrpc (6.1.3)

`
=== npm audit security report ===

Run npm update lodash --depth 3 to resolve 1 vulnerability

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate │ Prototype Pollution │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ ethrpc │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ ethrpc > async > lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/782
└───────────────┴──────────────────────────────────────────────────────────────┘

Run npm update node.extend --depth 2 to resolve 1 vulnerability

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate │ Prototype Pollution │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ node.extend │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ node-yaml-config │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ node-yaml-config > node.extend │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/781
└───────────────┴──────────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────────────────────────┐
│ Manual Review │
│ Some vulnerabilities require your attention to resolve │
│ │
│ Visit https://go.npm.me/audit-guide for additional guidance │
└──────────────────────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate │ Prototype Pollution │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in │ >=4.17.11 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ ethrpc │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ ethrpc > lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/782
└───────────────┴──────────────────────────────────────────────────────────────┘
found 3 moderate severity vulnerabilities in 990 scanned packages
run npm audit fix to fix 2 of them.
1 vulnerability requires manual review. See the full report for details.
`

Upgrade transact sequence to use block subscriptions / filters

Right now the transact callback sequence uses manual polling to confirm transactions. This should be replaced with:

  • a shared block filter for HTTP RPC transactions, so that the chain only must be polled once for all pending transactions. To avoid unnecessary polling, the filter should probably be unset when there are no pending transactions.
  • a new block subscription for transactions sent over websockets/IPC, so that geth's push notifications can replace the current polling method altogether.

Number validation

Number validation allow number to be null or undefined

if (number === null) return number;
if (number === undefined) return number;

transaction validator uses this validator for gas, gas price, value, nonce -- all this fields can be empty? (null/undefined)

Add onConfirmed callback support to transact

transact should accept an optional fourth callback function, onConfirmed, which fires after some pre-set number of confirmations (i.e., block arrivals where the transaction is still valid). For example, a good default value for the number of required transactions to be "confirmed" is rpc.REQUIRED_CONFIRMATIONS=5.

The augur.rpc.txs status labels should probably be updated at the same time, since confirmed status presently refers to transactions that have been mined (but have received 0 confirmations). Better labels might be mined for freshly mined, 0-confirmation transactions and confirmed for transactions that have been confirmed rpc.REQUIRED_CONFIRMATIONS times.

What does this error mean?

Error:

/home/brandan/node_modules/ethrpc/src/rpc/submit-request-to-blockchain.js:47
    internalState.get("transporter").blockchainRpc(jso, transportRequirements, debug.broadcast);
                                    ^
 
TypeError: Cannot read property 'blockchainRpc' of null
    at /home/brandan/node_modules/ethrpc/src/rpc/submit-request-to-blockchain.js:47:37
    at store.dispatch (/home/brandan/node_modules/redux-thunk-subscribe/src/index.js:10:18)
    at /home/brandan/node_modules/ethrpc/src/wrappers/raw.js:10:12
    at store.dispatch (/home/brandan/node_modules/redux-thunk-subscribe/src/index.js:10:18)
    at /home/brandan/node_modules/ethrpc/src/wrappers/make-wrapper.js:12:14
    at store.dispatch (/home/brandan/node_modules/redux-thunk-subscribe/src/index.js:10:18)
    at /home/brandan/node_modules/ethrpc/src/transact/call-or-send-transaction.js:31:14
    at store.dispatch (/home/brandan/node_modules/redux-thunk-subscribe/src/index.js:10:18)
    at Object.callOrSendTransaction (/home/brandan/node_modules/ethrpc/src/create-ethrpc.js:240:66)
    at Object.<anonymous> (/home/brandan/grava/tests/ethrpc.js:11:17)

Code:

var rpc = require("ethrpc");
 
rpc.connect({
    httpAddresses: ["http://localhost:9545"],
    wsAddresses: [],
    ipcAddresses: []
}, function (err) {
    console.log(err)
});
 
console.log(rpc.callOrSendTransaction({
    to: '0xfb88de099e13c3ed21f80a7a1e49f8caecf10df6',
    name: 'getIndex',
    signature: [],
    params: [],
    send: true,
    returns: 'int'
}))

Vulnerabilities reported by npm audit

Using Node 9.11.1, npm 6.4.1, Xubuntu 18.04, on ethrpc latest master branch:

jack@substrate:~/src/ethrpc$ npm audit
                                                                                
                       === npm audit security report ===                        
                                                                                
# Run  npm install --save-dev [email protected]  to resolve 2 vulnerabilities
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ minimatch                                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ browserify [dev]                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ browserify > glob > minimatch                                │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/118                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Critical      │ Potential Command Injection                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ shell-quote                                                  │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ browserify [dev]                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ browserify > shell-quote                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/117                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


# Run  npm install --save-dev [email protected]  to resolve 1 vulnerability
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Denial of Service                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ws                                                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ ethereumjs-stub-rpc-server [dev]                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ ethereumjs-stub-rpc-server > ws                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/550                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


# Run  npm install --save-dev [email protected]  to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Denial of Service                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ws                                                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ ws [dev]                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ ws                                                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/550                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


# Run  npm install --save-dev [email protected]  to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate      │ Memory Exposure                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ tunnel-agent                                                 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ bufferutil [dev]                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ bufferutil > prebuild-install > tunnel-agent                 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/598                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


# Run  npm install --save-dev [email protected]  to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate      │ Memory Exposure                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ tunnel-agent                                                 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ utf-8-validate [dev]                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ utf-8-validate > prebuild-install > tunnel-agent             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/598                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


found 6 vulnerabilities (2 moderate, 3 high, 1 critical) in 7198 scanned packages
  run `npm audit fix` to fix 1 of them.
  5 vulnerabilities require semver-major dependency updates.

Fix websocket batch RPC

Currently throws an "unknown message received" error. Example data field is:

'[{"jsonrpc":"2.0","id":4,"result":"0x00000000000000000000000000000000000000000000021a72a75ef8d57ef000"},{"jsonrpc":"2.0","id":5,"result":"0x0000000000000000000000000000000000000000000000028c418afbbb5c0000"}]\n'

Add full synchronous support to transact

Full synchronous support would be nice because it would make setup and debugging of long client-side sequences both simpler and more similar to the sequences in the back-end tests, which (by the time the client-side sequence is under construction) are confirmed working. transact already does the initial eth_sendTransaction invoke synchronously (if no onSent callback is supplied), but this only supplies the txHash; including the initial fire error check, call return, and mutable return value lookup would allow the whole sequence setup to be written in simple synchronous style (for tests only, of course).

Error: Channel does not exist

hi, what is this error? and whats the meaning channel here? - (I took the code from here: (https://github.com/ScaleDrone/react-chat-tutorial))
Error: Channel does not exist
at exports.wrapError (scaledrone.min.js:297)
at Object. (scaledrone.min.js:288)
at l (scaledrone.min.js:2)
at Object.trigger (scaledrone.min.js:2)
at WebSocket.o.onmessage (scaledrone.min.js:294)

No error when trying to connect to geth, and no peers.

To reproduce:

  • Start geth and make sure there are no peers connected.
  • Run rpc.connect.
  • No error returns. hangs forever.

The issue happens because when trying to do the initial connection you do 3 things in parallel, where the first thing is ensureLatestBlock, and if you look at the code you will see that it fails silently, causing the async.parallel to hang forever.

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.