Saturday, April 20, 2024
HomeJavaCardano-client-lib : A Java Library to work together with Cardano — Half...

Cardano-client-lib : A Java Library to work together with Cardano — Half I – Java Code Geeks


On this submit, I’m going to introduce a Java library referred to as “cardano-client-lib”. You should use this library in a Java software to work together with Cardano blockchain.

Presently, I’m engaged on a undertaking referred to as “Cardano IntelliJ IDEA plugin (IntelliAda)”, which is a Catalyst Fund 3 funded undertaking. You’ll be able to verify the Catalyst proposal right here. Once I began this undertaking, I noticed that there are shopper aspect libraries obtainable for Cardano in languages like JavaScript, Rust (Cardano-serilization-lib), however I used to be not in a position discover any Java library doing the same factor with out counting on cardano-cli (Cardano command line instrument).

As Cardano IntelliJ Plugin is written in java, I would like a shopper library in Java, in order that I don’t have to depend on Cardano-cli instrument contained in the plugin to generate handle, signal transaction and different operations. Due to that I began engaged on cardano-client-lib undertaking to offer handle era, transaction serialization and signing assist by a Java library.

The preview model (0.1.0) of this library in now obtainable in Maven central repository, so you should use it in your java software.

This library additionally gives assist to work together with Cardano blockchain to question blockchain and submit transactions by few easy Backend Apis. Presently, just one implementation obtainable for Backend Api, which is for Blockfrost endpoint. Extra backends might be supported in future releases. (Cardano Pockets Backend, Cardano-ogmios ..)

The next key options are at the moment supported on this library

  • Handle Era (Base Handle, Enterprise Handle)
  • Construct and serialize transaction to CBOR format
  • Apis to construct Metadata
  • A converter to transform Metadata to Json (No Schema)
  • Fee transaction (ADA, Native tokens) signing and submission to Cardano community (by Blockfrost Backend Api)
  • Transaction with metadata
  • Api to mint native tokens
  • Apis to question Cardano blockchain by many Blockfrost backend apis (AddressService, AssetService, BlockService, EpochService,MetadataService, TransactionService …)

Present Limitations

  • Presently, this library is utilizing “Cardano-serialization-lib” rust library by JNI, primarily for handle era and transaction signing. So it bundles the platform dependent binaries of Cardano-serialization-lib within the Jar. Due to that, this library is at the moment supported solely on the next platforms

Apple MacOS (Intel and Apple Silicon)
Linux (x86_64) (Ubuntu 18.04 and above or suitable …)
Home windows 64bits (x86_64)

Notice: This limitation is non permanent. The plan is to take away this dependency sooner or later launch by implementing handle era and transaction signing natively in Java.

  • The library doesn’t assist any stake pool associated operations. Although in future, stake pool associated operations could be added.

Let’s see how we are able to use this library to create and submit a switch transaction with Ada.

  1. Add cardano-client-lib dependency to your software

In case you are utilizing Maven,

<>dependency>     <>groupId>com.bloxbean.cardano<>/groupId>     <>artifactId>cardano-client-lib<>/artifactId>     <>model>0.1.0<>/model> <>/dependency>

In case you are utilizing Gradle,

implementation 'com.bloxbean.cardano:cardano-client-lib:0.1.0'

Notice: You’ll be able to verify the most recent launched model in undertaking’s GitHub.

2. Create a brand new Account

Account account = new Account(Networks.testnet()); String baseAddress = account.baseAddress();

3. Import from Mnemonic Phrase

Present 24 phrases mnemonic phrase to derive the bottom account handle.

String mnemonic = "behind hope swing desk fats pleasure cellphone spoil response train dose fame thriller day meals lens debate slam lawsuit board behind permit excuse lengthen";Account account = new Account(Networks.testnet(), mnemonic); String baseAddress = account.baseAddress();

4. Get Backend Service

Present Blockfrost Cardano community and Challenge Id to get an occasion of Blockfrost backend service.

Register at https://blockfrost.io/ to get a free account and a undertaking id for Cardano Testnet.

BackendService backendService =      BackendFactory.getBlockfrostBackendService(         Constants.BLOCKFROST_TESTNET_URL, <>project_id>);

5. Get Different companies from Backend Service

The followings are the instance of few main companies you will get from BackendService. You should use these companies to work together with Cardano blockchain.

a. Get an occasion of TransactionHelperService to construct a cost or token mint transaction and undergo the Cardano community.

TransactionHelperService txnHelperService                = backendService.getTransactionHelperService();

b. Get an occasion of FeeCalculationService to calculate the estimated charges of a transaction.

FeeCalculationService feeCalcService                         = backendService.getFeeCalculationService();

c. Get TransactionService to question the blockchain for a transaction id.

TransactionService txnService                         = backendService.getTransactionService();

d. Get BlockService to get the block info from the blockchain.

BlockService blockService = backendService.getBlockService();

e. Get an occasion of AssetService to get Asset particulars.

AssetService assetService = backendService.getAssetService();

f. Get an occasion of UtxoService to fetch Utxos.

UtxoService utxoService = backendService.getUtxoService()

g. Get an occasion of MetadataService to fetch metdata

MetadataService metadataService                         = backendService.getMetadataService();

6. High-up your account with take a look at Ada

In case you are on Cardano testnet, you will get some Testnet Ada token from the Testnet faucet right here.

Notice: You should use Account api to create new testnet accounts.

7. Create your first Ada Fee Transaction

Now that we’ve got some take a look at Ada tokens, we are able to create a cost transaction to switch Ada from funded account to a different account.

PaymentTransaction paymentTransaction =         PaymentTransaction.builder()              .sender(senderAccount) //Sender Account object              .receiver(receiver)   // Receiver baseAddress as String              .quantity(BigInteger.valueOf(1500000))              .unit(CardanoConstants.LOVELACE)              .construct();

Notice: Within the above transaction, we are attempting to ship 1.5 Ada (1500000 Lovelace) from sender’s account to receiver’s account.

6. Get the most recent slot info after which calculate TTL (Time To Dwell)

Within the beneath code snippet, we’re getting the most recent block by BlockService after which including 1000 to the present slot quantity to calculate TTL.

lengthy ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;

7. Create a TransactionDetailsParams Object, set TTL and calculate the estimated payment utilizing FeeCalculation service

TransactionDetailsParams detailsParams =         TransactionDetailsParams.builder()                 .ttl(ttl)                 .construct(); BigInteger payment      = feeCalculationService.calculateFee(paymentTransaction, detailsParams, null);

8. Set the payment within the transaction request object

Now that we’ve got estimated payment for our transaction, let’s set it in our PaymentTransaction request object.

paymentTransaction.setFee(payment);

9. Submit Transaction to the Cardano community

To submit the transaction to the community, you have to use TransactionHelperService. TransactionHelperService will get the required Utxos after which create the inputs and outputs accordingly earlier than sending the transaction request to the community. It additionally calculates the min-ada required for every outputs.

Consequence<>String> consequence           = transactionHelperService.switch(paymentTransaction, detailsParams);

If every thing is okay, you must get the consequence success standing as “true” and consequence worth as “Transaction id”.

if(consequence.isSuccessful())     System.out.println("Transaction Id: " + consequence.getValue()); else     System.out.println("Transaction failed: " + consequence);

Now anticipate someday, in order that the our transaction is mined.

Now you can go to Cardano Testnet Explorer to verify the transaction particulars.

10. Switch Native Token

To switch native tokens from one account to a different, you have to use the identical PaymentTransaction api to construct the native token switch request and set the native token’s asset id within the “unit” discipline of the cost request. Different steps are precisely similar.

PaymentTransaction paymentTransaction =         PaymentTransaction.builder()                 .sender(senderAccount)                 .receiver(receiver)                 .quantity(BigInteger.valueOf(3000))                 .unit("d11b0562dcac7042636c9dbb44897b38.......")                 .construct();//Calculate Ttl = Newest slot + 1000 lengthy ttl = blockService               .getLastestBlock().getValue().getSlot() + 1000; TransactionDetailsParams detailsParams =         TransactionDetailsParams.builder()                 .ttl(ttl)                 .construct();//Calculate payment BigInteger payment       = feeCalculationService.calculateFee(paymentTransaction,            detailsParams, null);//Set payment paymentTransaction.setFee(payment); Consequence<>String> consequence             = transactionHelperService.switch(paymentTransaction, detailsParams);

Examine additionally :

Full Supply Code:

public void switch() throws ApiException, AddressExcepion, CborSerializationException {
        BackendService backendService =
                BackendFactory.getBlockfrostBackendService(Constants.BLOCKFROST_TESTNET_URL, Fixed.BF_PROJECT_KEY);
        FeeCalculationService feeCalculationService = backendService.getFeeCalculationService();
        TransactionHelperService transactionHelperService = backendService.getTransactionHelperService();
        BlockService blockService = backendService.getBlockService();

        String senderMnemonic = "package colour frog trick communicate make use of go well with kind bomb goddess jewel major spoil fade particular person ineffective measure handle warfare scale back few scrub past period";
        Account sender = new Account(Networks.testnet(), senderMnemonic);

        String receiver = "addr_test1qqwpl7h3g84mhr36wpetk904p7fchx2vst0z696lxk8ujsjyruqwmlsm344gfux3nsj6njyzj3ppvrqtt36cp9xyydzqzumz82";

        PaymentTransaction paymentTransaction =
                PaymentTransaction.builder()
                        .sender(sender) //Sender Account object
                        .receiver(receiver)   // Receiver baseAddress as String
                        .quantity(BigInteger.valueOf(1500000))
                        .unit(CardanoConstants.LOVELACE)
                        .construct();

        lengthy ttl = blockService.getLastestBlock().getValue().getSlot() + 1000;

        TransactionDetailsParams detailsParams =
                TransactionDetailsParams.builder()
                        .ttl(ttl)
                        .construct();

        BigInteger payment
                = feeCalculationService.calculateFee(paymentTransaction, detailsParams, null);
        paymentTransaction.setFee(payment);

        Consequence<String> consequence
                = transactionHelperService.switch(paymentTransaction, detailsParams);

        if(consequence.isSuccessful())
            System.out.println("Transaction Id: " + consequence.getValue());
        else
            System.out.println("Transaction failed: " + consequence);
    }
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments