A client library for Cardano in Java. This library simplifies the interaction with Cardano blockchain from a Java application.
Latest Stable Version: 0.4.3
More details --> Documentation
- Composable functions to build transactions
- Call Plutus V2 contract from off-chain Java code
- Cardano-client-libย : A Java Library to interact with Cardanoโ-โPartย I
- Cardano-client-lib: Transaction with Metadata in Javaโ-โPartย II
- Cardano-client-lib: Minting a new Native Token in Javaโ-โPartย III
Cardano-client-lib examples repository
In 0.4.0 and later, the library has been divided into smaller modules. These modules can be added to a project based on requirement.
Group Id: com.bloxbean.cardano
For simple setup, you can use cardano-client-lib and one of the backend provider as dependency.
Modules | Artifact Id | Description |
---|---|---|
cardano-client-lib | cardano-client-lib | This is a top level module which includes all other modules except backend provider modules. (Recommended for most applications) |
Backend Api | cardano-client-backend | Defines backend apis which are implemented by provider specific module. |
Blockfrost Backend | cardano-client-backend-blockfrost | Provides integration with Blockfrost |
Koios Backend | cardano-client-backend-koios | Provides integration with Koios |
Ogmios/Kupo Backend | cardano-client-backend-ogmios | Provides integration with Ogmios and Kupo. Supported Apis : submitTransaction, evaluateTx, Kupo support (UtxoService) |
For fine-grained dependency management, add one or more below modules as required.
Modules | Artifact Id | Description |
---|---|---|
common | cardano-client-common | Contains common utilities (HexUtil, JsonUtil, Cbor Utils etc). This module doesn't depend on any other module. Dependencies: None |
crypto | cardano-client-crypto | Provides implementation for standards like Bip32, Bip39, CIP1852 and other crypto primitives Dependencies: common |
address | cardano-client-address | Supports derivation of various types of Cardano addresses (Base, Enterprise, Pointer, Stake etc) Dependencies: common, crypto, transaction-common |
metadata | cardano-client-metadata | Provides simple api to generate and serialize generic metadata Dependencies: common, crypto |
transaction-common | cardano-client-transaction-common | A small module with some transaction specific common classes which are required in other modules. This module is there for backward compatibility. So you should not add this module directly in your application. Dependencies: common, crypto |
core | cardano-client-core | Contains low level transaction serialization logic and other common apis / interfaces (Account, Coin selections, UtxoSupplier, ProtocolParamSupplier etc.). Also contains high-level api like PaymentTransaction for backward compatibility. But HL api may be removed to a separate module in future release Dependencies: common, crypto, transaction-common, address, metadata |
function | cardano-client-function | Provides Composable Function Apis. A simple, flexible way to build transactions through re-usable functions. Dependencies: core |
cip | cardano-client-cip | A umbrella module which provides a simple way to get available cip implementations (cip25, cip8 etc.) Dependencies: cip8, cip20, cip25, cip27, cip30 |
cip8 | cardano-client-cip8 | CIP 8 - Message Signing Dependencies: common, crypto |
cip20 | cardano-client-cip20 | CIP 20 - Transaction message/comment metadata Dependencies: metadata |
cip25 | cardano-client-cip25 | CIP 25 - Media NFT Metadata Standard Dependencies: metadata |
cip27 | cardano-client-cip27 | CIP 27 - CNFT Community Royalties Standard Dependencies: cip25 |
cip30 | cardano-client-cip30 | CIP 30 - Cardano dApp-Wallet Web Bridge Dependencies: cip8, core |
For Maven, add the following dependencies to project's pom.xml
- Core module
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-lib</artifactId>
<version>0.4.3</version>
</dependency>
- Backend modules
- For backend support, use one of the following supported backend module
<!-- For Blockfrost backend -->
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-backend-blockfrost</artifactId>
<version>0.4.3</version>
</dependency>
<!-- For Koios backend -->
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-backend-koios</artifactId>
<version>0.4.3</version>
</dependency>
<!-- For Ogmios / Kupo backend -->
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-backend-ogmios</artifactId>
<version>0.4.3</version>
</dependency>
For Gradle, add the following dependencies to build.gradle
- Core Module
implementation 'com.bloxbean.cardano:cardano-client-lib:0.4.3'
- Backend modules
- For backend support, use one of the following supported backend module
//For Blockfrost
implementation 'com.bloxbean.cardano:cardano-client-backend-blockfrost:0.4.3'
//For Koios
implementation 'com.bloxbean.cardano:cardano-client-backend-koios:0.4.3'
//For Ogmios / Kupo
implementation 'com.bloxbean.cardano:cardano-client-backend-ogmios:0.4.3'
SNAPSHOT_VERSION : 0.4.4-SNAPSHOT (Please verify the latest snapshot version in gradle.properties)
- For Maven, add the following dependencies and repository to project's pom.xml
<dependencies>
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-lib</artifactId>
<version>{SNAPSHOT_VERSION}</version>
</dependency>
<dependency>
<groupId>com.bloxbean.cardano</groupId>
<artifactId>cardano-client-backend-blockfrost</artifactId>
<version>{SNAPSHOT_VERSION}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
- For Gradle, add the following dependencies and repository to build.gradle
repositories {
...
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
implementation 'com.bloxbean.cardano:cardano-client-lib:{SNAPSHOT_VERSION}'
implementation 'com.bloxbean.cardano:cardano-client-backend-blockfrost:{SNAPSHOT_VERSION}'
This section highlights few key apis in the library. For detailed documentation, please visit Cardano Client Doc site.
- Create a New Account
Account account = new Account(); //Create a Mainnet account
Account account = new Account(Networks.mainnet()); //Create a Mainnet account
Account account = new Account(Networks.testnet()); //Create a Testnet account
- Get base address, enterprise address, mnemonic
String baseAddress = account.baseAddress(); //Base address at index=0
String enterpriseAddress = account.account.enterpriseAddress(); //Enterprise address at index = 0
String mnemonic = account.mnemonic(); //Get Mnemonic
- Get Account from Mnemonic
String mnemonic = "...";
Account account = new Account(mnemonic); //Create a Mainnet account from Mnemonic
Account account = new Account(Networks.testnet(), mnemonic); //Create a Testnet account from Mnemonic
BackendService backendService =
new BFBackendService(Constants.BLOCKFROST_TESTNET_URL, <BF_PROJECT_ID>);
FeeCalculationService feeCalculationService = backendService.getFeeCalculationService();
TransactionHelperService transactionHelperService = backendService.getTransactionHelperService();
TransactionService transactionService = backendService.getTransactionService();
BlockService blockService = backendService.getBlockService();
AssetService assetService = backendService.getAssetService();
UtxoService utxoService = backendService.getUtxoService();
MetadataService metadataService = backendService.getMetadataService();
EpochService epochService = backendService.getEpochService();
AddressService addressService = backendService.getAddressService();
// For Blockfrost
String bf_projectId = "<Blockfrost Project Id>";
BackendService backendService =
new BFBackendService(Constants.BLOCKFROST_PREVIEW_URL, bf_projectId);
// For Koios
// BackendService backendService = new KoiosBackendService(KOIOS_TESTNET_URL);
// Define expected Outputs
Output output1 = Output.builder()
.address(receiverAddress1)
.assetName(LOVELACE)
.qty(adaToLovelace(10))
.build();
Output output2 = Output.builder()
.address(receiverAddress2)
.assetName(LOVELACE)
.qty(adaToLovelace(20))
.build();
// Create a CIP20 message metadata
MessageMetadata metadata = MessageMetadata.create()
.add("First transfer transaction");
// Define TxBuilder
TxBuilder txBuilder = output1.outputBuilder()
.and(output2.outputBuilder())
.buildInputs(createFromSender(senderAddress, senderAddress))
.andThen(metadataProvider(metadata))
.andThen(balanceTx(senderAddress, 1));
UtxoSupplier utxoSupplier = new DefaultUtxoSupplier(backendService.getUtxoService());
ProtocolParamsSupplier protocolParamsSupplier = new DefaultProtocolParamsSupplier(backendService.getEpochService());
//Build and sign the transaction
Transaction signedTransaction = TxBuilderContext.init(utxoSupplier, protocolParamsSupplier)
.buildAndSign(txBuilder, signerFrom(senderAccount));
//Submit the transaction
Result<String> result = backendService.getTransactionService().submitTransaction(signedTransaction.serialize());
PaymentTransaction paymentTransaction = PaymentTransaction.builder()
.sender(sender)
.receiver(receiver)
.amount(BigInteger.valueOf(1500000))
.unit("lovelace")
.build();
//Calculate Time to Live
long ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;
TransactionDetailsParams detailsParams =
TransactionDetailsParams.builder()
.ttl(ttl)
.build();
//Calculate fee
BigInteger fee
= feeCalculationService.calculateFee(paymentTransaction, detailsParams, null);
paymentTransaction.setFee(fee);
Result<String> result =
transactionHelperService.transfer(paymentTransaction, detailsParam);
if(result.isSuccessful())
System.out.println("Transaction Id: " + result.getValue());
PaymentTransaction paymentTransaction =
PaymentTransaction.builder()
.sender(sender)
.receiver(receiver)
.amount(BigInteger.valueOf(12))
.unit("329728f73683fe04364631c27a7912538c116d802416ca1eaf2d7a96736174636f696e")
.build();
//Calculate Time to Live
long ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;
TransactionDetailsParams detailsParams =
TransactionDetailsParams.builder()
.ttl(ttl)
.build();
//Calculate fee
BigInteger fee
= feeCalculationService.calculateFee(paymentTransaction, detailsParams, null);
paymentTransaction.setFee(fee);
Result<String> result = transactionHelperService.transfer(paymentTransaction, detailsParam);
if(result.isSuccessful())
System.out.println("Transaction Id: " + result.getValue());
Example: 1
ScriptPubkey scriptPubkey = new ScriptPubkey("ad7a7b87959173fc9eac9a85891cc93892f800dd45c0544128228884")
String policyId = scriptPubkey.getPolicyId();
Example: 2
ScriptPubkey scriptPubkey1 = ...;
SecretKey sk1 = ...;
ScriptPubkey scriptPubkey2 = ...;
SecretKey sk2 = ...;
ScriptPubkey scriptPubkey3 = ...;
SecretKey sk3 = ...;
ScriptAtLeast scriptAtLeast = new ScriptAtLeast(2)
.addScript(scriptPubkey1)
.addScript(scriptPubkey2)
.addScript(scriptPubkey3);
String policyId = scriptAtLeast.getPolicyId();
MultiAsset multiAsset = new MultiAsset();
multiAsset.setPolicyId(policyId);
Asset asset = new Asset("testtoken"), BigInteger.valueOf(250000));
multiAsset.getAssets().add(asset);
MintTransaction mintTransaction = MintTransaction.builder()
.sender(sender)
.receiver(receiver)
.mintAssets(Arrays.asList(multiAsset))
.policyScript(scriptAtLeast)
.policyKeys(Arrays.asList(sk2, sk3))
.build();
//Calculate Time to Live
long ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;
TransactionDetailsParams detailsParams =
TransactionDetailsParams.builder()
.ttl(ttl)
.build();
//Calculate fee
BigInteger fee
= feeCalculationService.calculateFee(mintTransaction, detailsParams, null);
mintTransaction.setFee(fee);
Result<String> result = transactionHelperService.mintToken(mintTransaction,
TransactionDetailsParams.builder().ttl(getTtl()).build());
CBORMetadataMap productDetailsMap
= new CBORMetadataMap()
.put("code", "PROD-800")
.put("slno", "SL20000039484");
CBORMetadataList tagList
= new CBORMetadataList()
.add("laptop")
.add("computer");
Metadata metadata = new CBORMetadata()
.put(new BigInteger("670001"), productDetailsMap)
.put(new BigInteger("670002"), tagList);
PaymentTransaction paymentTransaction =
PaymentTransaction.builder()
...
.build();
long ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;
TransactionDetailsParams detailsParams =
TransactionDetailsParams.builder()
.ttl(ttl)
.build();
//Also add metadata for fee calculation
BigInteger fee = feeCalculationService.calculateFee(paymentTransaction, detailsParams, metadata);
paymentTransaction.setFee(fee);
//Send metadata as 3rd parameter
Result<String> result
= transactionHelperService.transfer(paymentTransaction, detailsParams, metadata);
The utxo selection strategy can be changed by providing a custom implementation of "UtxoSelectionStrategy" interface. By default, the high level api like TransactionHelperService uses a default out-of-box implementation "DefaultUtxoSelectionStrategyImpl". The default strategy is too simple and finds all required utxos sequentially. But it may not be efficient for some use cases.
You can use a custom or different implementation of UtxoSelectionStrategy to change the default utxo selection behaviour.
UtxoSupplier utxoSupplier = new DefaultUtxoSupplier(utxoService);
ProtocolParamsSupplier protocolParamsSupplier = new DefaultProtocolParamsSupplier(epochService);
//Create TransactionHelperService with LargestFirst
TransactionBuilder transactionBuilder = new TransactionBuilder(new LargestFirstUtxoSelectionStrategy(utxoSupplier), protocolParamsSupplier);
TransactionHelperService transactionHelperService = new TransactionHelperService(transactionBuilder, new DefaultTransactionProcessor(transactionService));
//Get FeeCalculationService using the above TransactionHelperService
FeeCalculationService feeCalculationService = backendService.getFeeCalculationService(transactionHelperService);
git clone https://github.com/bloxbean/cardano-client-lib.git
export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8
./gradlew clean build
export BF_PROJECT_ID=<Blockfrost Preprod network Project Id>
./gradlew :integration-test:integrationTest -PBF_PROJECT_ID=${BF_PROJECT_ID}
- EASY1 Stake Pool Raffles
- Cardanotales
- Cardano Fans Raffles
- Cardano Fans Donation App
- adadomains.io
- ADAM - ADA Monitor APP
- ISR - Israeli Cardano Community
- MusicBox - CNFT Project
- Realfi.info - Portfolio Viewer
- Create a Github Discussion
- Create a Github Issue
- Discord Server
If this project helps you reduce time to develop on Cardano or if you just want to support this project, you can delegate to our pool:
YourKit has generously granted the BloxBean projects an Open Source licence to use their excellent Java Profiler.
YourKit supports open source projects with innovative and intelligent tools for monitoring and profiling Java and .NET applications. YourKit is the creator of YourKit Java Profiler, YourKit .NET Profiler, and YourKit YouMonitor.