API Reference TS/JS

Even though the IN3 client is written in C, we are using emscripten to build wasm. Together with some binding-code IN3 runs in any Javascript-Runtime. Using WASM gives us 3 important features:

  1. Performance. Since WASM runs at almost native speed it is very fast
  2. Security Since the WASM-Module has no dependencies it reduces the risk of using a malicious dependency, which would be able to manipulate Prototypes. Also, since the real work is happening inside the wasm, trying to change Prototype would not work.
  3. Size The current wasm-file is about 200kb. This is smaller then most other libraries and can easily be used in any app or website.

Installing

This client uses the in3-core sources compiled to wasm. The wasm is included into the js-file wich makes it easier to include the data. This module has no dependencies! All it needs is included inta a wasm of about 300kB.

Installing IN3 is as easy as installing any other module:

npm install --save in3

WASM-support

Even though most browsers and javascript enviroment such as nodejs, have full support for wasm, there are ocasions, where WASM is fully supported. In case you want to run IN3 within a react native app, you might face such issues. In this case you can use in3-asmjs, which has the same API, but runs on pure javascript (a bit slower and bigger, but full support everywhere).

Building from Source

install emscripten

In order to build the wasm or asmjs from source you need to install emscripten first. In case you have not done it yet:

# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git

# Enter that directory
cd emsdk

# install the latest-upstream sdk and activate it
./emsdk install latest-upstream && ./emsdk activate latest-upstream
# Please make sure you add this line to your .bash_profile or .zshrc
source <PATH_TO_EMSDK>/emsdk_env.sh > /dev/null

CMake

With emscripten set up, you can now configure the wasm and build it (in the in3-c directory):

# create a build directory
mkdir -p build
cd build

# configure CMake
emcmake cmake -DWASM=true -DCMAKE_BUILD_TYPE=MINSIZEREL ..

# and build it
make -j8 in3_wasm

# optionally you can also run the tests
make test

Per default the generated wasm embedded the wasm-data as base64 and resulted in the build/module. If you want to build asmjs, use the -DASMJS=true as an additional option. If you don’t want to embedd the wasm, add -DWASM_EMBED=false. If you want to set the -DCMAKE_BUILD_TYPE=DEBUG your filesize increases but all function names are kept (resulting in readable stacktraces) and emscriptten will add a lot of checks and assertions.

For more options please see the CMake Options.

Examples

get_block_api

source : in3-c/wasm/examples/get_block_api.ts

Reads the latest block by calling IN3’s web3.js-compatible eth API. Read the eth api from web3.js docs: https://web3js.readthedocs.io/en/v1.3.0/web3-eth.html

/// Reads the latest block by calling IN3's web3.js-compatible eth API.
/// Read the eth api from web3.js docs: https://web3js.readthedocs.io/en/v1.3.0/web3-eth.html
import { IN3 } from 'in3'

async function showLatestBlock() {

  // create new IN3 instance
  const client = new IN3({
    proof              : 'standard',
    signatureCount     : 1,
    chainId            : 'goerli'
  })

  const lastBlock = await client.eth.getBlockByNumber()

  console.log("latest Block: ", JSON.stringify(lastBlock, null, 2))

}

showLatestBlock().catch(console.error)

get_block_rpc

source : in3-c/wasm/examples/get_block_rpc.ts

Reads the latest block by calling IN3’s internal RPC to the WASM core. Learn other exclusive IN3 RPC calls here: https://in3.readthedocs.io/en/develop/rpc.html

/// Reads the latest block by calling IN3's internal RPC to the WASM core.
/// Learn other exclusive IN3 RPC calls here: https://in3.readthedocs.io/en/develop/rpc.html
import { IN3 } from 'in3'

async function showLatestBlock() {

    // create new IN3 instance
    var c = new IN3({
        chainId: '0x5' // use goerli
    })

    // make a RPC (this would throw if the response contains an error)
    const lastBlockResponse = await c.sendRPC('eth_getBlockByNumber', ['latest', false])

    console.log("latest Block: ", JSON.stringify(lastBlockResponse, null, 2))

}

showLatestBlock().catch(console.error)

register_pugin

source : in3-c/wasm/examples/register_pugin.ts

// Register a custom RPC for sha256 hashing using a plugin
// Read about IN3 Plugins in the docs: https://in3.readthedocs.io/en/develop/api-c.html#plugins
import { IN3, RPCRequest, IN3Plugin } from 'in3'
import * as crypto from 'crypto'

class Sha256Plugin<BigIntType, BufferType> implements IN3Plugin<BigIntType, BufferType> {

  // this function will register for handling rpc-methods
  // only if we return something other then `undefined`, it will be taken as the result of the rpc.
  // if we don't return, the request will be forwarded to the IN3 nodes
  handleRPC(client, request: RPCRequest): any {

    if (request.method === 'sha256') {
      // assert params
      if (request.params.length != 1 || typeof (request.params[0]) != 'string')
        throw new Error('Only one parameter with as string is expected!')

      // create hash
      const hash = crypto.createHash('sha256').update(Buffer.from(request.params[0], 'utf8')).digest()

      // return the result
      return '0x' + hash.toString('hex')
    }
  }

}

async function registerPlugin() {

  // create new IN3 instance
  const client = new IN3()

  // register the plugin
  client.registerPlugin(new Sha256Plugin())

  // exeucte a rpc-call
  const result = await client.sendRPC("sha256", ["testdata"])

  console.log(" sha256: ", result)

}

registerPlugin().catch(console.error)

use_web3

source : in3-c/wasm/examples/use_web3.ts

use IN3 as Web3Provider in web3.js

/// use IN3 as Web3Provider in web3.js
import {IN3} from 'in3'

const Web3 = require('web3')

const in3 = new IN3({
    proof: 'standard',
    signatureCount: 1,
    requestCount: 1,
    chainId: 'goerli',
    replaceLatestBlock: 10
})

// Use IN3 network client as a Http-Provider
const web3 = new Web3(in3.createWeb3Provider());

(async () => {
    const block = await web3.eth.getBlock('latest')
    console.log("Block : ", block)
})().catch(console.error);

in3_in_browser

source : in3-c/wasm/examples/in3_in_browser.html

use IN3 in html

<!-- use IN3 in html -->
<html>

<head>
    <script src="node_modules/in3/index.js"></script>
</head>

<body>
    IN3-Demo
    <div>
        result:
        <pre id="result"> ...waiting... </pre>
    </div>
    <script>
        var in3 = new IN3({ chainId: 0x1, replaceLatestBlock: 6, requestCount: 3 });
        in3.eth.getBlockByNumber('latest', false)
            .then(block => document.getElementById('result').innerHTML = JSON.stringify(block, null, 2))
            .catch(alert)
    </script>
</body>

</html>

Building

In order to run those examples, you need to install in3 and typescript first. The build.sh will do this and the run the tsc-compiler

./build.sh

In order to run a example use

node build/get_block_api.ts

Incubed - from Typescript to WASM

When we started to implement Incubed, it all began with a Proof of Concept. This was implemented in Typescript and showed that it was possible to verify all important ethereum rpc-requests. Out of thie PoC we continued to develop the first release of the Typescript Client at Devcon 2017. But the goal of incubed was always to be able to run in embedded devices with minimal specs (256kB RAM), so we started to implement the incubed client in C from scratch.

Why C? (not Rust?)

Don’t get me wrong, I love Rust and in the beginning this seemed the best way to implement it, but when looking at our target platforms (embeded devices) you soon find out that almost all of them use C or C++. It would be way easier to get a C-developer to inculde a C-Library than to change its toolchain to include Rust. Also at that time Rust was not ready for embedded yet. „Integrating Rust with an RTOS such as FreeRTOS or ChibiOS is still a work in progress; especially calling RTOS functions from Rust can be tricky.“ (https://rust-embedded.org) When we looked at Stackoverflow Developer Survey 2019 for the most loved Language, 83% of developers made Rust the #1, but looking at the results for actually usage, only 3% used Rust in their products. Another reason was the fact, that if you write code in C it will run everywhere. Especially embedded devices like to come with their own toolchain only supporting C/C++.

Size matters

While most Dektop-PCs are powerful enough so you wouldn’t care how big a library is, there are still 2 platforms, where size matters a lot:

  1. Browsers - when including it in a webapp each user needs to download the code. So having a small library means a faster and better user experience.
  2. Embedded Devices - if you only have 1MB flash memory you simply can’t use huge libraries.

The smallest possible incubed client is around 300kb including a full evm and running on devices with about 100kB RAM.

Emscripten

With Incubed implemented in C we used emscripten to compile it to WASM. This allows us to run almost at native speed in the browser. While almost all browsers support WASM, yet there are still JS-Engines without WebAssembly-Support. Luckely emscripten is able to compile it to asmjs as well, which allows us to also run ( a bit slower and bigger ) even there (which by the way includes react native !).

Security - no dependencies

Packing all in one wasm-file is not only creating a very compact size (The minimal wasm-size is 162kB), but also is a lot safer. When you look at your node_modules-folder after installing the old typescript-client, you would find 267 packages from various authors. if you do the same with the wasm-client version 3.2 now, you will find only one folder : in3. Yes, We are very proud of our library with ZERO dependencies! Why are dependencies bad? According to a security survey by npm, 77% of respondents were concerned with the security of OSS/third-party code. Especially when writing security critical applications, auditing all even nested dependencies is very hard. (Remember when an innocent package like event-stream became malicious and got downloaded 8 Million times? )

How to migrate?

For the WASM-Client we tried to keep the API as close as possible to the old TypeScript-Version, but due to new features and some WASM-specific behaviors there are some changes you need to be aware of:

  1. WASM loads async Since WebAssembly is always loaded async, some function (like special util-functions) may not be available if you execute code directly after requiring the client. For all those cases the Incubed-Client now offers a onInit-function, which also returns a promis with the result. ( his is not be needed for normale rpc-request, since they are already async)

    import IN3 from 'in3'
    
    // the code will be executed as soon as the client is ready (wasm loaded)
    IN3.onInit(()=>{
        console.log(' Address :  ',  IN3.util.toChecksumAddress('0xb3b7874f13387d44a3398d298B075b7a3505d8d4'))
    })
    
  2. Freeing Memory As every C/C++-Developer knows, in order to avoid memory leaks, you need to free memory after usage. While it may not make a big difference if you only use one instance, if you create a temp instance, make sure to call .free() afterwards.

  3. Deprecated Functions We removed a lot of internal functions from the Client, like

    • getChainContext()
    • updateWhiteListNodes()
    • updateNodeList()
    • call()
    • verifyResponse()
    • clearStats()
    • addListener()

    On the other hand we also added some useful functions, like

    • setConfig(config: Partial<IN3Config>) - changes (partial) configurations
    • execLocal(method: string, params?: any[]) - to execute a rpc request synchronously directly in the client, like ( web3_version or )
  4. Changes in the Eth-API We extended the Eth-API (in3.eth) and added the following functions.

    • accounts - the Account API for adding signer keys
    • toWei() - converts any value and unit to wei as hex.
    • resolveENS() - ENS-Resolver
    • web3ContractAt() - creates a instance of a Contract with the same methods as web3 would do
    • contractAt()- creates a instance of an contract with the same methods as ethers would do
  5. New APIs

    • btc- this API support verified Bitcoin-Responses ( we will have a seperate blogpost about it )
    • zksync - API for using a zksync-service

Optimizing size

The official in3-module release contains different configurations you can choose from. This way you can pick a version which is just small enough to fit your needs. Currently those Versions are included:

  • require('in3') - default, uses asmjs and includes all modules (eth,btc, zksync) - 900kB
  • require('in3/wasm') - wasm-version which includes all modules (eth,btc, zksync) - 525kB
  • require('in3/eth1') - Ethereum only asmjs module - 823kB
  • require('in3/eth1-wasm') - Ethereum only wasm module - 470kB
  • require('in3/btc') - Bitcoin - the asmjs-version with only eth_nano and btc - 656kB
  • require('in3/btc-wasm') - Bitcoin - the wasm-version with only eth_nano and btc - 400kB
  • require('in3/zksync') - Zksync - the asmjs-version with only eth_full, ipfs and zksync - 2.8MB
  • require('in3/zksync-wasm') - Zksync - the wasm-version with only eth_full, ipfs and zksync - 819kB
  • require('in3/min') - Minimal - the asmjs-version with only eth_nano - 524kB
  • require('in3/min-wasm') - Minimal - the wasm-version with only eth_nano - 313kB

For all wasm-versions we are embedding the wasm-code as base64 directly into the code making it easier to bundle the package.

IN3 Module

This page contains a list of all Datastructures and Classes used within the IN3 WASM-Client

Importing IN3 is as easy as

import {IN3} from "in3"

BufferType and BigIntType

The WASM-Module comes with no dependencies. This means per default it uses the standard classes provided as part of the EMCAScript-Standard.

If you work with a library which expects different types, you can change the generic-type and giving a converter:

Type BigIntType

Per default we use bigint. This is used whenever we work with number too big to be stored as a number-type.

If you want to change this type, use setConverBigInt() function.

Type Buffer

Per default we use UInt8Array. This is used whenever we work with raw bytes.

If you want to change this type, use setConverBuffer() function.

Generics

import {IN3Generic} from 'in3'
import BN from 'bn.js'

// create a new client by setting the Generic Types
const c = new IN3Generic<BN,Buffer>()

// set the converter-functions
IN3Generic.setConverBuffer(val => Buffer.from(val))
IN3Generic.setConverBigInt(val => new BN(val))

Package

While the In3Client-class is also the default import, the following imports can be used:

Class
default Incubed client with
bigint for big numbers
Uint8Array for bytes
Class
the IN3Generic
Class
the SimpleSigner
Interface
The Account API
Interface
a full Block including the transactions
Interface
a Block header
Interface
Block state.
Interface
API for handling BitCoin data
Interface
a BitCoin Transaction.
Interface
a Input of a Bitcoin Transaction
Interface
a Input of a Bitcoin Transaction
Interface
Response of a Deposit-Transaction.
Interface
L1 Operation State
Interface
The API for ethereum operations.
Interface
fee collection.
Interface
the configuration of the IN3-Client. This can be changed at any time.
All properties are optional and will be verified when sending the next request.
Interface
a configuration of a in3-server.
Interface
a local weight of a n3-node. (This is used internally to weight the requests)
Interface
a Incubed plugin.

Depending on the methods this will register for those actions.

Interface
API for storing and retrieving IPFS-data.
Interface
a JSONRPC-Request with N3-Extension
Interface
a JSONRPC-Responset with N3-Extension
Interface
the Signer
Interface
Token representation
Interface
Token List.
Interface
Transaction state
Interface
Defines the type of a transaction.
Interface
Collection of different util-functions.
Interface
the Web3Contract
Interface
the Web3Event
Interface
the Web3TransactionObject
Interface
return structure after fetching the current account info.
Interface
API for zksync.
Type literal
the ABI
Type literal
the ABIField
Type alias
a 20 byte Address encoded as Hex (starting with 0x)
Type literal
the Block
Type
BlockNumber or predefined Block
Type alias
data encoded as Hex (starting with 0x)
Type alias
a 32 byte Hash encoded as Hex (starting with 0x)
Type
a Hexcoded String (starting with 0x)
Type literal
the Log
Type literal
the LogFilter
Type
a BigInteger encoded as hex.
Type literal
Signature
Type literal
the Transaction
Type literal
the TransactionDetail
Type literal
a Receipt of a Transaction containing the events and execution status
Type literal
the TxRequest
Interface
bitcoin configuration.
Interface
zksync configuration.

Package index

Type IN3

Source: index.d.ts

default Incubed client with bigint for big numbers Uint8Array for bytes

supporting both ES6 and UMD usage
collection of util-functions.
btc API
IN3 config
eth1 API.
ipfs API
the signer, if specified this interface will be used to sign transactions, if not, sending transaction will not be possible.
collection of util-functions.
zksync API

freeAll()

frees all Incubed instances.

static void freeAll ()

onInit()

registers a function to be called as soon as the wasm is ready. If it is already initialized it will call it right away.

static Promise<T> onInit (
fn:() => T )

Parameters:

fn
() => T
the function to call

Returns:

static Promise<T>

setConvertBigInt()

sets the convert-function, which converts any kind of type to Type defined for BigInt-operation. if not set the default type would be bigint.

static void setConvertBigInt (
convert:(any) => any)

Parameters:

convert
(any) => any
convert

setConvertBuffer()

sets the convert-function, which converts any kind of type to Type defined for Buffer or Bytes-operation. if not set the default type would be UInt8Array.

static void setConvertBuffer (
convert:(any) => any)

Parameters:

convert
(any) => any
convert

setStorage()

changes the storage handler, which is called to read and write to the cache.

static void setStorage (
handler:)

Parameters:

handler

handler

setTransport()

changes the default transport-function.

static void setTransport (
fn:(string , string , number) => Promise<string>)

Parameters:

fn
(string , string , number) => Promise<string>
the function to fetch the response for the given url

constructor()

creates a new client.

IN3 constructor (
config:Partial<IN3Config> )

Parameters:

config
a optional config

Returns:

IN3

createWeb3Provider()

returns a Object, which can be used as Web3Provider.

const web3 = new Web3(new IN3().createWeb3Provider())

any createWeb3Provider ()

Returns:

any

execLocal()

sends a RPC-Requests specified by name and params as a sync call. This is only alowed if the request is handled internally, like web3_sha3,

if the response contains an error, this will be thrown. if not the result will be returned.

any execLocal (
method:string, params:any [])

Parameters:

method
string
the method to call.

params
any []
params

Returns:

any

free()

disposes the Client. This must be called in order to free allocated memory!

void free ()

registerPlugin()

rregisters a plugin. The plugin may define methods which will be called by the client.

void registerPlugin (
plugin:IN3Plugin<bigint,Uint8Array> )

Parameters:

plugin
the plugin-object to register

send()

sends a raw request. if the request is a array the response will be a array as well. If the callback is given it will be called with the response, if not a Promise will be returned. This function supports callback so it can be used as a Provider for the web3.

Promise<RPCResponse> send (
request:RPCRequest , callback:(Error , RPCResponse ) => void)

Parameters:

request
a JSONRPC-Request with N3-Extension
callback
(Error , RPCResponse ) => void
callback

Returns:

Promise<RPCResponse>

sendRPC()

sends a RPC-Requests specified by name and params.

if the response contains an error, this will be thrown. if not the result will be returned.

Promise<any> sendRPC (
method:string, params:any [])

Parameters:

method
string
the method to call.

params
any []
params

Returns:

Promise<any>

setConfig()

sets configuration properties. You can pass a partial object specifieing any of defined properties.

void setConfig (
config:Partial<IN3Config> )

Parameters:

config
config

Type IN3Generic

Source: index.d.ts

supporting both ES6 and UMD usage
collection of util-functions.
btc API
IN3 config
eth1 API.
ipfs API
the signer, if specified this interface will be used to sign transactions, if not, sending transaction will not be possible.
collection of util-functions.
zksync API

freeAll()

frees all Incubed instances.

static void freeAll ()

onInit()

registers a function to be called as soon as the wasm is ready. If it is already initialized it will call it right away.

static Promise<T> onInit (
fn:() => T )

Parameters:

fn
() => T
the function to call

Returns:

static Promise<T>

setConvertBigInt()

sets the convert-function, which converts any kind of type to Type defined for BigInt-operation. if not set the default type would be bigint.

static void setConvertBigInt (
convert:(any) => any)

Parameters:

convert
(any) => any
convert

setConvertBuffer()

sets the convert-function, which converts any kind of type to Type defined for Buffer or Bytes-operation. if not set the default type would be UInt8Array.

static void setConvertBuffer (
convert:(any) => any)

Parameters:

convert
(any) => any
convert

setStorage()

changes the storage handler, which is called to read and write to the cache.

static void setStorage (
handler:)

Parameters:

handler

handler

setTransport()

changes the default transport-function.

static void setTransport (
fn:(string , string , number) => Promise<string>)

Parameters:

fn
(string , string , number) => Promise<string>
the function to fetch the response for the given url

constructor()

creates a new client.

IN3Generic constructor (
config:Partial<IN3Config> )

Parameters:

config
a optional config

Returns:

IN3Generic

createWeb3Provider()

returns a Object, which can be used as Web3Provider.

const web3 = new Web3(new IN3().createWeb3Provider())

any createWeb3Provider ()

Returns:

any

execLocal()

sends a RPC-Requests specified by name and params as a sync call. This is only alowed if the request is handled internally, like web3_sha3,

if the response contains an error, this will be thrown. if not the result will be returned.

any execLocal (
method:string, params:any [])

Parameters:

method
string
the method to call.

params
any []
params

Returns:

any

free()

disposes the Client. This must be called in order to free allocated memory!

void free ()

registerPlugin()

rregisters a plugin. The plugin may define methods which will be called by the client.

void registerPlugin (
plugin:IN3Plugin<BigIntType,BufferType> )

Parameters:

plugin
the plugin-object to register

send()

sends a raw request. if the request is a array the response will be a array as well. If the callback is given it will be called with the response, if not a Promise will be returned. This function supports callback so it can be used as a Provider for the web3.

Promise<RPCResponse> send (
request:RPCRequest , callback:(Error , RPCResponse ) => void)

Parameters:

request
a JSONRPC-Request with N3-Extension
callback
(Error , RPCResponse ) => void
callback

Returns:

Promise<RPCResponse>

sendRPC()

sends a RPC-Requests specified by name and params.

if the response contains an error, this will be thrown. if not the result will be returned.

Promise<any> sendRPC (
method:string, params:any [])

Parameters:

method
string
the method to call.

params
any []
params

Returns:

Promise<any>

setConfig()

sets configuration properties. You can pass a partial object specifieing any of defined properties.

void setConfig (
config:Partial<IN3Config> )

Parameters:

config
config

Type SimpleSigner

Source: index.d.ts


the accounts

constructor()

constructor

SimpleSigner constructor (
pks:string | BufferType [])

Parameters:

pks
string | BufferType []
pks

Returns:

SimpleSigner

prepareTransaction()

optiional method which allows to change the transaction-data before sending it. This can be used for redirecting it through a multisig.

Promise<Transaction> prepareTransaction (
client:IN3Generic<BigIntType,BufferType> , tx:Transaction )

Parameters:

Returns:

Promise<Transaction>

sign()

signing of any data. if hashFirst is true the data should be hashed first, otherwise the data is the hash.

Promise<BufferType> sign (
data:Hex , account:Address , hashFirst:boolean, ethV:boolean)

Parameters:

data
a Hexcoded String (starting with 0x)
account
a 20 byte Address encoded as Hex (starting with 0x)
hashFirst
boolean
hash first
ethV
boolean
eth v

Returns:

Promise<BufferType>

addAccount()

adds a private key to the signer and returns the address associated with it.

string addAccount (
pk:Hash )

Parameters:

pk
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

string

canSign()

returns true if the account is supported (or unlocked)

Promise<boolean> canSign (
address:Address )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)

Returns:

Promise<boolean>

getAccounts()

returns all addresses managed by the signer.

Address [] getAccounts ()

Returns:

Address []

Type AccountAPI

Source: index.d.ts

The Account API

add()

adds a private key to sign with. This method returns address of the pk

Promise<string> add (
pk:string | BufferType )

Parameters:

pk
string | BufferType


Returns:

Promise<string>

Type BTCBlock

Source: index.d.ts

a full Block including the transactions

string
bits (target) for the block as hex
string
total amount of work since genesis
number
number of confirmations or blocks mined on top of the containing block
number
difficulty of the block
string
the hash of the blockheader
number
block number
string
unix timestamp in seconds since 1970
string
merkle root of the trie of all transactions in the block
number
number of transactions in the block
string
hash of the next blockheader
number
nonce-field of the block
string
hash of the parent blockheader
string
unix timestamp in seconds since 1970
T []
the transactions
number
used version
string
version as hex

Type BTCBlockHeader

Source: index.d.ts

a Block header

string
bits (target) for the block as hex
string
total amount of work since genesis
number
number of confirmations or blocks mined on top of the containing block
number
difficulty of the block
string
the hash of the blockheader
number
block number
string
unix timestamp in seconds since 1970
string
merkle root of the trie of all transactions in the block
number
number of transactions in the block
string
hash of the next blockheader
number
nonce-field of the block
string
hash of the parent blockheader
string
unix timestamp in seconds since 1970
number
used version
string
version as hex

Type BlockInfo

Source: index.d.ts

Block state.

number
the blockNumber
boolean
the committed
boolean
the verified

Type BtcAPI

Source: index.d.ts

API for handling BitCoin data

getBlockBytes()

retrieves the serialized block (bytes) including all transactions

Promise<BufferType> getBlockBytes (
blockHash:Hash )

Parameters:

blockHash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BufferType>

getBlockHeader()

retrieves the blockheader and returns the data as json.

Promise<BTCBlockHeader> getBlockHeader (
blockHash:Hash )

Parameters:

blockHash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BTCBlockHeader>

getBlockHeaderBytes()

retrieves the serialized blockheader (bytes)

Promise<BufferType> getBlockHeaderBytes (
blockHash:Hash )

Parameters:

blockHash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BufferType>

getBlockWithTxData()

retrieves the block including all tx data as json.

Promise<BTCBlock> getBlockWithTxData (
blockHash:Hash )

Parameters:

blockHash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BTCBlock>

getBlockWithTxIds()

retrieves the block including all tx ids as json.

Promise<BTCBlock> getBlockWithTxIds (
blockHash:Hash )

Parameters:

blockHash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BTCBlock>

getTransaction()

retrieves the transaction and returns the data as json.

Promise<BtcTransaction> getTransaction (
txid:Hash )

Parameters:

txid
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BtcTransaction>

getTransactionBytes()

retrieves the serialized transaction (bytes)

Promise<BufferType> getTransactionBytes (
txid:Hash )

Parameters:

txid
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<BufferType>

Type BtcTransaction

Source: index.d.ts

a BitCoin Transaction.

the block hash of the block containing this transaction.
number
The block time in seconds since epoch (Jan 1 1970 GMT)
number
The confirmations.
The transaction hash (differs from txid for witness transactions)
the hex representation of raw data
boolean
true if this transaction is part of the longest chain
number
The locktime
number
The serialized transaction size
number
The transaction time in seconds since epoch (Jan 1 1970 GMT)
The requested transaction id.
number
The version
the transaction inputs
the transaction outputs
number
The virtual transaction size (differs from size for witness transactions)
number
The transaction’s weight (between vsize4-3 and vsize4)

Type BtcTransactionInput

Source: index.d.ts

a Input of a Bitcoin Transaction


the script
number
The script sequence number
the transaction id
Data []
hex-encoded witness data (if any)
number
the index of the transactionoutput

Type BtcTransactionOutput

Source: index.d.ts

a Input of a Bitcoin Transaction

number
the index

the script
number
the value in BTC
number
the index of the transactionoutput

Type DepositResponse

Source: index.d.ts

Response of a Deposit-Transaction.

Type ETHOpInfoResp

Source: index.d.ts

L1 Operation State

the block
boolean
the executed

Type EthAPI

Source: index.d.ts

The API for ethereum operations.

blockNumber()

Returns the number of most recent block. (as number)

Promise<number> blockNumber ()

Returns:

Promise<number>

call()

Executes a new message call immediately without creating a transaction on the block chain.

Promise<string> call (
tx:Transaction , block:BlockType )

Parameters:

tx
tx
block
BlockNumber or predefined Block

Returns:

Promise<string>

callFn()

Executes a function of a contract, by passing a method-signature and the arguments, which will then be ABI-encoded and send as eth_call.

Promise<any> callFn (
to:Address , method:string, args:any [])

Parameters:

to
a 20 byte Address encoded as Hex (starting with 0x)
method
string
method
args
any []
args

Returns:

Promise<any>

chainId()

Returns the EIP155 chain ID used for transaction signing at the current best block. Null is returned if not available.

Promise<string> chainId ()

Returns:

Promise<string>

clientVersion()

Returns the clientVersion. This may differ in case of an network, depending on the node it communicates with.

Promise<string> clientVersion ()

Returns:

Promise<string>

constructor()

The API for ethereum operations.

EthAPI<BigIntType,BufferType> constructor (
client:IN3Generic<BigIntType,BufferType> )

Parameters:

Returns:

EthAPI<BigIntType,BufferType>

contractAt()

contract at

contractAt (
abi:ABI [], address:Address )

Parameters:

abi
ABI []
abi
address
a 20 byte Address encoded as Hex (starting with 0x)

decodeEventData()

decode event data

any decodeEventData (
log:Log , d:ABI )

Parameters:

log
log
d
d

Returns:

any

estimateGas()

Makes a call or transaction, which won’t be added to the blockchain and returns the used gas, which can be used for estimating the used gas.

Promise<number> estimateGas (
tx:Transaction )

Parameters:

tx
tx

Returns:

Promise<number>

gasPrice()

Returns the current price per gas in wei. (as number)

Promise<number> gasPrice ()

Returns:

Promise<number>

getAccounts()

returns the public addresses accounts

Promise<> getAccounts ()

Returns:

Promise<>

getBalance()

Returns the balance of the account of given address in wei (as hex).

Promise<BigIntType> getBalance (
address:Address , block:BlockType )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)
block
BlockNumber or predefined Block

Returns:

Promise<BigIntType>

getBlockByHash()

Returns information about a block by hash.

Promise<Block> getBlockByHash (
hash:Hash , includeTransactions:boolean)

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)
includeTransactions
boolean
include transactions

Returns:

Promise<Block>

getBlockByNumber()

Returns information about a block by block number.

Promise<Block> getBlockByNumber (
block:BlockType , includeTransactions:boolean)

Parameters:

block
BlockNumber or predefined Block
includeTransactions
boolean
include transactions

Returns:

Promise<Block>

getBlockTransactionCountByHash()

Returns the number of transactions in a block from a block matching the given block hash.

Promise<number> getBlockTransactionCountByHash (
block:Hash )

Parameters:

block
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<number>

getBlockTransactionCountByNumber()

Returns the number of transactions in a block from a block matching the given block number.

Promise<number> getBlockTransactionCountByNumber (
block:Hash )

Parameters:

block
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<number>

getCode()

Returns code at a given address.

Promise<string> getCode (
address:Address , block:BlockType )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)
block
BlockNumber or predefined Block

Returns:

Promise<string>

getFilterChanges()

Polling method for a filter, which returns an array of logs which occurred since last poll.

Promise<> getFilterChanges (
id:Quantity )

Parameters:

id
a BigInteger encoded as hex.

Returns:

Promise<>

getFilterLogs()

Returns an array of all logs matching filter with given id.

Promise<> getFilterLogs (
id:Quantity )

Parameters:

id
a BigInteger encoded as hex.

Returns:

Promise<>

getLogs()

Returns an array of all logs matching a given filter object.

Promise<> getLogs (
filter:LogFilter )

Parameters:

filter
filter

Returns:

Promise<>

getStorageAt()

Returns the value from a storage position at a given address.

Promise<string> getStorageAt (
address:Address , pos:Quantity , block:BlockType )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)
pos
a BigInteger encoded as hex.
block
BlockNumber or predefined Block

Returns:

Promise<string>

getTransactionByBlockHashAndIndex()

Returns information about a transaction by block hash and transaction index position.

Promise<TransactionDetail> getTransactionByBlockHashAndIndex (
hash:Hash , pos:Quantity )

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)
pos
a BigInteger encoded as hex.

Returns:

Promise<TransactionDetail>

getTransactionByBlockNumberAndIndex()

Returns information about a transaction by block number and transaction index position.

Promise<TransactionDetail> getTransactionByBlockNumberAndIndex (
block:BlockType , pos:Quantity )

Parameters:

block
BlockNumber or predefined Block
pos
a BigInteger encoded as hex.

Returns:

Promise<TransactionDetail>

getTransactionByHash()

Returns the information about a transaction requested by transaction hash.

Promise<TransactionDetail> getTransactionByHash (
hash:Hash )

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<TransactionDetail>

getTransactionCount()

Returns the number of transactions sent from an address. (as number)

Promise<number> getTransactionCount (
address:Address , block:BlockType )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)
block
BlockNumber or predefined Block

Returns:

Promise<number>

getTransactionReceipt()

Returns the receipt of a transaction by transaction hash. Note That the receipt is available even for pending transactions.

Promise<TransactionReceipt> getTransactionReceipt (
hash:Hash )

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<TransactionReceipt>

getUncleByBlockHashAndIndex()

Returns information about a uncle of a block by hash and uncle index position. Note: An uncle doesn’t contain individual transactions.

Promise<Block> getUncleByBlockHashAndIndex (
hash:Hash , pos:Quantity )

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)
pos
a BigInteger encoded as hex.

Returns:

Promise<Block>

getUncleByBlockNumberAndIndex()

Returns information about a uncle of a block number and uncle index position. Note: An uncle doesn’t contain individual transactions.

Promise<Block> getUncleByBlockNumberAndIndex (
block:BlockType , pos:Quantity )

Parameters:

block
BlockNumber or predefined Block
pos
a BigInteger encoded as hex.

Returns:

Promise<Block>

getUncleCountByBlockHash()

Returns the number of uncles in a block from a block matching the given block hash.

Promise<number> getUncleCountByBlockHash (
hash:Hash )

Parameters:

hash
a 32 byte Hash encoded as Hex (starting with 0x)

Returns:

Promise<number>

getUncleCountByBlockNumber()

Returns the number of uncles in a block from a block matching the given block hash.

Promise<number> getUncleCountByBlockNumber (
block:BlockType )

Parameters:

block
BlockNumber or predefined Block

Returns:

Promise<number>

hashMessage()

a Hexcoded String (starting with 0x)

Hex hashMessage (
data:Data )

Parameters:

data
data encoded as Hex (starting with 0x)

Returns:

Hex

newBlockFilter()

Creates a filter in the node, to notify when a new block arrives. To check if the state has changed, call eth_getFilterChanges.

Promise<string> newBlockFilter ()

Returns:

Promise<string>

newFilter()

Creates a filter object, based on filter options, to notify when the state changes (logs). To check if the state has changed, call eth_getFilterChanges.

A note on specifying topic filters: Topics are order-dependent. A transaction with a log with topics [A, B] will be matched by the following topic filters:

[] “anything” [A] “A in first position (and anything after)” [null, B] “anything in first position AND B in second position (and anything after)” [A, B] “A in first position AND B in second position (and anything after)” [[A, B], [A, B]] “(A OR B) in first position AND (A OR B) in second position (and anything after)”

Promise<string> newFilter (
filter:LogFilter )

Parameters:

filter
filter

Returns:

Promise<string>

newPendingTransactionFilter()

Creates a filter in the node, to notify when new pending transactions arrive.

To check if the state has changed, call eth_getFilterChanges.

Promise<string> newPendingTransactionFilter ()

Returns:

Promise<string>

protocolVersion()

Returns the current ethereum protocol version.

Promise<string> protocolVersion ()

Returns:

Promise<string>

resolveENS()

resolves a name as an ENS-Domain.

Promise<Address> resolveENS (
name:string, type:Address , registry:string)

Parameters:

name
string
the domain name
type
the type (currently only addr is supported)
registry
string
optionally the address of the registry (default is the mainnet ens registry)

Returns:

Promise<Address>

sendRawTransaction()

Creates new message call transaction or a contract creation for signed transactions.

Promise<string> sendRawTransaction (
data:Data )

Parameters:

data
data encoded as Hex (starting with 0x)

Returns:

Promise<string>

sendTransaction()

sends a Transaction

Promise<> sendTransaction (
args:TxRequest )

Parameters:

args
args

Returns:

Promise<>

sign()

signs any kind of message using the \x19Ethereum Signed Message:\n-prefix

Promise<BufferType> sign (
account:Address , data:Data )

Parameters:

account
the address to sign the message with (if this is a 32-bytes hex-string it will be used as private key)
data
the data to sign (Buffer, hexstring or utf8-string)

Returns:

Promise<BufferType>

syncing()

Returns the state of the underlying node.

Promise<> syncing ()

Returns:

Promise<>

toWei()

Returns the value in wei as hexstring.

string toWei (
value:string, unit:string)

Parameters:

value
string
value
unit
string
unit

Returns:

string

uninstallFilter()

Uninstalls a filter with given id. Should always be called when watch is no longer needed. Additonally Filters timeout when they aren’t requested with eth_getFilterChanges for a period of time.

Promise<Quantity> uninstallFilter (
id:Quantity )

Parameters:

id
a BigInteger encoded as hex.

Returns:

Promise<Quantity>

web3ContractAt()

web3 contract at

Web3Contract web3ContractAt (
abi:ABI [], address:Address , options:)

Parameters:

abi
ABI []
abi
address
a 20 byte Address encoded as Hex (starting with 0x)
options

options

Returns:

Web3Contract

Type Fee

Source: index.d.ts

fee collection.

the feeType
number
the gasFee
number
the gasPrice
number
the totalFee
number
the totalGas
number
the zkpFee

Type IN3Config

Source: index.d.ts

the configuration of the IN3-Client. This can be changed at any time. All properties are optional and will be verified when sending the next request.

boolean
if true the nodelist will be automaticly updated if the lastBlock is newer.

default: true
(optional)
boolean
if true, the first request (updating the nodelist) will also fetch the current health status
and use it for blacklisting unhealthy nodes. This is used only if no nodelist is availabkle from cache.

default: false
(optional)
config for btc (optional)
string
The chain-id based on EIP-155.
or the name of the supported chain.

Currently we support ‘mainnet’, ‘goerli’, ‘ipfs’ and ‘local’

While most of the chains use preconfigured chain settings,
‘local’ actually uses the local running client turning of proof.

example: ‘0x1’ or ‘mainnet’ or ‘goerli’

default: ‘mainnet’

string
main chain-registry contract
example: 0xe36179e2286ef405e929C90ad3E70E649B22a945 (optional)
boolean
if true, features marked as experimental are allowed.
Otherwise an exception would be thrown if those features would be used.

default: false
(optional)
number
the number in percent needed in order reach finality if you run on a POA-Chain.
(% of signature of the validators)

default: 0
(optional)
boolean
if true, the request should include the codes of all accounts.
Otherwise only the the codeHash is returned.
In this case the client may ask by calling eth_getCode() afterwards

default: false
(optional)
boolean
if true, the in3-section of the response will be kept and returned.
Otherwise it will be removed after validating the data.
This is useful for debugging or if the proof should be used afterwards.

default: false
(optional)
the key to sign requests. This is required for payments. (optional)
string
main chain-id, where the chain registry is running.
example: 0x1 (optional)
number
max number of attempts in case a response is rejected.
Incubed will retry to find a different node giving a verified response.

default: 5
(optional)
number
min stake of the server. Only nodes owning at least this amount will be chosen.

default: 0

number
the limit of nodes to store in the client. If set a random seed will be picked, which is the base for a deterministic verifiable partial nodelist.

default: 0
(optional)
number | Hex
a bitmask-value combining the minimal properties as filter for the selected nodes. See https://in3.readthedocs.io/en/develop/spec.html#node-structure for details.

the nodelists per chain. the chain_id will be used as key within the object. (optional)
'none' | 'standard' | 'full'
if true the nodes should send a proof of the response

default: ‘standard’
(optional)
number
if specified, the blocknumber latest will be replaced by blockNumber- specified value

default: 6
(optional)
number
the number of request send when getting a first answer

default: 1

string
url of a rpc-endpoints to use. If this is set proof will be turned off and it will be treated like local_chain. (optional)
number
number of signatures requested. The more signatures, the more security you get, but responses may take longer.

default: 0
(optional)
boolean
if false, the requests will not be included in the stats of the nodes ( or marked as intern ).

default: true
(optional)
number
specifies the number of milliseconds before the request times out. increasing may be helpful if the device uses a slow connection.

default: 5000
(optional)
config for zksync (optional)

transport()

sets the transport-function.

Promise<string> transport (
url:string, payload:string, timeout:number)

Parameters:

url
string
url
payload
string
payload
timeout
number
timeout

Returns:

Promise<string>

Type IN3NodeConfig

Source: index.d.ts

a configuration of a in3-server.

string
the address of the node, which is the public address it iis signing with.
example: 0x6C1a01C2aB554930A937B0a2E8105fB47946c679
number
the capacity of the node.
example: 100 (optional)
string []
the list of supported chains
example: 0x1
number
the deposit of the node in wei
example: 12350000
number
the index within the contract
example: 13 (optional)
number
the properties of the node.
example: 3 (optional)
number
the UNIX-timestamp when the node was registered
example: 1563279168 (optional)
number
the time (in seconds) until an owner is able to receive his deposit back after he unregisters himself
example: 3600 (optional)
number
the UNIX-timestamp when the node is allowed to be deregister
example: 1563279168 (optional)
string
the endpoint to post to

Type IN3NodeWeight

Source: index.d.ts

a local weight of a n3-node. (This is used internally to weight the requests)

number
average time of a response in ms
example: 240 (optional)
number
blacklisted because of failed requests until the timestamp
example: 1529074639623 (optional)
number
timestamp of the last request in ms
example: 1529074632623 (optional)
number
last price (optional)
number
number of uses.
example: 147 (optional)
number
factor the weight this noe (default 1.0)
example: 0.5 (optional)

Type IN3Plugin

Source: index.d.ts

Type IpfsAPI

Source: index.d.ts

API for storing and retrieving IPFS-data.

get()

retrieves the content for a hash from IPFS.

Promise<BufferType> get (
multihash:string)

Parameters:

multihash
string
the IPFS-hash to fetch


Returns:

Promise<BufferType>

put()

stores the data on ipfs and returns the IPFS-Hash.

Promise<string> put (
content:BufferType )

Parameters:

content
puts a IPFS content

Returns:

Promise<string>

Type RPCRequest

Source: index.d.ts

a JSONRPC-Request with N3-Extension

number | string
the identifier of the request
example: 2 (optional)
'2.0'
the version
string
the method to call
example: eth_getBalance
any []
the params
example: 0xe36179e2286ef405e929C90ad3E70E649B22a945,latest (optional)

Type RPCResponse

Source: index.d.ts

a JSONRPC-Responset with N3-Extension

string |
in case of an error this needs to be set (optional)
string | number
the id matching the request
example: 2
'2.0'
the version
any
the params
example: 0xa35bc (optional)

Type Signer

Source: index.d.ts

prepareTransaction()

optiional method which allows to change the transaction-data before sending it. This can be used for redirecting it through a multisig.

Promise<Transaction> prepareTransaction (
client:IN3Generic<BigIntType,BufferType> , tx:Transaction )

Parameters:

Returns:

Promise<Transaction>

sign()

signing of any data. if hashFirst is true the data should be hashed first, otherwise the data is the hash.

Promise<BufferType> sign (
data:Hex , account:Address , hashFirst:boolean, ethV:boolean)

Parameters:

data
a Hexcoded String (starting with 0x)
account
a 20 byte Address encoded as Hex (starting with 0x)
hashFirst
boolean
hash first
ethV
boolean
eth v

Returns:

Promise<BufferType>

canSign()

returns true if the account is supported (or unlocked)

Promise<boolean> canSign (
address:Address )

Parameters:

address
a 20 byte Address encoded as Hex (starting with 0x)

Returns:

Promise<boolean>

getAccounts()

returns all addresses managed by the signer.

Address [] getAccounts ()

Returns:

Address []

Type Token

Source: index.d.ts

Token representation

the address
number
the decimals
number
the id
the symbol

Type Tokens

Source: index.d.ts

Token List.

Type TxInfo

Source: index.d.ts

Transaction state

the block
boolean
the executed
string
the failReason
boolean
the success

Type TxType

Source: index.d.ts

Defines the type of a transaction.

'Withdraw'
| 'Transfer'
| 'TransferToNew'
the type

Type Utils

Source: index.d.ts

Collection of different util-functions.

abiDecode()

decodes the given data as ABI-encoded (without the methodHash)

any [] abiDecode (
signature:string, data:Data )

Parameters:

signature
string
the method signature, which must contain a return description
data
the data to decode

Returns:

any []

abiEncode()

encodes the given arguments as ABI-encoded (including the methodHash)

Hex abiEncode (
signature:string, args:any [])

Parameters:

signature
string
the method signature
args
any []
the arguments

Returns:

Hex

checkAddressChecksum()

checks whether the given address is a correct checksumAddress If the chainId is passed, it will be included accord to EIP 1191

boolean checkAddressChecksum (
address:Address , chainId:number)

Parameters:

address
the address (as hex)
chainId
number
the chainId (if supported)

Returns:

boolean

createSignatureHash()

a Hexcoded String (starting with 0x)

Hex createSignatureHash (
def:ABI )

Parameters:

def
def

Returns:

Hex

decodeEvent()

decode event

any decodeEvent (
log:Log , d:ABI )

Parameters:

log
log
d
d

Returns:

any

ecSign()

create a signature (65 bytes) for the given message and kexy

BufferType ecSign (
pk:Hex | BufferType , msg:Hex | BufferType , hashFirst:boolean, adjustV:boolean)

Parameters:

pk
the private key
msg
the message
hashFirst
boolean
if true the message will be hashed first (default:true), if not the message is the hash.
adjustV
boolean
if true (default) the v value will be adjusted by adding 27

Returns:

BufferType

getVersion()

returns the incubed version.

string getVersion ()

Returns:

string

isAddress()

checks whether the given address is a valid hex string with 0x-prefix and 20 bytes

boolean isAddress (
address:Address )

Parameters:

address
the address (as hex)

Returns:

boolean

keccak()

calculates the keccack hash for the given data.

BufferType keccak (
data:BufferType | Data )

Parameters:

data
the data as Uint8Array or hex data.

Returns:

BufferType

private2address()

generates the public address from the private key.

Address private2address (
pk:Hex | BufferType )

Parameters:

pk
the private key.

Returns:

Address

randomBytes()

returns a Buffer with strong random bytes. Thsi will use the browsers crypto-module or in case of nodejs use the crypto-module there.

BufferType randomBytes (
len:number)

Parameters:

len
number
the number of bytes to generate.

Returns:

BufferType

soliditySha3()

solidity sha3

string soliditySha3 (
args:any [])

Parameters:

args
any []
args

Returns:

string

splitSignature()

takes raw signature (65 bytes) and splits it into a signature object.

Signature splitSignature (
signature:Hex | BufferType , message:BufferType | Hex , hashFirst:boolean)

Parameters:

signature
the 65 byte-signature
message
the message
hashFirst
boolean
if true (default) this will be taken as raw-data and will be hashed first.

Returns:

Signature

toBuffer()

converts any value to a Buffer. optionally the target length can be specified (in bytes)

BufferType toBuffer (
data:Hex | BufferType | number | bigint, len:number)

Parameters:

data
| number
| bigint
data
len
number
len

Returns:

BufferType

toChecksumAddress()

generates a checksum Address for the given address. If the chainId is passed, it will be included accord to EIP 1191

Address toChecksumAddress (
address:Address , chainId:number)

Parameters:

address
the address (as hex)
chainId
number
the chainId (if supported)

Returns:

Address

toHex()

converts any value to a hex string (with prefix 0x). optionally the target length can be specified (in bytes)

Hex toHex (
data:Hex | BufferType | number | bigint, len:number)

Parameters:

data
| number
| bigint
data
len
number
len

Returns:

Hex

toMinHex()

removes all leading 0 in the hexstring

string toMinHex (
key:string | BufferType | number)

Parameters:

key
string
| number
key

Returns:

string

toNumber()

converts any value to a hex string (with prefix 0x). optionally the target length can be specified (in bytes)

number toNumber (
data:string | BufferType | number | bigint)

Parameters:

data
string
| number
| bigint
data

Returns:

number

toUint8Array()

converts any value to a Uint8Array. optionally the target length can be specified (in bytes)

BufferType toUint8Array (
data:Hex | BufferType | number | bigint, len:number)

Parameters:

data
| number
| bigint
data
len
number
len

Returns:

BufferType

toUtf8()

convert to String

string toUtf8 (
val:any)

Parameters:

val
any
val

Returns:

string

Type Web3Contract

Source: index.d.ts


the events

the methods

the options

deploy()

deploy

Web3TransactionObject deploy (
args:)

Parameters:

args

args

Returns:

Web3TransactionObject

once()

once

void once (
eventName:string, options:, handler:(Error , Web3Event ) => void)

Parameters:

eventName
string
event name
options

options
handler
(Error , Web3Event ) => void
handler

getPastEvents()

get past events

Promise<> getPastEvents (
evName:string, options:)

Parameters:

evName
string
ev name
options

options

Returns:

Promise<>

Type Web3Event

Source: index.d.ts

the address
the blockHash
number
the blockNumber
string
the event
number
the logIndex

the raw

the returnValues
string
the signature
the transactionHash
number
the transactionIndex

Type Web3TransactionObject

Source: index.d.ts

call()

call

Promise<any> call (
options:)

Parameters:

options

options

Returns:

Promise<any>

encodeABI()

a Hexcoded String (starting with 0x)

Hex encodeABI ()

Returns:

Hex

estimateGas()

estimate gas

Promise<number> estimateGas (
options:)

Parameters:

options

options

Returns:

Promise<number>

send()

send

Promise<any> send (
options:)

Parameters:

options

options

Returns:

Promise<any>

Type ZKAccountInfo

Source: index.d.ts

return structure after fetching the current account info.

string
the address

the committed

the depositing
number
the id

the verified

Type ZksyncAPI

Source: index.d.ts

API for zksync.

aggregatePubKey()

aggregates the given publickeys into one public key for a Musig Schnorr signature

string aggregatePubKey (
pubkeys:string | string [])

Parameters:

pubkeys
string | string []
the packed public keys (either a concatenated string or as array of public keys)

Returns:

string

deposit()

deposits the declared amount into the rollup

Promise<DepositResponse> deposit (
amount:number, token:string, approveDepositAmountForERC20:boolean, account:string)

Parameters:

amount
number
amount in wei to deposit
token
string
the token identifier e.g. ETH
approveDepositAmountForERC20
boolean
bool that is set to true if it is a erc20 token that needs approval
account
string
address of the account that wants to deposit (if left empty it will be taken from current signer)

Returns:

Promise<DepositResponse>

emergencyWithdraw()

executes an emergency withdrawel onchain

Promise<String> emergencyWithdraw (
token:string)

Parameters:

token
string
the token identifier e.g. ETH

Returns:

Promise<String>

getAccountAddress()

returns the address of the account used.

String getAccountAddress ()

Returns:

String

getAccountInfo()

gets current account Infoa and balances.

Promise<ZKAccountInfo> getAccountInfo (
account:string)

Parameters:

account
string
the address of the account . if not specified, the first signer is used.

Returns:

Promise<ZKAccountInfo>

getContractAddress()

gets the contract address of the zksync contract

Promise<String> getContractAddress ()

Returns:

Promise<String>

getEthopInfo()

returns the state of receipt of the PriorityOperation

Promise<ETHOpInfoResp> getEthopInfo (
opId:number)

Parameters:

opId
number
the id of the PriorityOperation

Returns:

Promise<ETHOpInfoResp>

getSyncKey()

returns private key used for signing zksync transactions

String getSyncKey ()

Returns:

String

getSyncPubKey()

returns public key used for signing zksync transactions

String getSyncPubKey ()

Returns:

String

getSyncPubKeyHash()

returns public key used for signing zksync transactions

String getSyncPubKeyHash ()

Returns:

String

getTokenPrice()

returns the current token price

Promise<Number> getTokenPrice (
tokenSymbol:string)

Parameters:

tokenSymbol
string
the address of the token

Returns:

Promise<Number>

getTokens()

returns an object containing Token objects with its short name as key

Promise<Tokens> getTokens ()

Returns:

Promise<Tokens>

getTxFee()

returns the transaction fee

Promise<Fee> getTxFee (
txType:TxType , receipient:string, token:string)

Parameters:

txType
either Withdraw or Transfer
receipient
string
the address the transaction is send to
token
string
the token identifier e.g. ETH

Returns:

Promise<Fee>

getTxInfo()

get transaction info

Promise<TxInfo> getTxInfo (
txHash:string)

Parameters:

txHash
string
the has of the tx you want the info about

Returns:

Promise<TxInfo>

setKey()

set the signer key based on the current pk

Promise<String> setKey (
tokenSymbol:string, newKey:BufferType | string)

Parameters:

tokenSymbol
string
the address of the token
newKey
BufferType | string
the seed of the new key ( this is optional, if ommited the derrived key will be set in the rollup)

Returns:

Promise<String>

sign()

signs the message based on the config and returns a Musig Schnorr signature

Promise<String> sign (
msg:string)

Parameters:

msg
string
the message

Returns:

Promise<String>

transfer()

transfers the specified amount to another address within the zksync rollup

Promise<String> transfer (
to:string, amount:number, token:string, account:string)

Parameters:

to
string
address of the receipient
amount
number
amount to send in wei
token
string
the token indentifier e.g. ETH
account
string
address of the account that wants to transfer (if left empty it will be taken from current signer)

Returns:

Promise<String>

verify()

verifies a Musig Schnorr signature

boolean verify (
msg:string, sig:string)

Parameters:

msg
string
the message
sig
string
the 96byte long signature

Returns:

boolean

withdraw()

withdraws the specified amount from the rollup to a specific address

Promise<String> withdraw (
ethAddress:string, amount:number, token:string, account:string)

Parameters:

ethAddress
string
the receipient address
amount
number
amount to withdraw in wei
token
string
the token identifier e.g. ETH
account
string
address of the account that wants to withdraw (if left empty it will be taken from current signer)

Returns:

Promise<String>

Type ABI

Source: index.d.ts

boolean
the anonymous (optional)
the components (optional)
boolean
the constant (optional)
the inputs (optional)
string
the internalType (optional)
string
the name (optional)
ABIField [] | any []
the outputs (optional)
boolean
the payable (optional)
'pure'
| 'view'
| 'nonpayable'
| 'payable'
| string
the stateMutability (optional)
'function'
| 'constructor'
| 'event'
| 'fallback'
| string
the type

Type ABIField

Source: index.d.ts

boolean
the indexed (optional)
string
the internalType (optional)
string
the name
string
the type

Type Address

Source: index.d.ts

a 20 byte Address encoded as Hex (starting with 0x) a Hexcoded String (starting with 0x) = string

Type Block

Source: index.d.ts

20 Bytes - the address of the author of the block (the beneficiary to whom the mining rewards were given)
integer of the difficulty for this block
the ‘extra data’ field of this block
the maximum gas allowed in this block
the total used gas by all transactions in this block
hash of the block. null when its pending block
256 Bytes - the bloom filter for the logs of the block. null when its pending block
20 Bytes - alias of ‘author’
8 bytes hash of the generated proof-of-work. null when its pending block. Missing in case of PoA.
The block number. null when its pending block
hash of the parent block
32 Bytes - the root of the receipts trie of the block
Data []
PoA-Fields
SHA3 of the uncles data in the block
integer the size of this block in bytes
32 Bytes - the root of the final state trie of the block
the unix timestamp for when the block was collated
integer of the total difficulty of the chain until this block
string | []
Array of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter
32 Bytes - the root of the transaction trie of the block
Hash []
Array of uncle hashes

Type Data

Source: index.d.ts

data encoded as Hex (starting with 0x) a Hexcoded String (starting with 0x) = string

Type Hash

Source: index.d.ts

a 32 byte Hash encoded as Hex (starting with 0x) a Hexcoded String (starting with 0x) = string

Type Log

Source: index.d.ts

20 Bytes - address from which this log originated.
Hash, 32 Bytes - hash of the block where this log was in. null when its pending. null when its pending log.
the block number where this log was in. null when its pending. null when its pending log.
contains the non-indexed arguments of the log.
integer of the log index position in the block. null when its pending log.
boolean
true when the log was removed, due to a chain reorganization. false if its a valid log.
Data []
- Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.)
Hash, 32 Bytes - hash of the transactions this log was created from. null when its pending log.
integer of the transactions index position log was created from. null when its pending log.

Type LogFilter

Source: index.d.ts

(optional) 20 Bytes - Contract address or a list of addresses from which logs should originate.
Quantity or Tag - (optional) (default: latest) Integer block number, or ‘latest’ for the last mined block or ‘pending’, ‘earliest’ for not yet mined transactions. (optional)
å(optional) The maximum number of entries to retrieve (latest first). (optional)
Quantity or Tag - (optional) (default: latest) Integer block number, or ‘latest’ for the last mined block or ‘pending’, ‘earliest’ for not yet mined transactions. (optional)
string | string [] []
(optional) Array of 32 Bytes Data topics. Topics are order-dependent. It’s possible to pass in null to match any topic, or a subarray of multiple topics of which one should be matching. (optional)

Type Signature

Source: index.d.ts

Signature

the message
the messageHash
the r
the s
the signature (optional)
the v

Type Transaction

Source: index.d.ts

any
optional chain id (optional)
string
4 byte hash of the method signature followed by encoded parameters. For details see Ethereum Contract ABI.
20 Bytes - The address the transaction is send from.
Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions.
Integer of the gas price used for each paid gas.
nonce
(optional when creating new contract) 20 Bytes - The address the transaction is directed to. (optional)
Integer of the value sent with this transaction.

Type TransactionDetail

Source: index.d.ts

32 Bytes - hash of the block where this transaction was in. null when its pending.
block number where this transaction was in. null when its pending.
the chain id of the transaction, if any.
any
(optional) conditional submission, Block number in block or timestamp in time or null. (parity-feature) (optional)
creates contract address
20 Bytes - address of the sender.
gas provided by the sender.
gas price provided by the sender in Wei.
32 Bytes - hash of the transaction.
the data send along with the transaction.
the number of transactions made by the sender prior to this one.
any
optional: the private key to use for signing (optional)
public key of the signer.
the R field of the signature.
raw transaction data
the standardised V field of the signature (0 or 1).
20 Bytes - address of the receiver. null when its a contract creation transaction.
integer of the transactions index position in the block. null when its pending.
the standardised V field of the signature.
value transferred in Wei.

Type TransactionReceipt

Source: index.d.ts

a Receipt of a Transaction containing the events and execution status

32 Bytes - hash of the block where this transaction was in.
block number where this transaction was in.
20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null.
The total amount of gas used when this transaction was executed in the block.

event objects, which are only added in the web3Contract (optional)
20 Bytes - The address of the sender.
The amount of gas used by this specific transaction alone.
Log []
Array of log objects, which this transaction generated.
256 Bytes - A bloom filter of logs/events generated by contracts during transaction execution. Used to efficiently rule out transactions without expected logs.
32 Bytes - Merkle root of the state trie after the transaction has been executed (optional after Byzantium hard fork EIP609) (optional)
0x0 indicates transaction failure , 0x1 indicates transaction success. Set for blocks mined after Byzantium hard fork EIP609, null before.
20 Bytes - The address of the receiver. null when it’s a contract creation transaction.
32 Bytes - hash of the transaction.
Integer of the transactions index position in the block.

Type TxRequest

Source: index.d.ts

any []
the argument to pass to the method (optional)
number
number of block to wait before confirming (optional)
the data to send (optional)
address of the account to use (optional)
number
the gas needed (optional)
number
the gasPrice used (optional)
string
the ABI of the method to be used (optional)
number
the nonce (optional)
raw private key in order to sign (optional)
number
number of seconds to wait for confirmations before giving up. Default: 10 (optional)
contract (optional)
the value in wei (optional)

Type btc_config

Source: index.d.ts

bitcoin configuration.

number
max number of DAPs (Difficulty Adjustment Periods) allowed when accepting new targets. (optional)
number
max increase (in percent) of the difference between targets when accepting new targets. (optional)

Type zksync_config

Source: index.d.ts

zksync configuration.

string
the account to be used. if not specified, the first signer will be used. (optional)

create2 arguments (optional)
string
concated packed public keys of the signers of the multisig (optional)
string []
if used as a musig-signature the (optional)
string
url of the zksync-server (optional)
'pk' | 'contract' | 'create2'
defines the type of the signer. Must be one of those 3 values. (default: pk) (optional)
string
optionaly the private seephrase to use when signing sync-transaction.
If ommited this key is derrived from the signer. (optional)

Type Hex

Source: index.d.ts

a Hexcoded String (starting with 0x) = string

Type BlockType

Source: index.d.ts

BlockNumber or predefined Block = number | 'latest' | 'earliest' | 'pending'

Type Quantity

Source: index.d.ts

a BigInteger encoded as hex. = number | Hex