API Reference Java¶
Installing¶
The Incubed Java client uses JNI in order to call native functions. But all the native-libraries are bundled inside the jar-file. This jar file ha no dependencies and can even be used standalone:
like
java -cp in3.jar in3.IN3 eth_getBlockByNumber latest false
Examples¶
Using in3 directly¶
import in3.IN3;
public class HelloIN3 {
//
public static void main(String[] args) {
String blockNumber = args[0];
// create incubed
IN3 in3 = new IN3();
// configure
in3.setChainId(0x1); // set it to mainnet (which is also dthe default)
// execute the request
String jsonResult = in3.sendRPC("eth_getBlockByNumber",new Object[]{ blockNumber ,true});
....
}
}
Using the API¶
in3 also offers a API for getting Information directly in a structured way.
Reading Blocks¶
import java.util.*;
import in3.*;
import in3.eth1.*;
public class HelloIN3 {
//
public static void main(String[] args) throws Exception {
// create incubed
IN3 in3 = new IN3();
// configure
in3.setChainId(0x1); // set it to mainnet (which is also dthe default)
// read the latest Block including all Transactions.
Block latestBlock = in3.getEth1API().getBlockByNumber(Block.LATEST, true);
// Use the getters to retrieve all containing data
System.out.println("current BlockNumber : " + latestBlock.getNumber());
System.out.println("minded at : " + new Date(latestBlock.getTimeStamp()) + " by " + latestBlock.getAuthor());
// get all Transaction of the Block
Transaction[] transactions = latestBlock.getTransactions();
BigInteger sum = BigInteger.valueOf(0);
for (int i = 0; i < transactions.length; i++)
sum = sum.add(transactions[i].getValue());
System.out.println("total Value transfered in all Transactions : " + sum + " wei");
}
}
Calling Functions of Contracts¶
This Example shows how to call functions and use the decoded results. Here we get the struct from the registry.
import in3.*;
import in3.eth1.*;
public class HelloIN3 {
//
public static void main(String[] args) {
// create incubed
IN3 in3 = new IN3();
// configure
in3.setChainId(0x1); // set it to mainnet (which is also dthe default)
// call a contract, which uses eth_call to get the result.
Object[] result = (Object[]) in3.getEth1API().call( // call a function of a contract
"0x2736D225f85740f42D17987100dc8d58e9e16252", // address of the contract
"servers(uint256):(string,address,uint256,uint256,uint256,address)",// function signature
1); // first argument, which is the index of the node we are looking for.
System.out.println("url : " + result[0]);
System.out.println("owner : " + result[1]);
System.out.println("deposit : " + result[2]);
System.out.println("props : " + result[3]);
....
}
}
Sending Transactions¶
In order to send, you need a Signer. The SimpleWallet class is a basic implementation which can be used.
package in3;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import in3.*;
import in3.eth1.*;
public class Example {
//
public static void main(String[] args) throws IOException{
// create incubed
IN3 in3 = new IN3();
// configure
in3.setChainId(0x1); // set it to mainnet (which is also dthe default)
// create a wallet managing the private keys
SimpleWallet wallet = new SimpleWallet();
// add accounts by adding the private keys
String keyFile = "myKey.json";
String myPassphrase = "<secrect>";
// read the keyfile and decoded the private key
String account = wallet.addKeyStore(
Files.readString(Paths.get(keyFile)),
myPassphrase);
// use the wallet as signer
in3.setSigner(wallet);
String receipient = "0x1234567890123456789012345678901234567890";
BigInteger value = BigInteger.valueOf(100000);
// create a Transaction
TransactionRequest tx = new TransactionRequest();
tx.from = account;
tx.to = "0x1234567890123456789012345678901234567890";
tx.function = "transfer(address,uint256)";
tx.params = new Object[] { receipient, value };
String txHash = in3.getEth1API().sendTransaction(tx);
System.out.println("Transaction sent with hash = " + txHash);
}
}
Downloading¶
The jar file can be downloaded from the latest release. here.
Alternatively, If you wish to download Incubed using the maven package manager, add this to your pom.xml
<dependency>
<groupId>it.slock</groupId>
<artifactId>in3</artifactId>
<version>2.21</version>
</dependency>
After which, install in3 with mvn install
.
Building¶
For building the shared library you need to enable java by using the -DJAVA=true
flag:
git clone git@github.com:slockit/in3-c.git
mkdir -p in3-c/build
cd in3-c/build
cmake -DJAVA=true .. && make
You will find the in3.jar
in the build/lib - folder.
Android¶
In order to use Incubed in android simply follow these steps:
Step 1: Create a top-level CMakeLists.txt in android project inside app folder and link this to gradle. Follow the steps using this guide on howto link.
The Content of the CMakeLists.txt
should look like this:
cmake_minimum_required(VERSION 3.4.1)
# turn off FAST_MATH in the evm.
ADD_DEFINITIONS(-DIN3_MATH_LITE)
# loop through the required module and cretae the build-folders
foreach(module
core
verifier/eth1/nano
verifier/eth1/evm
verifier/eth1/basic
verifier/eth1/full
bindings/java
third-party/crypto
third-party/tommath
api/eth1)
file(MAKE_DIRECTORY in3-c/src/${module}/outputs)
add_subdirectory( in3-c/src/${module} in3-c/src/${module}/outputs )
endforeach()
Step 2: clone in3-c into the app
-folder or use this script to clone and update in3:
#!/usr/bin/env sh
#github-url for in3-c
IN3_SRC=https://github.com/slockit/in3-c.git
cd app
# if it exists we only call git pull
if [ -d in3-c ]; then
cd in3-c
git pull
cd ..
else
# if not we clone it
git clone $IN3_SRC
fi
# copy the java-sources to the main java path
cp -r in3-c/src/bindings/java/in3 src/main/java/
# but not the native libs, since these will be build
rm -rf src/main/java/in3/native
Step 3: Use methods available in app/src/main/java/in3/IN3.java from android activity to access IN3 functions.
Here is example how to use it:
Package in3¶
class Chain¶
Constants for Chain-specs.
MULTICHAIN¶
support for multiple chains, a client can then switch between different chains (but consumes more memory)
Type: static final long
class IN3¶
This is the main class creating the incubed client.
The client can then be configured.
setCacheTimeout¶
sets number of seconds requests can be cached.
publicnative void
setCacheTimeout(int
val);
arguments:
int |
val |
setConfig¶
sets config object in the client
publicnative void
setConfig(String
val);
arguments:
String |
val |
setNodeLimit¶
sets the limit of nodes to store in the client.
publicnative void
setNodeLimit(int
val);
arguments:
int |
val |
setKey¶
sets the client key to sign requests
publicnative void
setKey(byte[]
val);
arguments:
byte[] |
val |
setKey¶
sets the client key as hexstring to sign requests
publicvoid
setKey(String
val);
arguments:
String |
val |
getMaxCodeCache¶
number of max bytes used to cache the code in memory
publicnative int
getMaxCodeCache();
setMaxCodeCache¶
sets number of max bytes used to cache the code in memory
publicnative void
setMaxCodeCache(int
val);
arguments:
int |
val |
setMaxBlockCache¶
sets the number of blocks cached in memory
publicnative void
setMaxBlockCache(int
val);
arguments:
int |
val |
getRequestCount¶
the number of request send when getting a first answer
publicnative int
getRequestCount();
setRequestCount¶
sets the number of requests send when getting a first answer
publicnative void
setRequestCount(int
val);
arguments:
int |
val |
getSignatureCount¶
the number of signatures used to proof the blockhash.
publicnative int
getSignatureCount();
setSignatureCount¶
sets the number of signatures used to proof the blockhash.
publicnative void
setSignatureCount(int
val);
arguments:
int |
val |
getMinDeposit¶
min stake of the server.
Only nodes owning at least this amount will be chosen.
publicnative long
getMinDeposit();
setMinDeposit¶
sets min stake of the server.
Only nodes owning at least this amount will be chosen.
publicnative void
setMinDeposit(long
val);
arguments:
long |
val |
getReplaceLatestBlock¶
if specified, the blocknumber latest will be replaced by blockNumber- specified value
publicnative int
getReplaceLatestBlock();
setReplaceLatestBlock¶
replaces the latest with blockNumber- specified value
publicnative void
setReplaceLatestBlock(int
val);
arguments:
int |
val |
getFinality¶
the number of signatures in percent required for the request
publicnative int
getFinality();
setFinality¶
sets the number of signatures in percent required for the request
publicnative void
setFinality(int
val);
arguments:
int |
val |
setMaxAttempts¶
sets the max number of attempts before giving up
publicnative void
setMaxAttempts(int
val);
arguments:
int |
val |
setSigner¶
sets the signer or wallet.
publicvoid
setSigner(Signer
signer);
arguments:
Signer | signer |
getTimeout¶
specifies the number of milliseconds before the request times out.
increasing may be helpful if the device uses a slow connection.
publicnative int
getTimeout();
setTimeout¶
specifies the number of milliseconds before the request times out.
increasing may be helpful if the device uses a slow connection.
publicnative void
setTimeout(int
val);
arguments:
int |
val |
getChainId¶
servers to filter for the given chain.
The chain-id based on EIP-155.
publicnative long
getChainId();
setChainId¶
sets the chain to be used.
The chain-id based on EIP-155.
publicnative void
setChainId(long
val);
arguments:
long |
val |
isAutoUpdateList¶
if true the nodelist will be automaticly updated if the lastBlock is newer
publicnative boolean
isAutoUpdateList();
setAutoUpdateList¶
activates the auto update.if true the nodelist will be automaticly updated if the lastBlock is newer
publicnative void
setAutoUpdateList(boolean
val);
arguments:
boolean |
val |
getStorageProvider¶
provides the ability to cache content
publicStorageProvider
getStorageProvider();
setStorageProvider¶
provides the ability to cache content like nodelists, contract codes and validatorlists
publicvoid
setStorageProvider(StorageProvider
val);
arguments:
StorageProvider | val |
send¶
send a request.
The request must a valid json-string with method and params
publicnative String
send(String
request);
arguments:
String |
request |
sendobject¶
send a request but returns a object like array or map with the parsed response.
The request must a valid json-string with method and params
publicnative Object
sendobject(String
request);
arguments:
String |
request |
sendRPC¶
send a RPC request by only passing the method and params.
It will create the raw request from it and return the result.
arguments:
String |
method |
Object[] |
params |
sendRPCasObject¶
send a RPC request by only passing the method and params.
It will create the raw request from it and return the result.
arguments:
String |
method |
Object[] |
params |
IN3¶
public IN3();
setTransport¶
sets The transport interface.
This allows to fetch the result of the incubed in a different way.
publicvoid
setTransport(IN3Transport
newTransport);
arguments:
IN3Transport |
newTransport |
forChain¶
create a Incubed client using the chain-config.
if chainId is Chain.MULTICHAIN, the client can later be switched between different chains, for all other chains, it will be initialized only with the chainspec for this one chain (safes memory)
arguments:
long |
chainId |
class IN3DefaultTransport¶
class JSON¶
internal helper tool to represent a JSON-Object.
Since the internal representation of JSON in incubed uses hashes instead of name, the getter will creates these hashes.
get¶
gets the property
publicObject
get(String
prop);
arguments:
String |
prop | the name of the property. |
returns: Object
: the raw object.
put¶
adds values.
This function will be called from the JNI-Iterface.
Internal use only!
arguments:
int |
key | the hash of the key |
Object |
val | the value object |
getLong¶
returns the property as long
publiclong
getLong(String
key);
arguments:
String |
key | the propertyName |
returns: long
: the long value
getBigInteger¶
returns the property as BigInteger
publicBigInteger
getBigInteger(String
key);
arguments:
String |
key | the propertyName |
returns: BigInteger
: the BigInteger value
getStringArray¶
returns the property as StringArray
publicString[]
getStringArray(String
key);
arguments:
String |
key | the propertyName |
returns: String[]
: the array or null
getString¶
returns the property as String or in case of a number as hexstring.
publicString
getString(String
key);
arguments:
String |
key | the propertyName |
returns: String
: the hexstring
toString¶
publicString
toString();
hashCode¶
publicint
hashCode();
asStringArray¶
casts the object to a String[]
public staticString[]
asStringArray(Object
o);
arguments:
Object |
o |
class TempStorageProvider¶
a simple Storage Provider storing the cache in the temp-folder.
enum Proof¶
The Proof type indicating how much proof is required.
The enum type contains the following values:
none | 0 | No Verification. |
standard | 1 | Standard Verification of the important properties. |
full | 2 | Full Verification including even uncles wich leads to higher payload. |
interface IN3Transport¶
interface Signer¶
a Interface responsible for signing data or transactions.
prepareTransaction¶
optiional method which allows to change the transaction-data before sending it.
This can be used for redirecting it through a multisig.
arguments:
IN3 | in3 |
TransactionRequest | tx |
Package in3.eth1¶
class API¶
a Wrapper for the incubed client offering Type-safe Access and additional helper functions.
getBlockByNumber¶
finds the Block as specified by the number.
use Block.LATEST
for getting the lastest block.
arguments:
long |
block | |
boolean |
includeTransactions | < the Blocknumber < if true all Transactions will be includes, if not only the transactionhashes |
getBlockByHash¶
Returns information about a block by hash.
arguments:
String |
blockHash | |
boolean |
includeTransactions | < the Blocknumber < if true all Transactions will be includes, if not only the transactionhashes |
getChainId¶
Returns the EIP155 chain ID used for transaction signing at the current best block.
Null is returned if not available.
publicString
getChainId();
call¶
calls a function of a smart contract and returns the result.
arguments:
TransactionRequest | request | |
long |
block | < the transaction to call. < the Block used to for the state. |
returns: Object
: the decoded result. if only one return value is expected the Object will be returned, if not an array of objects will be the result.
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.
arguments:
TransactionRequest | request | |
long |
block | < the transaction to call. < the Block used to for the state. |
returns: long
: the gas required to call the function.
getBalance¶
Returns the balance of the account of given address in wei.
arguments:
String |
address |
long |
block |
getStorageAt¶
Returns the value from a storage position at a given address.
arguments:
String |
address |
BigInteger |
position |
long |
block |
getBlockTransactionCountByHash¶
Returns the number of transactions in a block from a block matching the given block hash.
publiclong
getBlockTransactionCountByHash(String
blockHash);
arguments:
String |
blockHash |
getBlockTransactionCountByNumber¶
Returns the number of transactions in a block from a block matching the given block number.
publiclong
getBlockTransactionCountByNumber(long
block);
arguments:
long |
block |
getFilterChangesFromLogs¶
Polling method for a filter, which returns an array of logs which occurred since last poll.
arguments:
long |
id |
getFilterChangesFromBlocks¶
Polling method for a filter, which returns an array of logs which occurred since last poll.
publicString[]
getFilterChangesFromBlocks(long
id);
arguments:
long |
id |
getFilterLogs¶
Polling method for a filter, which returns an array of logs which occurred since last poll.
arguments:
long |
id |
getLogs¶
Polling method for a filter, which returns an array of logs which occurred since last poll.
arguments:
LogFilter | filter |
getTransactionByBlockHashAndIndex¶
Returns information about a transaction by block hash and transaction index position.
arguments:
String |
blockHash |
int |
index |
getTransactionByBlockNumberAndIndex¶
Returns information about a transaction by block number and transaction index position.
arguments:
long |
block |
int |
index |
getTransactionByHash¶
Returns the information about a transaction requested by transaction hash.
publicTransaction
getTransactionByHash(String
transactionHash);
arguments:
String |
transactionHash |
getTransactionCount¶
Returns the number of transactions sent from an address.
arguments:
String |
address |
long |
block |
getTransactionReceipt¶
Returns the number of transactions sent from an address.
publicTransactionReceipt
getTransactionReceipt(String
transactionHash);
arguments:
String |
transactionHash |
getUncleByBlockNumberAndIndex¶
Returns information about a uncle of a block number and uncle index position.
Note: An uncle doesn’t contain individual transactions.
arguments:
long |
block |
int |
pos |
getUncleCountByBlockHash¶
Returns the number of uncles in a block from a block matching the given block hash.
publiclong
getUncleCountByBlockHash(String
block);
arguments:
String |
block |
getUncleCountByBlockNumber¶
Returns the number of uncles in a block from a block matching the given block hash.
publiclong
getUncleCountByBlockNumber(long
block);
arguments:
long |
block |
newBlockFilter¶
Creates a filter in the node, to notify when a new block arrives.
To check if the state has changed, call eth_getFilterChanges.
publiclong
newBlockFilter();
newLogFilter¶
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)”
publiclong
newLogFilter(LogFilter
filter);
arguments:
LogFilter | filter |
uninstallFilter¶
uninstall filter.
publicboolean
uninstallFilter(long
filter);
arguments:
long |
filter |
sendRawTransaction¶
Creates new message call transaction or a contract creation for signed transactions.
publicString
sendRawTransaction(String
data);
arguments:
String |
data |
returns: String
: transactionHash
sendTransaction¶
sends a Transaction as desribed by the TransactionRequest.
This will require a signer to be set in order to sign the transaction.
publicString
sendTransaction(TransactionRequest
tx);
arguments:
TransactionRequest | tx |
class Block¶
represents a Block in ethereum.
getTotalDifficulty¶
returns the total Difficulty as a sum of all difficulties starting from genesis.
publicBigInteger
getTotalDifficulty();
getTransactionsRoot¶
the roothash of the merkletree containing all transaction of the block.
publicString
getTransactionsRoot();
getTransactionReceiptsRoot¶
the roothash of the merkletree containing all transaction receipts of the block.
publicString
getTransactionReceiptsRoot();
getStateRoot¶
the roothash of the merkletree containing the complete state.
publicString
getStateRoot();
getTransactionHashes¶
the transaction hashes of the transactions in the block.
publicString[]
getTransactionHashes();
getSha3Uncles¶
the roothash of the merkletree containing all uncles of the block.
publicString
getSha3Uncles();
hashCode¶
publicint
hashCode();
class Log¶
a log entry of a transaction receipt.
isRemoved¶
true when the log was removed, due to a chain reorganization.
false if its a valid log.
publicboolean
isRemoved();
getLogIndex¶
integer of the log index position in the block.
null when its pending log.
publicint
getLogIndex();
gettTansactionIndex¶
integer of the transactions index position log was created from.
null when its pending log.
publicint
gettTansactionIndex();
getTransactionHash¶
Hash, 32 Bytes - hash of the transactions this log was created from.
null when its pending log.
publicString
getTransactionHash();
getBlockHash¶
Hash, 32 Bytes - hash of the block where this log was in.
null when its pending. null when its pending log.
publicString
getBlockHash();
getBlockNumber¶
the block number where this log was in.
null when its pending. null when its pending log.
publiclong
getBlockNumber();
getTopics¶
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.)
publicString[]
getTopics();
class LogFilter¶
Log configuration for search logs.
getFromBlock¶
publiclong
getFromBlock();
getToBlock¶
publiclong
getToBlock();
getAddress¶
publicString
getAddress();
getTopics¶
publicObject[]
getTopics();
getLimit¶
publicint
getLimit();
class SimpleWallet¶
a simple Implementation for holding private keys to sing data or transactions.
addRawKey¶
adds a key to the wallet and returns its public address.
publicString
addRawKey(String
data);
arguments:
String |
data |
addKeyStore¶
adds a key to the wallet and returns its public address.
arguments:
String |
jsonData |
String |
passphrase |
prepareTransaction¶
optiional method which allows to change the transaction-data before sending it.
This can be used for redirecting it through a multisig.
arguments:
IN3 | in3 |
TransactionRequest | tx |
class Transaction¶
represents a Transaction in ethereum.
getBlockNumber¶
the block number of the block containing this transaction.
publiclong
getBlockNumber();
getCreatedContractAddress¶
the address of the deployed contract (if successfull)
publicString
getCreatedContractAddress();
getSignature¶
the signature of the sender - a array of the [ r, s, v]
publicString[]
getSignature();
class TransactionReceipt¶
represents a Transaction receipt in ethereum.
getBlockNumber¶
the block number of the block containing this transaction.
publiclong
getBlockNumber();
getCreatedContractAddress¶
the address of the deployed contract (if successfull)
publicString
getCreatedContractAddress();
getTo¶
20 Bytes - The address of the receiver.
null when it’s a contract creation transaction.
publicString
getTo();
getLogsBloom¶
256 Bytes - A bloom filter of logs/events generated by contracts during transaction execution.
Used to efficiently rule out transactions without expected logs
publicString
getLogsBloom();
getRoot¶
32 Bytes - Merkle root of the state trie after the transaction has been executed (optional after Byzantium hard fork EIP609).
publicString
getRoot();
getStatus¶
success of a Transaction.
true indicates transaction failure , false indicates transaction success. Set for blocks mined after Byzantium hard fork EIP609, null before.
publicboolean
getStatus();
class TransactionRequest¶
represents a Transaction Request which should be send or called.
getFrom¶
publicString
getFrom();
getTo¶
publicString
getTo();
getValue¶
publicBigInteger
getValue();
getNonce¶
publiclong
getNonce();
getGas¶
publiclong
getGas();
getGasPrice¶
publiclong
getGasPrice();
getFunction¶
publicString
getFunction();
getParams¶
publicObject[]
getParams();
getTransactionJson¶
publicString
getTransactionJson();