If you use a different version of the Node (for example, Node v15), utilize the Node Version Manager(nvm) to install and use the version supported by caver-js.
Installation
To try it out, install caver-js with npm using the following command:
$ npm install caver-js
Note: package.json file should exist on the same install path. If it does not exist, package.json can be generated via npm init.
To install a specific version of caver-js, try the following command:
$ npm install caver-js@X.X.X
Starting with caver-js
Once you have finished installing caver-js, you can now connect to a Klaytn Node using caver-js.
To practice the examples below, first create a test file in the working directory.
$touchtest.js
You can see the test.js file created in the working directory.
Running the above code gives you the following result.
$node./test.jsKlaytn/v1.4.0/linux-amd64/go1.14.1
If you see the output of console.log like above, proceed with the steps below. The version number can be different according to the version of the connected Klaytn node.
Connecting to a Klaytn Node
You can import the caver-js module and connect it to a Klaytn Node in the Baobab testnet as shown in the example below:
Keyring is a structure that contains the address of the Klaytn 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 store 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 two-dimensional array (empty keys will look like [ [], [], [] ]) that 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.
The execution result is shown above. Member variables defined inside the instance can be accessed through keyring.address and keyring.key.
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.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Create a keyring from a private keyconstkeyringFromPrivateKey=caver.wallet.keyring.createFromPrivateKey('0x{private key}')console.log(keyringFromPrivateKey)}testFunction()
Running the above code gives you the following result.
The result of caver.wallet.keyring.createFromPrivateKey, like the result of caver.wallet.keyring.generate above, is a SingleKeyring instance with an address defined inside it and a [PrivateKey] instance in keyring.key.
Creating a SingleKeyring with a private key and an address
If your private key for your Klaytn account is decoupled from the address, you can create a keyring using the given address and the given private key like below.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Create a keyring with an address and a private keyconstkeyring=caver.wallet.keyring.createWithSingleKey('0x{address in hex}','0x{private key}')console.log(keyring)// Create a keyring from a KlaytnWalletKey const keyringFromKlaytnWalletKey = caver.wallet.keyring.createFromKlaytnWalletKey('0x{private key}0x{type}0x{address in hex}')
console.log(keyringFromKlaytnWalletKey)}testFunction()
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.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Create a keyring with an address and private keys const keyring = caver.wallet.keyring.createWithMultipleKey('0x{address in hex}', [ '0x{private key1}', '0x{private key2}' ])
console.log(keyring)}testFunction()
Running the above code gives you the following result.
As you can see, _keys has multiple PrivateKey instances in the array. Member variables defined inside the instance can be accessed through keyring.address and keyring.keys.
Creating a RoleBasedKeyring with private keys
To use different private key(s) for each role, caver.wallet.keyring.createWithRoleBasedKey is used instead. 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.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Create a keyring with an address and private keys defined by each rolesconstkeyring=caver.wallet.keyring.createWithRoleBasedKey('0x{address in hex}', [ [ '0x{private key1}','0x{private key2}','0x{private key3}' ], [ '0x{private key4}'], [ '0x{private key5}','0x{private key6}' ], ])console.log(keyring)}testFunction()
Running the above code gives you the following result.
Looking at the output above, the first element of the keys array, roleTransactionKey, has three PrivateKey instances, and the second element, roleAccountUpdateKey, has one PrivateKey instance. And the last element of the array, roleFeePayerKey, has two PrivateKey instances.
Note: Calling functions related to keyring (caver.wallet.keyring) or wallet (caver.wallet) do not affect the actual Klaytn blockchain platform (Klaytn).
Adding Keyrings to caver-js
You can use a keyring easily by using the in-memory wallet provided by caver-js. The following examples illustrate how to add a keyring to a wallet using a keyring instance and a keystore file generated by Klaytn Wallet.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Using a keyring instanceconstkeyring=caver.wallet.keyring.generate()caver.wallet.add(keyring)console.log(caver.wallet.getKeyring(keyring.address))// Using a keystore fileconstdecrypted=caver.wallet.keyring.decrypt({ version:4, id:'9c12de05-0153-41c7-a8b7-849472eb5de7', address:'0xc02cec4d0346bf4124deeb55c5216a4138a40a8c', keyring: [ { ciphertext:'eacf496cea5e80eca291251b3743bf93cdbcf7072efc3a74efeaf518e2796b15', cipherparams: { iv:'d688a4319342e872cefcf51aef3ec2da' }, cipher:'aes-128-ctr', kdf:'scrypt', kdfparams: { dklen:32, salt:'c3cee502c7157e0faa42386c6d666116ffcdf093c345166c502e23bc34e6ba40', n:4096, r:8, p:1 }, mac:'4b49574f3d3356fa0d04f73e07d5a2a6bbfdd185bedfa31f37f347bc98f2ef26' } ] },'password')caver.wallet.add(decrypted)console.log(caver.wallet.getKeyring(decrypted.address))}testFunction()
Looking at the output above, you can query your keyring from caver.wallet after adding it to caver.wallet.
If you have an address and private key(s) to use, you can easily create a keyring and add it directly to caver.wallet via caver.wallet.newKeyring.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Add to wallet with an address and a private keyconstaddedSingle=caver.wallet.newKeyring('0x{address in hex}','0x{private key1}')console.log(caver.wallet.getKeyring(addedSingle.address))// Add to wallet with an address and private keys const addedMultiple = caver.wallet.newKeyring('0x{address in hex}', ['0x{private key2}', '0x{private key3}', '0x{private key4}'])
console.log(caver.wallet.getKeyring(addedMultiple.address))// Add to wallet with an address and private keys defined by each rolesconstaddedRoleBased=caver.wallet.newKeyring('0x{address in hex}', [ ['0x{private key5}','0x{private key6}','0x{private key7}'], ['0x{private key8}','0x{private key9}'], ['0x{private key10}','0x{private key11}'] ])console.log(caver.wallet.getKeyring(addedRoleBased.address))}testFunction()
Running the above code gives you the following result. The result of the above code execution is shown below. When caver.wallet.newKeyring is executed with a private key, a Keyring instance with one private key is created and added to caver.wallet. For multiple private keys, a Keyring instance with multiple private keys is created. When passing one or more private keys for each role as arguments, a Keyring instance with a different private key(s) for each role is created and also added to the caver.wallet.
caver.wallet.add or caver.wallet.newKeyring returns a Keyring instance after adding it to caver.wallet.
Sending a Transaction
This section will show you how to send KLAY using caver-js on the Baobab network.
Getting KLAY via Baobab Faucet
If you need KLAY for testing, you can get Baobab testnet KLAY from the Klaytn Wallet. Log in to the Klaytn Wallet using the private key or the keystore file and receive Baobab testnet KLAY via the faucet for testing.
Sending a Value Transfer Transaction
You can use a caver-js wallet to generate a signature of a transaction. You have to go through two steps below to send the transaction to the network.
Sign a transaction
If the keyring you want to use is added to caver.wallet, you can use caver.wallet.sign function to sign.
If you manage the keyring separately without adding it to caver.wallet, you can sign the transaction through transaction.sign function.
Send the RLP-encoded string of the signed transaction to the Klaytn via caver.rpc.klay.sendRawTransaction.
Note: The sender should have enough number of KLAY.
Sign a transaction
Before sending a transaction to Klaytn, you should sign a transaction first.
Below is an example of how to sign a transaction if a keyring is added to the caver.wallet.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Add a keyring to caver.walletconstkeyring=caver.wallet.keyring.createFromPrivateKey('0x{private key}')caver.wallet.add(keyring)// Create a value transfer transactionconstvalueTransfer=caver.transaction.valueTransfer.create({ from:keyring.address, to:'0x176ff0344de49c04be577a3512b6991507647f72', value:1, gas:30000, })// Sign the transaction via caver.wallet.signawaitcaver.wallet.sign(keyring.address, valueTransfer)constrlpEncoded=valueTransfer.getRLPEncoding()console.log(`RLP-encoded string: ${rlpEncoded}`)}testFunction()
The above code adds a keyring to caver.wallet, creates a transaction, and signs the transaction through caver.wallet.sign.
Running the above code gives you the following result. When the above code is executed, the RLP-encoded string of the transaction is shown below. (The RLP-encoded string output you got could be different from the string output shown below.)
Send the RLP-encoded string of the signed transaction to the Klaytn
Now you can send a signed transaction to the network like below. If you want to run the below example, replace 0x{RLP-encoded string} with the value of rlpEncoded above.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {constrlpEncoding=`0x{RLP-encoded string}`// Send the transaction using `caver.rpc.klay.sendRawTransaction`.constreceipt=awaitcaver.rpc.klay.sendRawTransaction(rlpEncoding)console.log(receipt)}testFunction()
Running the above code gives you the following result. When the above code is executed, the receipt of the transaction is shown below.
If you want to sign a transaction and send it to the network without caver.wallet, see the example below.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {// Create a value transfer transactionconstkeyring=caver.wallet.keyring.createFromPrivateKey('0x{private key}')constvalueTransfer=caver.transaction.valueTransfer.create({ from:keyring.address, to:'0x176ff0344de49c04be577a3512b6991507647f72', value:1, gas:30000, })// Sign the transaction via transaction.signawaitvalueTransfer.sign(keyring)// Send the transaction to the Klaytn using `caver.rpc.klay.sendRawTransaction`.constreceipt=awaitcaver.rpc.klay.sendRawTransaction(valueTransfer)console.log(receipt)}testFunction()
When the above code is executed, the receipt of the transaction is printed like the previous example.
Checking Receipts
You can use the promise or event emitter to get the receipt of the transaction when you transfer the transaction to the Klaytn by caver.rpc.klay.sendRawTransaction.
The following example shows how to get a receipt using promises and event emitters.
// Using a promise - async/awaitconstreceipt=awaitcaver.rpc.klay.sendRawTransaction(rawTransaction)console.log(receipt)// Using a promisecaver.rpc.klay.sendRawTransaction(rawTransaction).then(console.log)// Using an event emittercaver.rpc.klay.sendRawTransaction(rawTransaction).on('receipt',console.log)
As described in the example above, you can get the result of sending a transaction through the promise and event emitter. The transactionHash field is defined inside the receipt object. You can use caver.rpc.klay.getTransactionReceipt RPC call with receipt.transactionHash to query the receipt of a transaction at any time from the network after the transaction is included in a block. The example below shows how to get a receipt using the caver.rpc.klay.getTransactionReceipt RPC call.
Klaytn provides various transaction types for extensibility and performance. For more information, see Transactions. This section describes some examples that can be used with caver-js.
Fee Delegation
Klaytn provides Fee Delegation feature. Here's an example of making a RLP-encoded transaction when you are a sender of this kind of transaction:
When the above code is executed, the RLP-encoded string will be printed. (The RLP-encoded string output you got could be different from the string output shown below.)
The fee payer can send the transaction to the Klaytn after attaching the feePayerSignatures to the RLP-encoded string (rawTransaction) signed by the transaction sender. If caver.wallet also has the fee payer's key, the fee payer's signature can be injected into feeDelegatedTx by calling caver.wallet.signAsFeePayer(feePayer.address, feeDelegatedTx). Otherwise, the fee payer has to create a feeDelegatedTx from the RLP-encoded string signed by the sender and add the fee payer's sign onto it, as illustrated below. If you want to run the below example, replace 0x{RLP-encoded string} with the value of rlpEncoded above.
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {constfeePayer=caver.wallet.keyring.createFromPrivateKey('0x{private key}')caver.wallet.add(feePayer)constrlpEncoded='0x{RLP-encoded string}'constfeeDelegateTxFromRLPEncoding=caver.transaction.feeDelegatedValueTransfer.create(rlpEncoded)// Set the fee payer address.feeDelegateTxFromRLPEncoding.feePayer =feePayer.addressawaitcaver.wallet.signAsFeePayer(feePayer.address, feeDelegateTxFromRLPEncoding)console.log(feeDelegateTxFromRLPEncoding.getRLPEncoding())}testFunction()
When the above code is executed, the RLP-encoded string including the sender's signatures and fee payer's signatures is printed like below. (The output you got could be different from the string output shown below.)
The transaction is now signed by both the sender and the fee payer, and it can now be sent over the network. Replace 0x{RLP-encoded string} with the RLP-encoded string output of the example code above.
Running the above code gives you the following result. Through the execution result of the above code, you can check the FeeDelegatedValueTransfer transaction result.
If you want to change the private key(s) for your Klaytn account, there are 3 important things you need to remember:
Klaytn validates every transaction you send to it.
The validation requires your public keys which exactly corresponds to your private key(s).
Thus, changing your private key(s) into the new one(s) is always bepreceded by changing your old public key(s) to the new one(s). The new public key(s) must be derived from the new private key(s).
Keeping the 3 things above in your mind, you can change your private key(s) by following the steps below:
Prepare the new private key(s) to create a new keyring.
Create a keyring by its type (Single keyring, Multiple keyring, or Role-based keyring) you need.
Generate an Account instance from the new keyring. This Account instance holds the new public key(s) for your Klaytn account.
Send AccountUpdate transaction including Account instance to Klaytn.
Finally, replace your old keyring to the new one that was created in Step 2.
To change your AccountKey, you must provide an Account instance for the account field in the input argument object of caver.transaction.accountUpdate. An Account instance contains the address of the Klaytn account and the AccountKey to be updated.
The code below is an example code that changes the private key(s) you use for your Klaytn account along with changing AccountKey of your Klaytn account to AccountKeyPublic. Don't forget to prepare your new private key(s).
// test.jsconstCaver=require('caver-js')constcaver=newCaver('https://public-en-baobab.klaytn.net/')asyncfunctiontestFunction() {let sender =caver.wallet.keyring.createFromPrivateKey('0x{private key}')caver.wallet.add(sender)constnewPrivateKey=caver.wallet.keyring.generateSingleKey()console.log(`new private key string: ${newPrivateKey}`)constnewKeyring=caver.wallet.keyring.createWithSingleKey(sender.address, newPrivateKey)// create an Account instanceconstaccount=newKeyring.toAccount()constupdateTx=caver.transaction.accountUpdate.create({ from:sender.address, account: account, gas:50000, })awaitcaver.wallet.sign(sender.address, updateTx)constreceipt=awaitcaver.rpc.klay.sendRawTransaction(updateTx)console.log(receipt)// Update the keyring in caver.wallet for signing afterward. sender =caver.wallet.updateKeyring(newKeyring)}testFunction()
If the above code is executed successfully, you no longer are able to use the old private key(s) to sign any transaction with the old keyring. So you must update the old keyring with the newKeyring through caver.wallet.updateKeyring(newKeyring). Once it is updated, the signing will be done by the newly updated private key(s).
Running the above code gives you the following result. In the execution result of the above code, the result of the private key and the account update that you should newly use are printed like below.
Here comes how to update AccountKey of your Klaytn account with multiple [AccountKeys]? The example below explains how to create an Account instance with multiple private keys that what you want to use (You can create an Account instance with multiple public keys via caver.account.create). Same again, after feeding the account instance created to the account field inside the transaction object, the left rest of the updating process is just the same as the above example.
// Create an account instance with three private keys using AccountKeyWeightedMultiSigconstnewPrivateKeys=caver.wallet.keyring.generateMultipleKeys(3)constnewKeyring=caver.wallet.keyring.createWithMultipleKey(sender.address, newPrivateKeys)// threshold = 3, the weights of the three keys = [1, 2, 1]constoptions=newcaver.account.weightedMultiSigOptions(3, [1,2,1])constaccount=newKeyring.toAccount(options)
// Create an account instance with roles using AccountKeyRoleBased. In the account instance created, each role has a public key that corresponds to one private key.
constnewPrivateKeys=caver.wallet.keyring.generateRoleBasedKeys([1,1,1])constnewKeyring=caver.wallet.keyring.createWithRoleBasedKey(sender.address, newPrivateKeys)constaccount=newKeyring.toAccount()
The AccountKeyRoleBased above is an example of using one public key for each role. As you can see from the code above, each of them corresponds to one private key. If you want to use multiple private keys for each role, caver.account.weightedMultiSigOptions must be defined for each role as shown below.
// Create an account instance with [3, 2, 3] keys for each role using AccountKeyRoleBasedconstnewPrivateKeys=caver.wallet.keyring.generateRoleBasedKeys([3,2,3])constnewKeyring=caver.wallet.keyring.createWithRoleBasedKey(sender.address, newPrivateKeys)constoptions= [// thresold = 4, weights of keys = [2, 2, 4] for roleTransactionKeynewcaver.account.weightedMultiSigOptions(4, [2,2,4]),// threshold = 2, weights of keys = [1, 1]newcaver.account.weightedMultiSigOptions(2, [1,1]),// threshold = 3, weights of keys = [1, 1, 1]newcaver.account.weightedMultiSigOptions(3, [1,1,1]),]constaccount=newKeyring.toAccount(options)
If you want to update AccountKey to AccountKeyLegacy or accountKeyFail, create an Account instance as shown below and assign it to the account field of the transaction.
// Create an account with AccountKeyLegacyconstaccountWithLegacyKey=caver.account.createWithAccountKeyLegacy(keyringToUpdate.address)// Create an account with AccountKeyFailconstaccountWithFailKey=caver.account.createWithAccountKeyFail(keyringToUpdate.address)
Smart Contract
The caver.contract package makes it easy to interact with smart contracts on Klaytn. It automatically converts all methods of a smart contract into javascript calls when its low-level ABI (Application Binary Interface) is given. This allows you to interact with smart contracts as if they were JavaScript objects.
First, we make a simple solidity example like the below. Create a 'test.sol' file and write down the below example.
pragma solidity ^0.5.6;
contract KVstore {
mapping(string=>string) store;
function get(string memory key) public view returns (string memory) {
return store[key];
}
function set(string memory key, string memory value) public {
store[key] = value;
}
}
Now we can compile a smart contract to get its bytecode and ABI.
Looking at the output above, you can see that the methods are managed through abi inside the Contract instance. And since it hasn't been deployed yet, you can see that the result of contractInstance.options.address is output as null.
If the smart contract has already been deployed and you know the contract address where the smart contract was deployed, please pass the contract address to the second parameter as shown below.