• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Maximal RPC wrapper

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.

More Repositories

1

ethereumjs-monorepo

Monorepo for the Ethereum VM TypeScript Implementation
TypeScript
2,525
star
2

ethereumjs-wallet

Utilities for handling Ethereum keys
TypeScript
986
star
3

ethereumjs-tx

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
779
star
4

keythereum

Create, import and export Ethereum keys
JavaScript
602
star
5

ethereumjs-util

Project is in active development and has been moved to the EthereumJS monorepo.
TypeScript
601
star
6

ethereumjs-lib

[DEPRECATED] A JavaScript library of core Ethereum functions
442
star
7

merkle-patricia-tree

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
306
star
8

ethereumjs-abi

[DEPRECATED] Decoder and encoder for the Ethereum ABI
JavaScript
294
star
9

ethereumjs-client

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
192
star
10

ethereumjs-devp2p

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
140
star
11

ethereumjs-blockchain

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
120
star
12

rlp

Project is in active development and has been moved to the EthereumJS monorepo.
TypeScript
120
star
13

ultralight

Ethereum Portal Network TypeScript implementation
TypeScript
97
star
14

ethereumjs-blockstream

Reliable stream of Ethereum blocks
TypeScript
80
star
15

helpeth

Help (with) Ethereum. Purists' commandline tool for key and transaction management.
JavaScript
75
star
16

browser-builds

[DEPRECATED] Browser builds of ethereumjs libraries.
JavaScript
59
star
17

node-blockchain-server

[DEPRECATED] A simple blockchain server (downloads block and serves them, doesn't do state transitions)
57
star
18

ethashjs

Project is in active development and has been moved to the EthereumJS VM monorepo.
JavaScript
56
star
19

geth.js

Start and stop geth from Node.js
JavaScript
45
star
20

ethereumjs-account

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
44
star
21

ethereumjs-block

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
42
star
22

ethereumjs-units

Ethereum unit conversion.
JavaScript
41
star
23

ethereumjs-connect

[DEPRECATED] Basic Ethereum connection tasks
JavaScript
36
star
24

eth-query

minimal rpc wrapper
JavaScript
28
star
25

node-devp2p

[DEPRECATED] A node.js implementation of the RLPx transport
28
star
26

ethereumjs-common

Project is in active development and has been moved to the EthereumJS VM monorepo.
TypeScript
26
star
27

rustbn.js

Rust to Javascript/Webassembly compilation of ethereum-bn128.rs.
HTML
20
star
28

node-devp2p-dpt

[DEPRECATED] Ethereum Distubted Peer Table Implementation
15
star
29

ethereumjs-ledger

[DEPRECATED] A wrapper library around the Ledger line of devices that attempts to simplify usage and handle various failure modes/problems.
TypeScript
14
star
30

ethereumjs-icap

Utilities for handling ICAP (Ethereum in IBAN) encoding
JavaScript
14
star
31

eth-bin-to-ops

[DEPRECATED] Simple utility for parsing binary evm code into opcodes
JavaScript
13
star
32

ethereum-verified-contracts

[DEPRECATED] Ethereum Verified Contracts
JavaScript
12
star
33

organization

A repo for discussions and other non-code organizing stuff
11
star
34

ethereumjs-testing

This utility library has been moved to the EthereumJS VM monorepo.
JavaScript
11
star
35

ethereumjs.github.io

Website for an intro to the EthereumJS ecosystem
CSS
10
star
36

ethereumjs-stub-rpc-server

Stub Ethereum JSON-RPC Server
JavaScript
9
star
37

node-ethash

Node bindings for the C++ Ethash implementation.
C++
7
star
38

fixed-bn.js

a bn.js wrapper that constrains numbers to a fixed width
TypeScript
7
star
39

ethereumjs-config

[DEPRECATED] Configuration is now added within a config folder of the EthereumJS monorepo
Shell
4
star
40

node-devp2p-eth

[DEPRECATED] Ethereum wire protocol implementation
3
star
41

sharding

Serenity phase 2 shard-chain PoC
WebAssembly
2
star
42

eth-bin-to-method-ids

[DEPRECATED] Extract the four byte method ids from evm byte code
JavaScript
2
star
43

rustbn-wasm

TypeScript
1
star
44

ethereumjs-collation

[DEPRECATED] Implementation of an Ethereum sharding collation
JavaScript
1
star
45

node-devp2p-rlpx

[DEPRECATED] Implements RLPx
1
star