Note

This documentation is under construction and the web3.js 1.0 stable version isn’t released. If your using a version v0.x.x of web3.js then please have a look at github.com/ethereum/wiki/wiki/JavaScript-API.

Admin Module

The web3-eth-admin package allows you to interact with the Ethereum node’s admin management.

import Web3 from 'web3';
import {Admin} from 'web3-eth-admin';

// "Web3.givenProvider" will be set if in an Ethereum supported browser.
const admin = new Admin(Web3.givenProvider || 'ws://some.local-or-remote.node:8546', null, options);

options

An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:

Example

import Web3 from 'web3';

const options = {
    defaultAccount: '0x0',
    defaultBlock: 'latest',
    defaultGas: 1,
    defaultGasPrice: 0,
    transactionBlockTimeout: 50,
    transactionConfirmationBlocks: 24,
    transactionPollingTimeout: 480,
    transactionSigner: new CustomTransactionSigner()
}

const web3 = new Web3('http://localhost:8545', null, options);

defaultBlock

web3.defaultBlock
web3.eth.defaultBlock
web3.shh.defaultBlock
...

The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.

Example:

Returns

The defaultBlock property can return the following values:

  • Number: A block number
  • "genesis" - String: The genesis block
  • "latest" - String: The latest block (current head of the blockchain)
  • "pending" - String: The currently mined block (including pending transactions)

Default is "latest"


defaultAccount

web3.defaultAccount
web3.eth.defaultAccount
web3.shh.defaultAccount
...

This default address is used as the default "from" property, if no "from" property is specified.

Returns

String - 20 Bytes: Any Ethereum address. You need to have the private key for that address in your node or keystore. (Default is undefined)


defaultGasPrice

web3.defaultGasPrice
web3.eth.defaultGasPrice
web3.shh.defaultGasPrice
...

The default gas price which will be used for a request.

Returns

string|number: The current value of the defaultGasPrice property.


defaultGas

web3.defaultGas
web3.eth.defaultGas
web3.shh.defaultGas
...

The default gas which will be used for a request.

Returns

string|number: The current value of the defaultGas property.


transactionBlockTimeout

web3.transactionBlockTimeout
web3.eth.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...

The transactionBlockTimeout will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens. This means the PromiEvent rejects with a timeout error when the timeout got exceeded.

Returns

number: The current value of transactionBlockTimeout


transactionConfirmationBlocks

web3.transactionConfirmationBlocks
web3.eth.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...

This defines the number of blocks it requires until a transaction will be handled as confirmed.

Returns

number: The current value of transactionConfirmationBlocks


transactionPollingTimeout

web3.transactionPollingTimeout
web3.eth.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...

The transactionPollingTimeout will be used over a HTTP connection. This option does define the amount of polls (each second) it should wait until the first confirmation happens.

Returns

number: The current value of transactionPollingTimeout


transactionSigner

web3.eth.transactionSigner
...

The transactionSigner property does provide us the possibility to customize the signing process of the Eth module and the related sub-modules.

The interface of a TransactionSigner:

interface TransactionSigner {
    sign(txObject: Transaction): Promise<SignedTransaction>
}

interface SignedTransaction {
    messageHash: string,
    v: string,
    r: string,
    s: string,
    rawTransaction: string
}

Returns

TransactionSigner: A JavaScript class of type TransactionSigner.


setProvider

web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...

Will change the provider for its module.

Note

When called on the umbrella package web3 it will also set the provider for all sub modules web3.eth, web3.shh, etc.

Parameters

  1. Object|String - provider: a valid provider
  2. Net - net: (optional) the node.js Net package. This is only required for the IPC provider.

Returns

Boolean

Example

import Web3 from 'web3';

const web3 = new Web3('http://localhost:8545');

// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path

// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\geth.ipc'
// on linux the path is: '/users/myuser/.ethereum/geth.ipc'

providers

Web3.providers
Eth.providers
...

Contains the current available providers.

Value

Object with the following providers:

  • Object - HttpProvider: The HTTP provider is deprecated, as it won’t work for subscriptions.
  • Object - WebsocketProvider: The Websocket provider is the standard for usage in legacy browsers.
  • Object - IpcProvider: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.

Example

const Web3 = require('web3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:8546'));

// Using the IPC provider in node.js
const net = require('net');

const web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\geth.ipc'
// on linux the path is: '/users/myuser/.ethereum/geth.ipc'

givenProvider

Web3.givenProvider
web3.eth.givenProvider
web3.shh.givenProvider
...

When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise null.

Returns

Object: The given provider set or false.

Example

web3.setProvider(Web3.givenProvider || 'ws://localhost:8546');

currentProvider

web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
...

Will return the current provider.

Returns

Object: The current provider set.

Example

if (!web3.currentProvider) {
    web3.setProvider('http://localhost:8545');
}

BatchRequest

new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
...

Class to create and execute batch requests.

Parameters

none

Returns

Object: With the following methods:

  • add(request): To add a request object to the batch call.
  • execute(): Will execute the batch request.

Example

const contract = new web3.eth.Contract(abi, address);

const batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);

addPeer

admin.addPeer(url, [callback])

Add an admin peer on the node that Web3 is connected to with its provider. The RPC method used is admin_addPeer.

Parameters

  1. url - String: The enode URL of the remote peer.
  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean> - True if peer added successfully.

Example

admin.addPeer("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303")
.then(console.log);
> true

getDataDirectory

admin.getDataDirectory([, callback])

Provides absolute path of the running node, which is used by the node to store all its databases. The RPC method used is admin_datadir.

Parameters

  1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<string> - The path.

Example

admin.getDataDirectory()
.then(console.log);
> "/home/ubuntu/.ethereum"

getNodeInfo

admin.getNodeInfo([, callback])

This property can be queried for all the information known about the running node at the networking granularity. The RPC method used is admin_nodeInfo.

Parameters

  1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<object> - The node information array.

  • enode - string: Enode address of the node.
  • id - string: Node Id.
  • listenAddr - string: lister host and port address.
  • name - string: Name of the node, including client type, version, OS, custom data
  • discovery - number: UDP listening port for discovery protocol
  • listener - number: TCP listening port for RLPx
  • difficulty - number: Difficulty level applied during the nonce discovering of this block.
  • genesis - string: Very first block hash.
  • head - string: Current block hash.
  • network - number: currently used Ethereum networks ids.

Example

admin.getNodeInfo().then(console.log);
> {
    enode: "enode://44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d@[::]:30303",
    id: "44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d",
    ip: "::",
    listenAddr: "[::]:30303",
    name: "Geth/v1.5.0-unstable/linux/go1.6",
    ports: {
        discovery: 30303,
        listener: 30303
    },
    protocols: {
        eth: {
        difficulty: 17334254859343145000,
        genesis: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
        head: "0xb83f73fbe6220c111136aefd27b160bf4a34085c65ba89f24246b3162257c36a",
        network: 1
        }
    }
}

getPeers

admin.getPeers([, callback])

This will provide all the information known about the connected remote nodes at the networking granularity. The RPC method used is admin_peers.

Parameters

  1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<Object> - List of all connected peers.

  • caps - Array: Protocols advertised by this peer.
  • id - string: Peer node Id.
  • name - string: Peer name of the node, including client type, version, OS, custom data
  • localAddress - string: Local endpoint of the TCP data connection.
  • remoteAddress - string: Remote endpoint of the TCP data connection.
  • difficulty - number: Difficulty level applied during the nonce discovering of this block.
  • head - string: Peer’s current block hash.
  • version - number: Version number of the protocol.

Example

admin.getPeers().then(console.log);
> [{
        caps: ["eth/61", "eth/62", "eth/63"],
        id: "08a6b39263470c78d3e4f58e3c997cd2e7af623afce64656cfc56480babcea7a9138f3d09d7b9879344c2d2e457679e3655d4b56eaff5fd4fd7f147bdb045124",
        name: "Geth/v1.5.0-unstable/linux/go1.5.1",
        network: {
            localAddress: "192.168.0.104:51068",
            remoteAddress: "71.62.31.72:30303"
        },
        protocols: {
            eth: {
                difficulty: 17334052235346465000,
                head: "5794b768dae6c6ee5366e6ca7662bdff2882576e09609bf778633e470e0e7852",
                version: 63
            }
        }
    }, /* ... */ {
        caps: ["eth/61", "eth/62", "eth/63"],
        id: "fcad9f6d3faf89a0908a11ddae9d4be3a1039108263b06c96171eb3b0f3ba85a7095a03bb65198c35a04829032d198759edfca9b63a8b69dc47a205d94fce7cc",
        name: "Geth/v1.3.5-506c9277/linux/go1.4.2",
        network: {
            localAddress: "192.168.0.104:55968",
            remoteAddress: "121.196.232.205:30303"
        },
        protocols: {
        eth: {
            difficulty: 17335165914080772000,
            head: "5794b768dae6c6ee5366e6ca7662bdff2882576e09609bf778633e470e0e7852",
            version: 63
        }
    }
}]

setSolc

admin.setSolc(string, [, callback])

Sets the Solidity compiler path to be used by the node when invoking the eth_compileSolidity RPC method The RPC method used is admin_setSolc.

Parameters

  1. String - The path of the solidity compiler.
  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<string> - A message.

Example

admin.setSolc("/usr/bin/solc").then(console.log);
> "solc, the solidity compiler commandline interface\nVersion: 0.3.2-0/Release-Linux/g++/Interpreter\n\npath: /usr/bin/solc"

startRPC

admin.startRPC(host, port, cors, apis [, callback])

It starts an HTTP based JSON RPC API webserver to handle client requests. All the parameters are optional. The RPC method used is admin_startRPC.

Parameters

  1. host - String - (optional) The network interface to open the listener socket on (defaults to “localhost”).
  2. port - number - (optional) The network port to open the listener socket on (defaults to 8545).
  3. cors - string - (optional) Cross-origin resource sharing header to use (defaults to “”).
  4. apis - string - (optional) API modules to offer over this interface (defaults to “eth,net,web3”).
  5. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean> - True if Remote Procedure Call (RPC) got started.

Example

admin.startRPC("127.0.0.1", 8545)
.then(console.log('RPC Started!'));
> "RPC Started!"

startWS

admin.startWS(host, port, cors, apis [, callback])

It starts an WebSocket based JSON RPC API webserver to handle client requests. All the parameters are optional. The RPC method used is admin_startWS.

Parameters

  1. host - String - (optional) The network interface to open the listener socket on (defaults to “localhost”).
  2. port - number - (optional) The network port to open the listener socket on (defaults to 8545).
  3. cors - string - (optional) Cross-origin resource sharing header to use (defaults to “”).
  4. apis - string - (optional) API modules to offer over this interface (defaults to “eth,net,web3”).
  5. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean> - True if Web socket (WS) got started.

Example

admin.startRPC("127.0.0.1", 8546)
.then(console.log('WS Started!'));
> "WS Started!"

stopRPC

admin.stopRPC([, callback])

This method closes the currently open HTTP RPC endpoint. As the node can only have a single HTTP endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not. The RPC method used is admin_stopRPC.

Parameters

  1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean> - True if Remote Procedure Call (RPC) successfully stopped.

Example

admin.stopRPC().then(console.log);
> true

stopWS

admin.stopWS([, callback])

This method closes the currently open WebSocket RPC endpoint. As the node can only have a single WebSocket endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not. The RPC method used is admin_stopWS.

Parameters

  1. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean> - True if Web Socket (WS) successfully stopped.

Example

admin.stopWS().then(console.log);
> true