Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

com.bloxbean.cardano:cardano-client-backend

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

com.bloxbean.cardano:cardano-client-backend

Cardano Client Lib Backend Api Module

  • 0.6.1
  • Source
  • Maven
  • Socket score

Version published
Maintainers
1
Source

Clean, Build CodeQL License

A client library for Cardano in Java. This library simplifies the interaction with Cardano blockchain from a Java application.

Latest Stable Version: 0.5.1

Latest Beta: 0.6.0-beta1 (Conway Era Ready)

More details --> Documentation

Recent Posts

Tutorials

Old Posts

Note: Some of the APIs mentioned in the below posts are deprecated. Please refer to the latest documentation for the latest APIs.

Examples

Cardano-client-lib examples repository

JavaDoc

Modules

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.

ModulesArtifact IdDescription
cardano-client-libcardano-client-libThis is a top level module which includes all other modules except backend provider modules.
(Recommended for most applications)
Backend Apicardano-client-backendDefines backend apis which are implemented by provider specific module.
Blockfrost Backendcardano-client-backend-blockfrostProvides integration with Blockfrost
Koios Backendcardano-client-backend-koiosProvides integration with Koios
Ogmios/Kupo Backendcardano-client-backend-ogmiosProvides 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.

ModulesArtifact IdDescription
commoncardano-client-commonContains common utilities (HexUtil, JsonUtil, Cbor Utils etc). This module doesn't depend on any other module.
Dependencies: None
cryptocardano-client-cryptoProvides implementation for standards like Bip32, Bip39, CIP1852 and other crypto primitives
Dependencies: common
addresscardano-client-addressSupports derivation of various types of Cardano addresses (Base, Enterprise, Pointer, Stake etc)
Dependencies: common, crypto, common-spec
metadatacardano-client-metadataProvides simple api to generate and serialize generic metadata
Dependencies: common, crypto
common-speccardano-client-common-specA small module with some common serialization classes (CDDL spec)
Dependencies: common, crypto
transaction-speccardano-client-transaction-specProvides cbor serialization code for transactions (CDDL spec).
Dependencies: common, common-spec, crypto, address, metadata, plutus
corecardano-client-coreCointains few common api like Account.
Also contains high-level api like PaymentTransaction for backward compatibility.
Dependencies: common, crypto, common-spec, address, metadata, transaction-spec, core-api, plutus, coinselection
core-apicardano-client-core-apiContains core apis, model classes and utils
Dependencies: common, transaction-spec
plutuscardano-client-plutusProvides plutus specific apis and serialization implementation.
Dependencies: common, common-spec
annotation-processorcardano-client-annotation-processorAnnotation processor for POJO <--> PlutusData.
Dependencies: plutus
quicktxcardano-client-quicktxProvides QuickTx TX builder APIs. A declarative API to build and submit transactions.
Dependencies: core, function, backend
functioncardano-client-functionProvides Composable Function Apis. A simple, flexible way to build transactions through re-usable functions.
Dependencies: core
coinselectioncardano-client-coinselectionProvides Coin selection algorithms.
Dependencies: common, core-api
cipcardano-client-cipA umbrella module which provides a simple way to get available cip implementations (cip25, cip8 etc.)
Dependencies: cip8, cip20, cip25, cip27, cip30
cip8cardano-client-cip8CIP 8 - Message Signing
Dependencies: common, crypto
cip20cardano-client-cip20CIP 20 - Transaction message/comment metadata
Dependencies: metadata
cip25cardano-client-cip25CIP 25 - Media NFT Metadata Standard
Dependencies: metadata
cip27cardano-client-cip27CIP 27 - CNFT Community Royalties Standard
Dependencies: cip25
cip30cardano-client-cip30CIP 30 - Cardano dApp-Wallet Web Bridge
Dependencies: cip8, core
cip67cardano-client-cip67CIP 67 - Asset Name Label Registry
Dependencies: crypto, common
cip68cardano-client-cip68CIP 68 - Datum Metadata Standard
Dependencies: cip67, cip25, plutus, transaction-spec
ogmios-suppliercardano-client-ogmios-supplierProvides Ogmios specific implementation for ProtocolParamsSupplier and TransactionProcessor.
kupo-suppliercardano-client-kupo-supplierProvides Kupo specific implementation for UtxoSupplier.

Use as a library in a Java Project

For release binaries

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.5.1</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.5.1</version>
        </dependency>
        
         <!-- For Koios backend -->
        <dependency>
            <groupId>com.bloxbean.cardano</groupId>
            <artifactId>cardano-client-backend-koios</artifactId>
            <version>0.5.1</version>
        </dependency>
        
         <!-- For Ogmios / Kupo backend -->
        <dependency>
            <groupId>com.bloxbean.cardano</groupId>
            <artifactId>cardano-client-backend-ogmios</artifactId>
            <version>0.5.1</version>
        </dependency>

For Gradle, add the following dependencies to build.gradle

  • Core Module
implementation 'com.bloxbean.cardano:cardano-client-lib:0.5.1'
  • Backend modules
    • For backend support, use one of the following supported backend module
//For Blockfrost
implementation 'com.bloxbean.cardano:cardano-client-backend-blockfrost:0.5.1'

//For Koios
implementation 'com.bloxbean.cardano:cardano-client-backend-koios:0.5.1'

//For Ogmios / Kupo
implementation 'com.bloxbean.cardano:cardano-client-backend-ogmios:0.5.1'

For snapshot binaries

SNAPSHOT_VERSION : 0.5.2-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}'

Usages

This section highlights few key apis in the library. For detailed documentation, please visit Cardano Client Doc site.

Account API Usage
  • 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
Create Backend Service
//For Blockfrost
BackendService backendService =
                new BFBackendService(Constants.BLOCKFROST_TESTNET_URL, <BF_PROJECT_ID>);               

// For Koios
// BackendService backendService = new KoiosBackendService(KOIOS_TESTNET_URL);
        
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();
Simple ADA Payment using QuickTx Api
        Tx tx1 = new Tx()
                .payToAddress(receiver1Addr, Amount.ada(1.5))
                .payToAddress(receiver2Addr, Amount.ada(2.5))
                .attachMetadata(MessageMetadata.create().add("This is a test message 2"))
                .from(sender1Addr);

        Tx tx2 = new Tx()
                .payToAddress(receiver2Addr, Amount.ada(4.5))
                .from(sender2Addr);

        QuickTxBuilder quickTxBuilder = new QuickTxBuilder(backendService);
        Result<String> result = quickTxBuilder
                .compose(tx1, tx2)
                .feePayer(sender1Addr)
                .withSigner(SignerProviders.signerFrom(sender1))
                .withSigner(SignerProviders.signerFrom(sender2))
                .completeAndWait(System.out::println);
        
Simple ADA Payment using Composable Functions Api
        // 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());
ScriptHash
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();

Metadata
MetadataMap productDetailsMap = MetadataBuilder.createMap()
                .put("code", "PROD-800")
                .put("slno", "SL20000039484");

MetadataList tagList = MetadataBuilder.createList()
                .add("laptop")
                .add("computer");

Metadata metadata = MetadataBuilder.createMetadata()
                .put(new BigInteger("670001"), productDetailsMap)
                .put(new BigInteger("670001"), productDetailsMap);
UtxoSelectionStrategy in High Level Api

The utxo selection strategy can be changed by providing a custom implementation of UtxoSelectionStrategy interface. By default, the transaction builder apis use DefaultUtxoSelectionStrategyImpl which 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. Out-of-box, the library provides two additional implementations of UtxoSelectionStrategy

  • LargestFirstUtxoSelectionStrategy
  • RandomImproveUtxoSelectionStrategy
UtxoSupplier, ProtocolPramsSupplier

You can get UtxoSupplier and ProtocolParamsSupplier from the backend service. Alternatively, you can create your own UtxoSupplier, ProtocolParamsSupplier and use it in the transaction builder api.

UtxoSupplier utxoSupplier = new DefaultUtxoSupplier(utxoService);
ProtocolParamsSupplier protocolParamsSupplier = new DefaultProtocolParamsSupplier(epochService);

Build from source and run integration tests

Prerequisites: Java 11

Build
git clone https://github.com/bloxbean/cardano-client-lib.git

export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8
./gradlew clean build
Integration Tests
export BF_PROJECT_ID=<Blockfrost Preprod network Project Id>
./gradlew :integration-test:integrationTest -PBF_PROJECT_ID=${BF_PROJECT_ID}

Used by

Any questions, ideas or issues?

Sponsors :sparkling_heart:

Previous Sponsors :sparkling_heart:

 

If this project helps you reduce time to develop on Cardano or if you just want to support this project :

Support this project

Support from YourKit

YourKit has generously granted the BloxBean projects an Open Source licence to use their excellent Java Profiler.

YourKit

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.

FAQs

Package last updated on 16 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc