Welcome to Browseth’s documentation!

Quickstart

Browseth quickstart for those already familiar with Ethereum development. New to Ethereum? Check out the getting-started.


Installation

From your project directory:

yarn add browseth

Import inside relevant project files:

import Browseth from 'browseth'

Initializing Browseth

Initialize Browseth with an Ethereum RPC url or web3 instance.

By default, Browseth uses http://localhost:8545.

const beth = new Browseth("https://mainnet.infura.io")
// or
const beth = new Browseth(window.web3)

Getting Started

Browseth is a simple JavaScript library for Ethereum.


Installation

From your project directory:

yarn add browseth

Import inside relevant project files:

import Browseth from 'browseth'

Choosing an Ethereum RPC (Remote Procedure Call)

An Ethereum RPC is your gateway to interacting with Ethereum.

Ethereum nodes have the option to expose a JSON RPC allowing developers to interact with the Ethereum network.

A local Ethereum node usually exposes a JSON RPC at port 8545. There are services like Infura that provide a public JSON RPC for developers.

Initializing Browseth

Initialize Browseth with an Ethereum RPC url or web3 instance.

By default, Browseth uses http://localhost:8545.

const beth = new Browseth("https://mainnet.infura.io")
// or
const beth = new Browseth(window.web3)

Now Browseth is connected to the Ethereum network!

Types of Requests

There are two types of requests to Ethereum: read and writes.

A call request is free to call but may not add, remove, or change any data in the blockchain.

A send request requires a network fee, but may change the state of the blockchain. These methods must be made by a transaction and mined before any changes to the state are made. So these methods are subject to fluctuating gas prices, network congestion, and miner heuristics.

Signers

Signers are required to make send requests.

The following signer types are supported: private key, ledger, and online.

import PrivateKeySigner from '@browseth/signer-private-key'
import SignerLedger from '@browseth/signer-ledger'

beth.useSignerAccount(new PrivateKeySigner(PRIVATE_KEY));
beth.useSignerAccount(new SignerLedger());

Units

Unit conversion library

import * as units from '@browseth/units';

You can also import specific functions

import {etherToWei, conversion} from '@browseth/units';

units . convert ( fromUnit, value, toUnit )
convert unit of value to unit
units . etherToWei ( value )
convert value in ether to wei
units . gweiToWei ( value )
convert value in gwei to wei
units . weiToEther ( value )
convert value in wei to ether
units . toWei ( fromUnit, value )
convert unit of value to wei
units . toEther ( fromUnit, value )
convert unit of value to ether
units . unitToPow ( unit )
returns the power of the unit relative to wei
Supported Units:
wei, kwei, ada, femtoether, mwei, babbage, picoether, gwei, shannon, nanoether, nano, szabo, microether, micro, finney, milliether, milli, ether, kether, grand, einstein, mether, gether, tether

Utilities

const utils = require('@browseth/utils');

or

import utils from '@browseth/utils';

Array Buffers

An Array Buffer is an Array Buffer.

utils.ab . isBytes ( value [, length] )
Checks to see if value is bytes and if it matches optional length
utils.ab . fromView ( view )
Returns an Array Buffer from view
utils.ab . fromBytes ( value [, length] )
Returns Array Buffer from bytes with optional length
utils.ab . fromUtf8 ( value )
Returns Array Buffer from fromUtf8
utils.ab . fromUInt ( value )
Returns Array Buffer from UInt
utils.ab . toUf8 ( value )
Converts Array Buffer into Utf8
utils.ab . toTwos ( value, size )
Converts Array Buffer into a two’s compliment
utils.ab . stripStart ( value )
Strips out the start of an Array Buffer
utils.ab . padStart ( value, length [, fillByte] )
Pads the start of an Array Buffer
utils.ab . padEnd ( value, length [, fillByte] )
Pads the end of an Array Buffer
utils.ab . concat ( values )
Concats an array of Array Buffers

Address

Utilities for manipulating addresses

utils.address . isValid ( value )
Checks if the given value is a valid address
utils.address . from ( value )
Returns an address from bytes
utils.address . fromAddressAndNonce ( address, nonce )
Returns an address from an address and nonce

Crypto

utils.crypto . keccak256 ( value )
returns the keccak256 of a string
utils.crypto . uuid ( value )
TODO: uuid is meant for internal use. Not working externally yet. returns the uuid of a string

Interval

utils.interval . setUnrefedInterval ( fn, delay [, args] )
Sets an interval that dies when the function it’s wrapped in is finished
utils.interval . setUnrefedTimeout ( fn, delay [, args] )
Sets a timeout that dies when the function it’s wrapped in is finished

Param

utils.param . toData ( value, length )
Converts parameters to hex
utils.param . toQuantity ( value )
Converts parameters to hex string quantity
utils.param . toTag ( value )
Converts value into a tag
utils.param . isData ( value [, length] )
Checks if value is data of optional length
utils.param . isQuantity ( value )
Checks if value is a quantity
utils.param . isTag ( value )
Checks if value is a tag
utils.param . fromData ( value, length )
Converts value to uint8Array of length
utils.param . fromQuantity ( value )
Converts quantity to Big Number
utils.param . fromTag ( value )
Converts tag to Big Number

RLP

RLP (Recursive Length Prefix) is the main encoding method used to serialize objects in Ethereum

utils.rlp . encode ( value )
Encodes value to Array Buffer
utils.rlp . encodeLength ( len, offset )
Encodes length to Array Buffer with offset

Block Tracker

Poll for blocks every 5 seconds until a block number is confirmed. Use this class to keep track of block(s). Contains #emitter.

Creating Instances

new Browseth.utils . BlockTracker ( requestQueue [, confirmationDelay = 0] )
Request queue is an eth reference. The confirmation delay is the minimum number of confirmed blocks until the block is considered confirmed.

Prototype

prototype . addTracker ( key [, options] )

Track a block.

Options may have the following properties:

  • synced – ‘latest’, ‘earliest’, or block # to track (defaults to ‘latest’)
  • confirmationDelay – minimum # of confirmed blocks until tracked block is considered confirmed
prototype . syncBlockNumber ( )

Sets the latest block number

emits ‘block.number’ with block # passed to the event callback

See #emitter

prototype . syncBlocks ( )

Syncs blocks to latest block

emits ‘block’ for every synced block - block is passed to the event callback

See #emitter

Transaction Listener

Monitor transactions

Creating Instances

new Browseth.utils . TxListener ( ethRef )
Create new TxListener object with eth reference.

Prototype

prototype . listen ( txHash ): <Promise>

Listen for a transaction until it is mined. Returns a promise that resolves to a transaction receipt.

If the listener does not see a receipt after 30 minutes it throws assuming the transaction has been dropped from the network

Example
import Browseth from '@browseth/browser'

const beth = new Browseth('https://mainnet.infura.io');
beth.useOnlineAccount();

const txListener = new Browseth.utils.TxListener(beth);

txListener.listen(txHash)
    .then(receipt => console.log(receipt))
    .catch(e => console.log('Transaction dropped!'))

Observable

Subscribe to value changes with callbacks

Creating Instances

new Browseth.utils . Observable ( value )
Create new Observable object with the value to watch.

Prototype

prototype . subscribe ( fn )
Add function to list of callbacks on value change. returns function to used unsubscribe function
prototype . set ( newValue )
Set the new value to watch. Triggers subscribed functions
prototype . get ( )
Gets the current watched value.
Example
const observable = new Browseth.utils.Observable('123');

const unsubscribe = observable.subscribe(() => console.log('This is an example'));

observable.set('456');  // Sets new value and logs 'This is an example'

unsubscribe(); // unsubscribe earlier subscribed function

observable.set('78'); // Will set new value with no callbacks

observable.get(); // returns '78'

Emitter

Add events with callbacks and trigger those callbacks by emitting events.

Creating Instances

new Browseth.utils . Emitter ( )
Create new Emitter object.

Prototype

prototype . on ( event, fn )
Add event label and provide callback
prototype . off ( event, fn )
Remove callback from an event
prototype . onEvery ( fn )
Provide callback for every emit
prototype . emit ( event [, params] )
Emit an event and pass parameters to the callbacks
Example
const emitter = new Browseth.utils.Emitter('123');

emitter.on('test', () => console.log('example'));

emitter.onEvery(() => console.log('example2'));

emitter.emit('test') // Console logs 'example' and 'example2'

Contract

There are two types of methods that can be called on a Contract:

A call method may not add, remove or change any data in the storage. These methods are free to call.

A send method requires a fee, but may change the state of the blockchain or any data in the storage. These methods must be made by a transaction and mined before any changes to the state are made. Therefore, these methods are subject to fluctuating gas prices, network congestion, and miner heuristics.

import Contract from '@browseth/contract';

Creating Instances

new Contract ( ethRef, contractAbi [, options] )

Options may have the properties:

  • bin — contract binary (required for contract deployment)
  • address — address of already deployed contract - .send() and .call() will default to this for the {to: address} option

Deploying Contracts

prototype . construct ( [params] )
Takes in constructor parameters for the deploying contract returns send() and gas() methods
. send ( [options] )
deploys contract and returns transaction hash
. gas ( [options] )

returns the estimated gas for deploying the contract

Options may have the properties:

  • chainId — set contract binary for contract deployment
  • gasPrice — set gas price in wei for transaction
  • gas — sets the max amount of gas for the transaction
import Browseth from '@browseth/browser'
import Contract from '@browseth/contract'
import PrivateKeySigner from '@browseth/signer-private-key'

const beth = new Browseth(eth_rpc);
beth.useSignerAccount(new PrivateKeySigner(PRIVATE_KEY));

const contractInstance = new Contract(beth, contract.abi, {bin: contract.bin});
const txHash = await contractInstance.construct().send({ gasPrice: 10000000000});

ENS

Ethereum Name Service (ENS) library for name lookup and standard resolver interface reading.

import EnsLookup from '@browseth/units';

Creating Instances

new EnsLookup ( ethRef )
Initialize EnsLookup object with browseth instance

Prototype

prototype . resolverAddress ( node )
Returns the address of the node’s resolver
prototype . address ( node )
Returns the address field set in the node’s resolver
prototype . name ( node )
Returns the name set in the node’s resolver
prototype . text ( node, key )
Returns the text of a key in the node’s resolver
prototype . supportsInterface ( node, interfaceId )
Checks if the interfaceId is supported by the node’s resolver

Signers

A Signer manages a private/public key pair which is used to cryptographically sign transactions and prove ownership on the Ethereum network.


Private Key Signer

const PrivateKeySigner = require('@browseth/signer-private-key')

or

import PrivateKeySigner from '@browseth/signer-private-key'

Creating Instances

new PrivateKeySigner ( privateKey )
Creates a private key signer object from privateKey

Prototype

prototype . address ( )
Returns the address of the signer generated from the privateKey
prototype . signMessage ( message )
Returns a signed message
prototype . signTransaction ( [params] )

Returns a signed transaction

Parameters may include:

  • to
  • gasPrice
  • gasLimit
  • nonce
  • data
  • value
  • chainId