API Reference WASM¶
Even though the incubed client is written in C, we are using emscripten to build wasm. Together with some binding-code incubed runs in any Javascript-Runtime. Using WASM gives us 3 important features:
- Performance. Since WASM runs at almost native speed it is very fast
- 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.
- 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 incubed is as easy as installing any other module:
npm install --save in3-wasm
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 incubed 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_rpc¶
source : in3-c/wasm/examples/get_block_rpc.js
read block as rpc
/// read block as rpc
const IN3 = require('in3-wasm')
async function showLatestBlock() {
// create new incubed instance
var c = new IN3()
await c.setConfig({
chainId: 0x5 // use goerli
})
// send raw RPC-Request (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))
// clean up
c.free()
}
showLatestBlock().catch(console.error)
get_block_api¶
source : in3-c/wasm/examples/get_block_api.ts
read block with API
/// read block with API
import { IN3 } from 'in3-wasm'
async function showLatestBlock() {
// create new incubed instance
const client = new IN3({
chainId: 'goerli'
})
// send raw RPC-Request
const lastBlock = await client.eth.getBlockByNumber()
console.log("latest Block: ", JSON.stringify(lastBlock, null, 2))
// clean up
client.free()
}
showLatestBlock().catch(console.error)
register_pugin¶
source : in3-c/wasm/examples/register_pugin.ts
register a custom plugin
/// register a custom plugin
import { IN3, RPCRequest } from 'in3-wasm'
import * as crypto from 'crypto'
class Sha256Plugin {
// 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 incubed nodes
handleRPC(c: IN3, 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 incubed 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)
// clean up
client.free()
}
registerPlugin().catch(console.error)
use_web3¶
source : in3-c/wasm/examples/use_web3.ts
use incubed as Web3Provider in web3js
/// use incubed as Web3Provider in web3js
// import in3-Module
import { IN3 } from 'in3-wasm'
const Web3 = require('web3')
const in3 = new IN3({
proof: 'standard',
signatureCount: 1,
requestCount: 1,
chainId: 'mainnet',
replaceLatestBlock: 10
})
// use the In3Client as Http-Provider
const web3 = new Web3(in3.createWeb3Provider());
(async () => {
// use the web3
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 incubed directly in html
<!-- use incubed directly in html -->
<html>
<head>
<script src="node_modules/in3-wasm/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)
.finally(() => in3.free())
</script>
</body>
</html>
Building¶
In order to run those examples, you need to install in3-wasm 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 Module¶
This page contains a list of all Datastructures and Classes used within the IN3 WASM-Client
Importing incubed is as easy as
import {IN3} from "in3-wasm"
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-wasm'
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 withbigint for big numbersUint8Array for bytes Class the IN3Generic Class the SimpleSigner Interface The Account API Interface a full Block including the transactions Interface a Block header Interface the BlockInfo 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 the DepositResponse Interface the ETHOpInfoResp Interface The API for ethereum operations. Interface the Fee 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 the Token Interface the Tokens Interface the TxInfo Interface the TxType Interface Collection of different util-functions. Interface the Web3Contract Interface the Web3Event Interface the Web3TransactionObject Interface the ZKAccountInfo 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 the TransactionReceipt 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
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()¶
set convert big int
- static
any
setConvertBigInt ( - convert:(
any
) =>any
)
Parameters:
convert (any
) =>any
convert
Returns:
static any
setConvertBuffer()¶
set convert buffer
- static
any
setConvertBuffer ( - convert:(
any
) =>any
)
Parameters:
convert (any
) =>any
convert
Returns:
static any
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:
createWeb3Provider()¶
returns a Object, which can be used as Web3Provider.
const web3 = new Web3(new IN3().createWeb3Provider())
any
createWeb3Provider ()
Returns:
any
free()¶
disposes the Client. This must be called in order to free allocated memory!
any
free ()
Returns:
any
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 callback
Returns:
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:
methodstring
the method to call. paramsany
[] params
Returns:
Promise<any>
sendSyncRPC()¶
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
sendSyncRPC (- method:
string
, params:any
[])
Parameters:
methodstring
the method to call. paramsany
[] params
Returns:
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
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()¶
set convert big int
- static
any
setConvertBigInt ( - convert:(
any
) =>any
)
Parameters:
convert (any
) =>any
convert
Returns:
static any
setConvertBuffer()¶
set convert buffer
- static
any
setConvertBuffer ( - convert:(
any
) =>any
)
Parameters:
convert (any
) =>any
convert
Returns:
static any
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:
createWeb3Provider()¶
returns a Object, which can be used as Web3Provider.
const web3 = new Web3(new IN3().createWeb3Provider())
any
createWeb3Provider ()
Returns:
any
free()¶
disposes the Client. This must be called in order to free allocated memory!
any
free ()
Returns:
any
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 callback
Returns:
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:
methodstring
the method to call. paramsany
[] params
Returns:
Promise<any>
sendSyncRPC()¶
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
sendSyncRPC (- method:
string
, params:any
[])
Parameters:
methodstring
the method to call. paramsany
[] params
Returns:
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:
pksstring
| BufferType [] pks
Returns:
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:
client client tx tx
Returns:
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:
Returns:
addAccount()¶
add account
string
addAccount (- pk:Hash )
Parameters:
pk a 32 byte Hash encoded as Hex (starting with 0x)
Returns:
string
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:
pkstring
| BufferType
Returns:
Promise<string>
Type BTCBlock¶
Source: index.d.ts
a full Block including the transactions
string
bits (target) for the block as hexstring
total amount of work since genesisnumber
number of confirmations or blocks mined on top of the containing blocknumber
difficulty of the blockstring
the hash of the blockheadernumber
block numberstring
unix timestamp in seconds since 1970string
merkle root of the trie of all transactions in the blocknumber
number of transactions in the blockstring
hash of the next blockheadernumber
nonce-field of the blockstring
hash of the parent blockheaderstring
unix timestamp in seconds since 1970 T [] the transactionsnumber
used versionstring
version as hex
Type BTCBlockHeader¶
Source: index.d.ts
a Block header
string
bits (target) for the block as hexstring
total amount of work since genesisnumber
number of confirmations or blocks mined on top of the containing blocknumber
difficulty of the blockstring
the hash of the blockheadernumber
block numberstring
unix timestamp in seconds since 1970string
merkle root of the trie of all transactions in the blocknumber
number of transactions in the blockstring
hash of the next blockheadernumber
nonce-field of the blockstring
hash of the parent blockheaderstring
unix timestamp in seconds since 1970number
used versionstring
version as hex
Type BlockInfo¶
Source: index.d.ts
number
the blockNumberboolean
the committedboolean
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:
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:
getBlockHeaderBytes()¶
retrieves the serialized blockheader (bytes)
- Promise<BufferType> getBlockHeaderBytes (
- blockHash:Hash )
Parameters:
blockHash a 32 byte Hash encoded as Hex (starting with 0x)
Returns:
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:
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:
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:
getTransactionBytes()¶
retrieves the serialized transaction (bytes)
- Promise<BufferType> getTransactionBytes (
- txid:Hash )
Parameters:
txid a 32 byte Hash encoded as Hex (starting with 0x)
Returns:
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 databoolean
true if this transaction is part of the longest chainnumber
The locktimenumber
The serialized transaction sizenumber
The transaction time in seconds since epoch (Jan 1 1970 GMT) The requested transaction id.number
The version the transaction inputs the transaction outputsnumber
The virtual transaction size (differs from size for witness transactions)number
The transaction’s weight (between vsize4-3 and vsize4)
Type BtcTransactionOutput¶
Source: index.d.ts
a Input of a Bitcoin Transaction
number
the index the scriptnumber
the value in BTCnumber
the index of the transactionoutput
Type EthAPI¶
Source: index.d.ts
The API for ethereum operations.
accounts-API the client used. a custom signer (optional)
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.
Parameters:
to a 20 byte Address encoded as Hex (starting with 0x) methodstring
method argsany
[] 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()¶
constructor
any
constructor (- client:IN3Generic<BigIntType,BufferType> )
Parameters:
client client
Returns:
any
decodeEventData()¶
decode event data
any
decodeEventData (- log:Log , d:ABI )
Parameters:
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>
getBalance()¶
Returns the balance of the account of given address in wei (as hex).
- Promise<BigIntType> getBalance (
- address:Address , block:BlockType )
Parameters:
Returns:
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) includeTransactionsboolean
include transactions
Returns:
getBlockByNumber()¶
Returns information about a block by block number.
- Promise<Block> getBlockByNumber (
- block:BlockType ,
includeTransactions:
boolean
)
Parameters:
block BlockNumber or predefined Block includeTransactionsboolean
include transactions
Returns:
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>
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.
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:
Returns:
Promise<string>
getTransactionByBlockHashAndIndex()¶
Returns information about a transaction by block hash and transaction index position.
- Promise<TransactionDetail> getTransactionByBlockHashAndIndex (
- hash:Hash , pos:Quantity )
Parameters:
Returns:
getTransactionByBlockNumberAndIndex()¶
Returns information about a transaction by block number and transaction index position.
Parameters:
Returns:
getTransactionByHash()¶
Returns the information about a transaction requested by transaction hash.
Parameters:
hash a 32 byte Hash encoded as Hex (starting with 0x)
Returns:
getTransactionCount()¶
Returns the number of transactions sent from an address. (as number)
Promise<number>
getTransactionCount (- address:Address , block:BlockType )
Parameters:
Returns:
Promise<number>
getTransactionReceipt()¶
Returns the receipt of a transaction by transaction hash. Note That the receipt is available even for pending transactions.
Parameters:
hash a 32 byte Hash encoded as Hex (starting with 0x)
Returns:
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:
Returns:
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:
Returns:
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:
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)”
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:
namestring
the domain name type the type (currently only addr is supported) registrystring
optionally the address of the registry (default is the mainnet ens registry)
Returns:
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:
Returns:
toWei()¶
Returns the value in wei as hexstring.
string
toWei (- value:
string
, unit:string
)
Parameters:
valuestring
value unitstring
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.
Parameters:
id a BigInteger encoded as hex.
Returns:
web3ContractAt()¶
web3 contract at
- Web3Contract web3ContractAt (
- abi:ABI [], address:Address , options:)
Parameters:
Returns:
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 statusand 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’, ‘kovan’, ‘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 contractexample: 0xe36179e2286ef405e929C90ad3E70E649B22a945 (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() afterwardsdefault: 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: 0number
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 responsedefault: ‘standard’(optional)number
if specified, the blocknumber latest will be replaced by blockNumber- specified valuedefault: 6(optional)number
the number of request send when getting a first answerdefault: 1string
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)
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: 0x6C1a01C2aB554930A937B0a2E8105fB47946c679number
the capacity of the node.example: 100 (optional)string
[] the list of supported chainsexample: 0x1number
the deposit of the node in weiexample: 12350000number
the index within the contractexample: 13 (optional)number
the properties of the node.example: 3 (optional)number
the UNIX-timestamp when the node was registeredexample: 1563279168 (optional)number
the time (in seconds) until an owner is able to receive his deposit back after he unregisters himselfexample: 3600 (optional)number
the UNIX-timestamp when the node is allowed to be deregisterexample: 1563279168 (optional)string
the endpoint to post toexample: https://in3.slock.it
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 msexample: 240 (optional)number
blacklisted because of failed requests until the timestampexample: 1529074639623 (optional)number
timestamp of the last request in msexample: 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:
multihashstring
the IPFS-hash to fetch
Returns:
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 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:
client client tx tx
Returns:
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:
Returns:
Type Tokens¶
Source: index.d.ts
Type TxInfo¶
Source: index.d.ts
the blockboolean
the executedstring
the failReasonboolean
the success
Type Utils¶
Source: index.d.ts
Collection of different util-functions.
abiDecode()¶
decodes the given data as ABI-encoded (without the methodHash)
Parameters:
signaturestring
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)
Parameters:
signaturestring
the method signature argsany
[] the arguments
Returns:
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) chainIdnumber
the chainId (if supported)
Returns:
boolean
createSignatureHash()¶
a Hexcoded String (starting with 0x)
- Hex createSignatureHash (
- def:ABI )
Parameters:
def def
Returns:
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 hashFirstboolean
if true the message will be hashed first (default:true), if not the message is the hash. adjustVboolean
if true (default) the v value will be adjusted by adding 27
Returns:
isAddress()¶
checks whether the given address is a valid hex string with 0x-prefix and 20 bytes
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:
private2address()¶
generates the public address from the private key.
- Address private2address (
- pk:Hex | BufferType )
Parameters:
pk the private key.
Returns:
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:
lennumber
the number of bytes to generate.
Returns:
soliditySha3()¶
solidity sha3
string
soliditySha3 (- args:
any
[])
Parameters:
argsany
[] 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 hashFirstboolean
if true (default) this will be taken as raw-data and will be hashed first.
Returns:
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 data lennumber
len
Returns:
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) chainIdnumber
the chainId (if supported)
Returns:
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 data lennumber
len
Returns:
toMinHex()¶
removes all leading 0 in the hexstring
string
toMinHex (- key:
string
| BufferType |number
)
Parameters:
key 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 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 data lennumber
len
Returns:
Type Web3Contract¶
Source: index.d.ts
getPastEvents()¶
get past events
Promise<>
getPastEvents (- evName:
string
, options:)
Parameters:
evNamestring
ev name options options
Returns:
Promise<>
Type Web3Event¶
Source: index.d.ts
the address the blockHashnumber
the blockNumberstring
the eventnumber
the logIndex the raw the returnValuesstring
the signature the transactionHashnumber
the transactionIndex
Type Web3TransactionObject¶
Source: index.d.ts
estimateGas()¶
estimate gas
Promise<number>
estimateGas (- options:)
Parameters:
options options
Returns:
Promise<number>
Type ZKAccountInfo¶
Source: index.d.ts
string
the address the committed the depositingnumber
the id the verified
Type ZksyncAPI¶
Source: index.d.ts
API for zksync.
deposit()¶
deposits the declared amount into the rollup
- Promise<DepositResponse> deposit (
- amount:
number
, token:string
, approveDepositAmountForERC20:boolean
, account:string
)
Parameters:
amountnumber
amount in wei to deposit tokenstring
the token identifier e.g. ETH approveDepositAmountForERC20boolean
bool that is set to true if it is a erc20 token that needs approval accountstring
address of the account that wants to deposit (if left empty it will be taken from current signer)
Returns:
emergencyWithdraw()¶
executes an emergency withdrawel onchain
- Promise<String> emergencyWithdraw (
- token:
string
)
Parameters:
tokenstring
the token identifier e.g. ETH
Returns:
getAccountInfo()¶
gets current account Infoa and balances.
- Promise<ZKAccountInfo> getAccountInfo (
- account:
string
)
Parameters:
accountstring
the address of the account . if not specified, the first signer is used.
Returns:
getContractAddress()¶
gets the contract address of the zksync contract
Promise<String> getContractAddress ()
Returns:
getEthopInfo()¶
returns the state of receipt of the PriorityOperation
- Promise<ETHOpInfoResp> getEthopInfo (
- opId:
number
)
Parameters:
opIdnumber
the id of the PriorityOperation
Returns:
getSyncKey()¶
returns private key used for signing zksync transactions
String getSyncKey ()
Returns:
getTokenPrice()¶
returns the current token price
- Promise<Number> getTokenPrice (
- tokenSymbol:
string
)
Parameters:
tokenSymbolstring
the address of the token
Returns:
getTxFee()¶
returns the transaction fee
- Promise<Fee> getTxFee (
- txType:TxType ,
receipient:
string
, token:string
)
Parameters:
txType either Withdraw or Transfer receipientstring
the address the transaction is send to tokenstring
the token identifier e.g. ETH
Returns:
getTxInfo()¶
get transaction info
- Promise<TxInfo> getTxInfo (
- txHash:
string
)
Parameters:
txHashstring
the has of the tx you want the info about
Returns:
transfer()¶
transfers the specified amount to another address within the zksync rollup
- Promise<String> transfer (
- to:
string
, amount:number
, token:string
, account:string
)
Parameters:
tostring
address of the receipient amountnumber
amount to send in wei tokenstring
the token indentifier e.g. ETH accountstring
address of the account that wants to transfer (if left empty it will be taken from current signer)
Returns:
withdraw()¶
withdraws the specified amount from the rollup to a specific address
- Promise<String> withdraw (
- ethAddress:
string
, amount:number
, token:string
, account:string
)
Parameters:
ethAddressstring
the receipient address amountnumber
amount to withdraw in wei tokenstring
the token identifier e.g. ETH accountstring
address of the account that wants to withdraw (if left empty it will be taken from current signer)
Returns:
Type ABI¶
Source: index.d.ts
boolean
the anonymous (optional) ABIField [] the components (optional)boolean
the constant (optional) ABIField [] 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 namestring
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 blockstring
| [] 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) The maximum number of entries to retrieve (latest first). Quantity or Tag - (optional) (default: latest) Integer block number, or ‘latest’ for the last mined block or ‘pending’, ‘earliest’ for not yet mined transactions.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.
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. 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) 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
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) 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 zksync_config¶
Source: index.d.ts
zksync configuration.
string
the account to be used. if not specified, the first signer will be used. (optional)string
url of the zksync-server (optional)
Type BlockType¶
Source: index.d.ts
BlockNumber or predefined Block
= number
| 'latest'
| 'earliest'
| 'pending'