Getting Started
What's new?
In caver-java 1.5.0, we adopt Common Architecture. Common Architecture is a new software architecture for kaia development environment, which is shared by all kaia SDKs (caver-js/caver-java). It is designed for your streamlined development experience and ease of extensibility to other programming languages.
As caver-java is updated to 1.5.0, the APIs used in 1.4.0 are deprecated except for some APIs.
The APIs newly provided in caver-java 1.5.0 are as follows.
caver.account
caver.account is a package used to update AccountKey, which could be one or more public keys (AccountKeyPublic, AccountKeyWeightedMultiSig, and AccountKeyRoleBased) or a special type of keys (AccountKeyLegacy and AccountKeyFail), for a kaia account.
caver.account
replacescaver.tx.account
in caver-java 1.4.0
caver.wallet
caver.wallet is a package that manages Keyring instances in in-memory wallet. A Keyring is an instance that stores the address of a kaia account and its private key(s), and it is used when the address of this account signs a transaction. caver.wallet accepts all types of Keyring (SingleKeyring, MultipleKeyring, and RoleBasedKeyring) and manages them with their kaia account address.
caver.wallet
replacescaver.crypto
in caver-java 1.4.0caver.wallet.KeyStore
replacescaver.wallet.WalletFile
in caver-java 1.4.0
caver.transaction
caver.transaction is a package that provides functionality related to Transaction.
caver.transaction
replacescaver.tx
in caver-java 1.4.0
caver.rpc
caver.rpc is a package that provides functionality related to rpc call with kaia Node.
caver.rpc.klay
andcaver.rpc.net
replacesKlay
,Net
interfaces in caver-java 1.4.0, respectively
caver.util
caver.utils provides utility functions.
caver.contract
caver.contract
is a package that makes it easy to handle smart contracts in kaia. With caver.contract, you can deploy smart contracts and execute them by calling their functions. caver.contract
first converts smart contract functions and events from ABI(Application Binary Interface), calls those functions, and obtains the event information.
Prerequisites
Adding a Repository
A library repository should be added before using IPFS. Please add the following repository first.
maven
<repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository></repositories>
gradle
allprojects { repositories { ... maven { url 'https://jitpack.io' } }}
Adding a Dependency
maven
<dependency> <groupId>com.klaytn.caver</groupId> <artifactId>core</artifactId> <version>1.5.0</version></dependency>
gradle
implementation 'com.klaytn.caver:core:1.5.0'
If you want to use Android dependency, just append -android at the end of the version string. (e.g. 1.0.1-android)
If you want to see details of the JSON-RPC requests and responses, please include LOGBack dependency in your project. Below is a Gradle build file example. You can add the dependency to Maven as well. Since caver-java uses the SLF4J logging facade, you can switch to your preferred logging framework instead of LOGBack.
implementation "ch.qos.logback:logback-classic:1.2.3"
Note: In the central repository, the RC, Android, and Java versions are listed together. If you use wildcards to get a version, you may be using a version that is not appropriate for your platform.
Command-line Tool
The command-line tool allows you to generate Solidity smart contract function wrappers from the command line.
Installation (Homebrew)
Java 1.8+ is required to install this.
$ brew tap klaytn/klaytn$ brew install caver-java
After installation you can run command 'caver-java' like below:
$ caver-java solidity generate -b <smart-contract>.bin -a <smart-contract>.abi -o <outputPath> -p <packagePath>
Installation (Other)
Currently, we do not support other package managers. As another solution, we provide a method to build the CLI below.
-
Download or fork caver-java.
-
Do task 'shadowDistZip' in the console module using Gradle. As a result,
console/build/distributions/console-shadow-{version}.zip
is generated.$ ./gradlew :console:shadowDistZip -
Unzip the zip file in the build directory
$ unzip ./console/build/distributions/console-shadow-{version}.zip -
Execute the binary file to run the command-line tool like below. You can find a shell script file for macOS users and a batch file for Window users.
$ ./console/build/distributions/console-shadow-{version}/bin/caver-java
Sending KAIA at a glance
This section describes a simple example of using a keystore file
to send KAIA with a value transfer transaction. The keystore file can be exported from Kaia Wallet. If you need KAIA for testing, you can get test KAIA from the Kaia Faucet.
When developing, it's best practice to use an account that isn't associated with any real funds. A good way to do this is to make a new browser profile (on Chrome, Brave, Firefox, etc) and install Kaia Wallet on that browser, and never send this wallet money.
public void sendingKLAY() throws IOException, CipherException, TransactionException { Caver caver = new Caver(Caver.BAOBAB_URL); //Read keystore json file. File file = new File("./keystore.json"); //Decrypt keystore. ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); KeyStore keyStore = objectMapper.readValue(file, KeyStore.class); AbstractKeyring keyring = caver.wallet.keyring.decrypt(keyStore, "password"); //Add to caver wallet. caver.wallet.add(keyring); BigInteger value = new BigInteger(caver.utils.convertToPeb(BigDecimal.ONE, "KLAY")); //Create a value transfer transaction ValueTransfer valueTransfer = caver.transaction.valueTransfer.create( TxPropertyBuilder.valueTransfer() .setFrom(keyring.getAddress()) .setTo("0x8084fed6b1847448c24692470fc3b2ed87f9eb47") .setValue(value) .setGas(BigInteger.valueOf(25000)) ); //Sign to the transaction valueTransfer.sign(keyring); //Send a transaction to the kaia blockchain platform (kaia) Bytes32 result = caver.rpc.klay.sendRawTransaction(valueTransfer.getRawTransaction()).send(); if(result.hasError()) { throw new RuntimeException(result.getError().getMessage()); } //Check transaction receipt. TransactionReceiptProcessor transactionReceiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15); TransactionReceipt.TransactionReceiptData transactionReceipt = transactionReceiptProcessor.waitForTransactionReceipt(result.getResult()); }
Starting with caver-java
Connecting to a kaia Node
If you are running an EN, you can connect it to your own node by changing the host and port like below:
Caver caver = new Caver("http://your.en.url:8551/");
Managing Keyrings
Keyring
is a structure that contains the address of the kaia account and the private key(s).
Keyring
can be classified into three types depending on the type of key being stored: SingleKeyring
to store one address and one private key, MultipleKeyring
to store one address and multiple private keys, and RoleBasedKeyring
to store one address and one or more private keys for each role.
SingleKeyring
defines key
property inside, and this key
stores one private key.
MultipleKeyring
defines keys
property inside, and this keys
is implemented as an array to store multiple private keys.
The keys
property defined in RoleBasedKeyring
is implemented as a List object having 3 arrays of private key(s) as its elements (empty keys
will look like [ [], [], [] ]
) and so that it can include multiple keys for each role
. The first element of the array is filled with the private key(s) to be used for roleTransactionKey
, the second element the private key(s) to be used for roleAccountUpdateKey
, and the third element the private key(s) to be used for roleFeePayerKey
.
Creating a Keyring
Generating a SingleKeyring
You can randomly generate a single keyring as shown below.
SingleKeyring keyring = caver.wallet.keyring.generate();
Creating a SingleKeyring from private key
Also, if you own a specific private key, you can use it to create a keyring as shown below.
String privateKey = "0x{private key in hex}";SingleKeyring keyring = caver.wallet.keyring.createFromPrivateKey(privateKey);
Creating a SingleKeyring with a private key and an address
If your private key for your kaia account is decoupled from the address, you can create a keyring using the given address and the given private key like below.
String address = "0x{address in hex}";String privateKey = "0x{private key in hex}";SingleKeyring keyring = caver.wallet.keyring.createWithSingleKey(address, privateKey);
Also, you can derive SingleKeyring instance from kaia wallet key.
String klaytnWalletKey = "0x{private key}0x{type}0x{address in hex}";SingleKeyring keyring = caver.wallet.keyring.createFromKlaytnWalletKey(klaytnWalletKey);
Creating a MultipleKeyring with multiple private keys
If you want to use multiple private keys, you can create a MultipleKeyring
using an address and multiple private keys. The below examples show how to create a MultipleKeyring
with multiple private keys.
String address = "0x{address in hex}";String[] privateKeyArray = new String[] {"0x{private key#1}", "0x{private key#2}", "0x{private key#3}"};MultipleKeyring multipleKeyring = caver.wallet.keyring.createWithMultipleKey(address, privateKeyArray);
Creating a RoleBasedKeyring with private keys
To use different private key(s) for each role
, caver.wallet.keyring.createWithRoleBasedKey
is used. Each array element represents a role described in RoleBasedKeyring
. The example below shows how to create a RoleBasedKeyring
instance from different keys for each role.
String address = "0x{address in hex}";String[][] privateKeyArr = new String[][] { //roleTransactionKey { "0x{privateKey in hex}", "0x{privateKey in hex}", "0x{privateKey in hex}", }, //roleAccountUpdateKey { "0x{privateKey in hex}", "0x{privateKey in hex}", "0x{privateKey in hex}", }, //roleFeePayerKey { "0x{privateKey in hex}", "0x{privateKey in hex}", "0x{privateKey in hex}", },};RoleBasedKeyring keyring = caver.wallet.keyring.createWithRoleBasedKey(address, Arrays.asList(privateKeyArr));