{"id":13695107,"url":"https://github.com/klaytn/caver-java","last_synced_at":"2025-05-03T09:31:42.656Z","repository":{"id":39176818,"uuid":"193423301","full_name":"klaytn/caver-java","owner":"klaytn","description":"Official caver-java repository","archived":true,"fork":false,"pushed_at":"2024-07-16T04:19:12.000Z","size":4528,"stargazers_count":65,"open_issues_count":1,"forks_count":43,"subscribers_count":15,"default_branch":"dev","last_synced_at":"2025-03-13T09:41:42.065Z","etag":null,"topics":["blockchain"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/klaytn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-24T02:53:19.000Z","updated_at":"2024-07-23T04:43:18.000Z","dependencies_parsed_at":"2024-11-19T20:47:15.877Z","dependency_job_id":null,"html_url":"https://github.com/klaytn/caver-java","commit_stats":null,"previous_names":[],"tags_count":95,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klaytn%2Fcaver-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klaytn%2Fcaver-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klaytn%2Fcaver-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klaytn%2Fcaver-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/klaytn","download_url":"https://codeload.github.com/klaytn/caver-java/tar.gz/refs/heads/dev","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252168971,"owners_count":21705355,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blockchain"],"created_at":"2024-08-02T18:00:17.576Z","updated_at":"2025-05-03T09:31:40.996Z","avatar_url":"https://github.com/klaytn.png","language":"Java","funding_links":[],"categories":["SDKs"],"sub_categories":[],"readme":"[![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/)\n\n# NO LONGER MAINTAINED\n\nSince the launch of Kaia Blockchain this repository has been parked in favour of the new open-source projects in [Kaia's Github](https://github.com/kaiachain). Contributors have now moved there continuing with massive open-source contributions to our blockchain ecosystem. Please visit the new repository at [kaia/caver-java](https://github.com/kaiachain/caver-java) to continue contributing and to access the latest updates. A big thank you to everyone who has contributed to this repository. For more information about Klaytn's chain merge with Finschia blockchain please refer to the launching of Kaia blockchain - [kaia.io](https://kaia.io/).\n\n---\n\n\n[![CircleCI](https://circleci.com/gh/klaytn/caver-java/tree/dev.svg?style=svg)](https://circleci.com/gh/klaytn/caver-java/tree/dev)\n[![Gitter](https://badges.gitter.im/klaytn/Caver-java.svg)](https://gitter.im/klaytn/Caver-java?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge)\n\n# caver-java: Caver Java Klaytn Dapp API\n\ncaver-java is a lightweight, high modular, convenient Java and Android library to interact with clients (nodes) on the Klaytn network:\nThis library is an interface which allows Java applications to easily communicate with [Klaytn](https://www.klaytn.com) network.\n\n## Features\n- Complete implementation of Klaytn’s JSON-RPC client API over HTTP and IPC\n- Support of Klaytn transaction, account, and account key types\n- Auto-generation of Java smart contract wrapper to deploy and execute a smart contract from native Java code\n- Creation of a new wallet and managing Klaytn wallets\n- Command line tools\n- Android compatible\n\n## Getting started\n\n### Installation\n\n#### add a Repository\n\nTo install caver-java, you should add a jitpack repository for IPFS feature.\n\n**maven**\n```groovy\n\u003crepositories\u003e\n    \u003crepository\u003e\n        \u003cid\u003ejitpack.io\u003c/id\u003e\n        \u003curl\u003ehttps://jitpack.io\u003c/url\u003e\n    \u003c/repository\u003e\n\u003c/repositories\u003e\n```\n\n**gradle**\n```groovy\nallprojects {\n    repositories {\n        ...\n        maven { url 'https://jitpack.io' }\n    }\n}\n```\n#### add a dependency\n\n**maven**\n```groovy\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.klaytn.caver\u003c/groupId\u003e\n    \u003cartifactId\u003ecore\u003c/artifactId\u003e\n    \u003cversion\u003eX.X.X\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**gradle**\n```groovy\ncompile 'com.klaytn.caver:core:X.X.X'\n```\nIf you want to use Android dependency, just append -android at the end of version. (e.g. 1.5.4-android)\n\nYou can find latest caver-java version at [release page](https://github.com/klaytn/caver-java/releases).\n\n## Start a Client\nIf you want to run your own EN (Endpoint Node), see [EN Operation Guide](https://docs.klaytn.com/node/en) to set up.\n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\n```\n\n## Transactions\nWhen you send transactions, `caver-java` provides easy-to-use wrapper classes. \n\nHere's an example of transferring KLAY using keystore.json and `ValueTransfer` class:\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\n\n//Read keystore json file.\nFile file = new File(\"./keystore.json\");\n\n//Decrypt keystore.\nObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();\nKeyStore keyStore = objectMapper.readValue(file, KeyStore.class);\nAbstractKeyring keyring = KeyringFactory.decrypt(keyStore, \"password\");\n\n//Add to caver wallet.\ncaver.wallet.add(keyring);\n\nBigInteger value = new BigInteger(Utils.convertToPeb(BigDecimal.ONE, \"KLAY\"));\n\n//Create a value transfer transaction\nValueTransfer valueTransfer = new ValueTransfer.Builder()\n        .setKlaytnCall(caver.rpc.getKlay())\n        .setFrom(keyring.getAddress())\n        .setTo(\"0x8084fed6b1847448c24692470fc3b2ed87f9eb47\")\n        .setValue(value)\n        .setGas(BigInteger.valueOf(25000))\n        .build();\n\n//Sign to the transaction\nvalueTransfer.sign(keyring);\n\n//Send a transaction to the klaytn blockchain platform (Klaytn)\nBytes32 result = caver.rpc.klay.sendRawTransaction(valueTransfer.getRawTransaction()).send();\nif(result.hasError()) {\n    throw new RuntimeException(result.getError().getMessage());\n}\n\n//Check transaction receipt.\nTransactionReceiptProcessor transactionReceiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);\nTransactionReceipt.TransactionReceiptData transactionReceipt = transactionReceiptProcessor.waitForTransactionReceipt(result.getResult());\n```\n\nIf you have address and private key(s) of keyring, you can make keyring directly through [KeyringFactory.create](https://docs.klaytn.com/bapp/sdk/caver-java/getting-started#creating-a-keyring).\n\n`\u003cvalueUnit\u003e` means a unit of value that is used in Klaytn. It is defined as an enum type. Examples of possible values are as below.\n\n```\nPEB, KPEB, MPEB, GPEB, STON, UKLAY, MKLAY, KLAY, KKLAY, MKLAY, GKLAY\n```\n\nIf `\u003cvalueUnit\u003e` is not given as a parameter, default unit of `\u003cvalue\u003e` is `PEB`. You can use `Utils.convertToPeb` or `Utils.convertFromPeb` to easily convert a value to another unit like below.\n\n```java\nUtils.convertToPeb(\"1\", KLAY).toBigInteger();  // 1000000000000000000\nUtils.convertFromPeb(\"1000000000000000000\", KLAY).toBigInteger();  // 1\n```\n\n### Fee Delegation\nKlaytn provides [Fee Delegation](https://docs.klaytn.com/klaytn/design/transactions#fee-delegation) feature. Here's an example code.\nWhen you are a sender:\n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\nSingleKeyring senderKeyring = KeyringFactory.createFromPrivateKey(\"0x{privateKey}\");\ncaver.wallet.add(senderKeyring);\n\nFeeDelegatedValueTransfer feeDelegatedValueTransfer = new FeeDelegatedValueTransfer.Builder()\n        .setKlaytnCall(caver.rpc.klay)\n        .setFrom(senderKeyring.getAddress())\n        .setTo(\"0x176ff0344de49c04be577a3512b6991507647f72\")\n        .setValue(BigInteger.valueOf(1))\n        .setGas(BigInteger.valueOf(30000))\n        .build();\n\ncaver.wallet.sign(senderKeyring.getAddress(), feeDelegatedValueTransfer);\nString rlpEncoded = feeDelegatedValueTransfer.getRLPEncoding();\nSystem.out.println(rlpEncoded);\n```\nAfter signing a transaction, the sender can get the RLP-encoded string through `feeDelegatedValueTransfer.getRLPEncoding()`.\nThen, the sender sends the transaction to the fee payer who will pay for the transaction fee instead.\n\nWhen you are a fee payer:\n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\n\nSingleKeyring feePayerKeyring = KeyringFactory.createFromPrivateKey(\"0x{privateKey}\");\ncaver.wallet.add(feePayerKeyring);\n\nString rlpEncoded = \"0x{RLP-encoded string}\"; // The result of feeDelegatedValueTransfer.getRLPEncoding() in above example\nFeeDelegatedValueTransfer feeDelegatedValueTransfer = FeeDelegatedValueTransfer.decode(rlpEncoded);\nfeeDelegatedValueTransfer.setFeePayer(feePayerKeyring.getAddress());\n\ncaver.wallet.signAsFeePayer(feePayerKeyring.getAddress(), feeDelegatedValueTransfer);\n\nTransactionReceiptProcessor receiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);\n\nString rlpEncoded = feeDelegatedValueTransfer.getRLPEncoding();\n\ntry {\n  // Send the transaction using `caver.rpc.klay.sendRawTransaction`.\n  Bytes32 sendResult = caver.rpc.klay.sendRawTransaction(rlpEncoding).send();\n  if(sendResult.hasError()) {\n    //do something to handle error\n\n  }\n\n  String txHash = sendResult.getResult();\n  TransactionReceipt.TransactionReceiptData receiptData = receiptProcessor.waitForTransactionReceipt(txHash);\n} catch (IOException | TransactionException e) {\n  // do something to handle exception.\n}\n```\nAfter the fee payer gets the transaction from the sender, the fee payer can sign with `signAsFeePayer`. \nFor more information about Klaytn transaction types, visit [Transactions](https://docs.klaytn.com/klaytn/design/transactions).\n\n\n## Klaytn Accounts\nAn account in Klaytn is a data structure containing information about a person's balance or a smart contract. If you require further information about Klaytn accounts, you can refer to the [Accounts](https://docs.klaytn.com/klaytn/design/account).\n\n### Account Key\nAn account key represents the key structure associated with an account.  Each account key has its own unique role. To get more details about the Klaytn account key, please read [Account Key](https://docs.klaytn.com/klaytn/design/account#account-key). These are 6 types of Account Keys in Klaytn:\n- AccountKeyNil\n- AccountKeyLegacy\n- AccountKeyPublic\n- AccountKeyFail\n- AccountKeyWeightedMultiSig\n- AccountKeyRoleBased\n\nIf you want to update the key of the given account, follow below steps :\n\n1. Create new private key(s) to use\n2. Create a keyring instance using the new private key(s) and the account address to update. \nAfter the AccountKey has been successfully updated in Klaytn, you can use the Keyring instance created here.\n3. To update the AccountKey of Klaytn Account, create an Account instance using the toAccount function.\n4. Create an AccountUpdate transaction (AccountUpdate/FeeDelegatedAccountUpdate/FeeDelegatedAccountUpdateWithRatio).\n5. Sign the AccountUpdate transaction\n6. Send signed transaction through `caver.rpc.klay.sendRawTransaction`\n\n```java\nCaver caver = new Caver(Caver.BAOBAB_URL);\nSingleKeyring senderKeyring = KeyringFactory.createFromPrivateKey(\"0x{privateKey}\");\ncaver.wallet.add(senderKeyring);\n\nString newPrivateKey = KeyringFactory.generateSingleKey();\nSingleKeyring newKeyring = KeyringFactory.createFromPrivateKey(newPrivateKey);\n\nAccount account = newKeyring.toAccount();\n\nAccountUpdate accountUpdate = new AccountUpdate.Builder()\n        .setKlaytnCall(caver.rpc.klay)\n        .setFrom(senderKeyring.getAddress())\n        .setAccount(account)\n        .setGas(BigInteger.valueOf(50000))\n        .build();\n\ntry {\n    caver.wallet.sign(senderKeyring.getAddress(), accountUpdate);\n    String rlpEncoded = accountUpdate.getRLPEncoding();\n\n    Bytes32 sendResult = caver.rpc.klay.sendRawTransaction(rlpEncoded).send();\n    if(sendResult.hasError()) {\n        //do something to handle error\n    }\n\n    String txHash = sendResult.getResult();\n\n    TransactionReceiptProcessor receiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);\n    TransactionReceipt.TransactionReceiptData receiptData = receiptProcessor.waitForTransactionReceipt(txHash);\n} catch (IOException | TransactionException e) {\n    // do something to handle exception.\n}\n\nsenderKeyring = caver.wallet.updateKeyring(newKeyring);\n```\n\n## Manage Contracts using Java Smart Contract Wrappers\n\nCaver supports `Contract` class to make it easy to interact with smart contract in Klaytn.\nBefore generating a wrapper code, you need to compile the smart contract first (Note: This will only work if solidity compiler is installed in your computer).\n\n```shell\n$ solc --abi --bin ./test.sol\n```\n\nYou can create a contract instance as below using the result of compiling the smart contract: \n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\ntry {\n    Contract contract = new Contract(caver, ABI);\n    contract.getMethods().forEach((methodName, contractMethod) -\u003e {\n        System.out.println(\"methodName : \" + methodName + \", ContractMethod : \" + contractMethod);\n    });\n    System.out.println(\"ContractAddress : \" + contract.getContractAddress());\n} catch (IOException e) {\n    //handle exception..\n}\n```\n\nIf you want to deploy the smart contract at Baobab testnet, you could do like this:\n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\nSingleKeyring deployer = KeyringFactory.createFromPrivateKey(\"0x{private key}\");\ncaver.wallet.add(deployer);\ntry {\n    Contract contract = new Contract(caver, ABI);\n    ContractDeployParams params = new ContractDeployParams(byteCode, null);\n    SendOptions sendOptions = new SendOptions();\n    sendOptions.setFrom(deployer.getAddress());\n    sendOptions.setGas(BigInteger.valueOf(40000))\n    \n    Contract newContract = contract.deploy(params, sendOptions);\n    System.out.println(\"Contract address : \" + newContract.getContractAddress());\n} catch (IOException | TransactionException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {\n    //handle exception..\n}\n```\n\nAfter the smart contract has been deployed, you can load the smart contract as below:\n\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\nString contractAddress = \"0x3466D49256b0982E1f240b64e097FF04f99Ed4b9\";\ntry {\n    Contract contract = new Contract(caver, ABI, contractAddress);\n    contract.getMethods().forEach((methodName, contractMethod) -\u003e {\n        System.out.println(\"methodName : \" + methodName + \", ContractMethod : \" + contractMethod);\n    });\n    System.out.println(\"ContractAddress : \" + contract.getContractAddress());\n} catch (IOException e) {\n    //handle exception..\n}\n```\n\nTo transact with a smart contract:\n```java\nCaver caver = new Caver(Caver.DEFAULT_URL);\nSingleKeyring executor = KeyringFactory.createFromPrivateKey(\"0x{private key}\");\ncaver.wallet.add(executor);\ntry {\n    Contract contract = new Contract(caver, ABI, '0x{address in hex}');\n    \n    SendOptions sendOptions = new SendOptions();\n    sendOptions.setFrom(executor.getAddress());\n    sendOptions.setGas(BigInteger.valueOf(40000))\n    TransactionReceipt.TransactionReceiptData receipt = contract.getMethod(\"set\").send(Arrays.asList(\"testValue\"), sendOptions);\n    } catch (IOException | TransactionException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {\n    //handle exception..\n}\n```\n\n## Filters\nTBD\n\n## Web3j Similarity\nWe made caver-java as similar as possible to web3j for easy usability.\n```java\n/* start a client */\nWeb3j web3 = Web3j.build(new HttpService(\u003cendpoint\u003e)); // Web3j\nCaver caver = Caver.build(new HttpService(\u003cendpoint\u003e)); // caver-java\n\n/* get nonce */\nBigInteger nonce = web3j.ethGetTransactionCount(\u003caddress\u003e, \u003cblockParam\u003e).send().getTransactionCount(); // Web3j\nQuantity nonce = caver.klay().getTransactionCount(\u003caddress\u003e, \u003cblockParam\u003e).send().getValue(); // caver-java\n\n/* convert unit */\nConvert.toWei(\"1.0\", Convert.Unit.ETHER).toBigInteger(); // Web3j\nConvert.toPeb(\"1.0\", Convert.Unit.KLAY).toBigInteger(); // caver-java\n \n/* generate wallet file */\nWalletUtils.generateNewWalletFile(\u003cpassword\u003e, \u003cfilepath\u003e); // Web3j\nKlayWalletUtils.generateNewWalletFile(\u003caddress\u003e, \u003cpassword\u003e, \u003cfilepath\u003e); // caver-java\n\n/* load credentials */\nCredentials credentials = WalletUtils.loadCrendetials(\u003cpassword\u003e, \u003cfilepath\u003e\"); // Web3j\nKlayCredentials credentials = KlayWalletUtils.loadCredentials(\u003cpassword\u003e, \u003cfilepath\u003e); // caver-java\n                                                      \n/* Value Transfer */\nTransactionReceipt transactionReceipt = Transfer.sendFunds(...),send(); // Web3j\nKlayTransactionReceipt.TransactionReceipt transactionReceipt = ValueTransfer.create(...).sendFunds(...).send(); // caver-java\n```\n\n## Command-line Tool\nA caver-java fat jar is distributed with open repository. The 'caver-java' allows you to generate Solidity smart contract function wrappers from the command line: \n- Generate Solidity smart contract function wrappers\nInstallation\n```shell\n$ brew tap klaytn/klaytn\n$ brew install caver-java\n```\nAfter installation you can run command 'caver-java'\n```shell\n$ caver-java solidity generate -b \u003csmart-contract\u003e.bin -a \u003csmart-contract\u003e.abi -o \u003coutputPath\u003e -p \u003cpackagePath\u003e\n```\n\n## Related projects \n**caver-js** for a javascript\n\n## Build instructions\nTBD\n\n## Snapshot dependencies\nTBD\n\n## Thanks to\n- The [web3j](https://github.com/web3j/web3j) project for the inspiration.  🙂 \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fklaytn%2Fcaver-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fklaytn%2Fcaver-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fklaytn%2Fcaver-java/lists"}