Wednesday, November 30, 2022
HomeJavaCardano-client-lib: New composable capabilities to construct transaction in Java— Half I -...

Cardano-client-lib: New composable capabilities to construct transaction in Java— Half I – Java Code Geeks


Cardano-client-lib is a Java consumer library for Cardano blockchain. It simplifies the interplay with Cardano blockchain from a Java software. Utilizing this library, you possibly can carry out numerous forms of transactions in a Java software.

Cardano-client-lib is a Java consumer library for Cardano blockchain. It simplifies the interplay with Cardano blockchain from a Java software. Utilizing this library, you possibly can carry out numerous forms of transactions in a Java software.

For instance, you are able to do a switch from one handle to a different, mint a token or an NFT and invoke a Plutus good contract in Java.

On this submit, I’m going to clarify the idea of newly launched composable capabilities API.

Within the subsequent few posts of this sequence, I’ll undergo particular examples from common switch to token minting to plutus contract calls utilizing composable operate apis.

If you’re new to cardano-client-lib, it at the moment helps three forms of apis to construct / carry out numerous transactions.

  1. Excessive Stage API : Gives easy interfaces to do switch and token minting transaction. However some complicated transactions is probably not attainable by means of high-level API.
  2. Low Stage API : These are low degree serialization api to construct transaction for Cardano community. These APIs are versatile and good for complicated eventualities. Principally, you possibly can obtain any complexity with low degree api, however on the similar time these APIs should not newbie pleasant.
  3. Composable Features : These APIs have been launched in v0.2.0-beta2 which give a steadiness between easy interface and suppleness. Utilizing out-of-box composable capabilities, you possibly can obtain any complexity and on the similar time, you possibly can write your individual composable capabilities to customise the habits throughout transaction constructing.

So on this submit, I’m going to give attention to the final ideas of composable capabilities within the library.

The present model (0.2.0-beta2 or later) of the library supplies a set of FunctionalInterface which can be utilized to implement composable capabilities. These capabilities can be utilized to construct numerous several types of transactions. The library supplies many helpful out-of-box implementations of those capabilities.

The followings are the principle FunctionalInterface

  1. TxBuilder
  2. TxOutputBuilder
  3. TxInputBuilder
  4. TxSigner

TxBuilder : This practical interface helps to remodel a transaction object. The construct methodology on this interface takes a TxBuilderContext and a Transaction object as enter parameters. The function of this operate is to remodel the enter transaction object with further attributes or replace current attributes.

TxOutputBuilder : This practical interface helps to construct a TransactionOutput object and add that to the transaction output checklist. The settle for methodology on this interface takes a TxBuilderContext and a listing of TransactionOutput.

TxInputBuilder : This practical interface is accountable to construct inputs from the anticipated outputs.

TxSigner : This interface is accountable to offer transaction signing functionality.

Every operate takes TxBuilderContext as the primary enter parameter. The primary duty of TxBuilderContext is to offer context knowledge like BackendService, UtxoSelectionStrategy and a few short-term knowledge to the capabilities through the transaction constructing.

The library supplies many out-of-box capabilities by means of helper courses which assist to construct the transaction. So that you don’t want to start out from zero and the identical time you possibly can write your individual capabilities if required.

Within the present model (0.2.0-beta2) of the library, the next helper courses can be found

  1. OutputBuilders : Gives a listing of helper strategies to create a TxOutputBuilder operate which is used create a TransactionOutput from a TransactionOutput or Output object. The TxOutputBuilder capabilities confirm min ada requirement and replace the ada quantity accordingly within the TransactionOutput.

A few of the helper strategies obtainable on this class are

- TxOutputBuilder createFromOutput(Output output) 
- TxOutputBuilder createFromOutput(TransactionOutput txnOutput) 
- TxOutputBuilder createFromMintOutput(Output output) 
- TxOutputBuilder createFromMintOutput(TransactionOutput txnOutput)

You possibly can mix a number of TxOutputBuilder utilizing “and” methodology.

TxOutputBuilder txOutputBuilder = createFromOutput(output1)                                      .and(createFromOutput(output2))

Observe: For token minting transaction, to calculate min required ada in output precisely, mint outputs or createFromMintOutput() strategies needs to be invoked in any case common outputs or createFromOutput() strategies.

2. InputBuilders : Gives helper strategies to create a TxInputBuilder operate which is used to construct required TransactionInput(s) from a listing of TransactionOutput(s) utilizing buildInputs() methodology of TxOutputBuilder.

TxBuilder txBuilder = txOutputBuilder1                        
.and(txOutputBuilder2)                        
.buildInputs(createFromSender(senderAddress, changeAddress))

A few of the helper strategies obtainable on this class are

- TxInputBuilder createFromSender(String sender, String changeAddress) 
- TxInputBuilder createFromUtxos(Listing<Utxo> utxos) 
- TxInputBuilder createFromUtxos(Provider<Listing<Utxo>> provider) 
- TxInputBuilder createFromUtxos(Listing<Utxo> utxos, String changeAddress) 
- TxInputBuilder createFromUtxos(Listing<Utxo> utxos, String changeAddress, Object datum) 
- TxInputBuilder createFromUtxos(Listing<Utxo> utxos, String changeAddress, String datumHash)

3. MintCreators : It supplies helper strategies to create a TxBuilder operate which is used so as to add multiasset minting associated knowledge to the Transaction object.

TxBuilder txBuilder = txOuputBuilder1                         
.and(txOuputBuilder2)                         
.and(createFromMintOutput(mintOutput))                       
.buildInputs(txInputBuilder)                       
.andThen(mintCreator(script, multiAsset)

Observe: For minting transaction, a TxOutputBuilder particular to mint output is required. This may be finished by calling one of many OutputBuilders.createFromMintOutput methodology.

A few of the helper strategies obtainable on this class are

- TxBuilder mintCreator(Script script, MultiAsset multiAsset) 
- TxBuilder mintCreator(Script script, MultiAsset multiAsset, boolean inclScriptInAuxData)

4. AuxDataProviders : Gives helper strategies to create a TxBuilder operate which is used so as to add metadata to the Transaction object.

TxBuilder txBuilder = txOuputBuilder1                         
.and(txOuputBuilder2)                       
.buildInputs(txInputBuilder)                       
.andThen(metadataProvider(metadata))

5. CollateralBuilders : Gives helper strategies to create a TxBuilder operate which is used so as to add collateral(s) to the Transaction object in a plutus script transaction.

TxBuilder txBuilder = txOuputBuilder1                         
.and(txOuputBuilder2)                       
.buildInputs(txInputBuilder)                       
.andThen(collateralFrom(txHash, txIndex))

A few of the helper strategies obtainable on this class are

- TxBuilder collateralFrom(String txHash, int txIndex) 
- TxBuilder collateralFrom(Listing<Utxo> utxos) 
- TxBuilder collateralFrom(Provider<Listing<Utxo>> provider)

6. ScriptCallConextProviders : Gives helper strategies to create a TxBuilder operate which is used so as to add plutus script particular knowledge to a Transaction object.

TxBuilder txBuilder = txOuputBuilder1               
.and(txOuputBuilder2)            
.buildInputs(txInputBuilder)            
.andThen(collateralFrom(txHash, txIndex))            
.andThen(createFromScriptCallContext(scriptCallContext))

A few of the helper strategies obtainable on this class are

- TxBuilder createFromScriptCallContext(ScriptCallContext sc) 
- TxBuilder scriptCallContext(PlutusScript plutusScript, Utxo utxo, T datum, Okay redeemerData,RedeemerTag tag, ExUnits exUnits) 
- TxBuilder scriptCallContext(PlutusScript plutusScript, int scriptInputIndex, T datum, Okay redeemerData, RedeemerTag tag, ExUnits exUnits)

7. FeeCalculators : Gives helper strategies to create TxBuilder operate to calculate price and replace Transaction object accordingly.

TxBuilder txBuilder = txOuputBuilder1                        
.and(txOuputBuilder2)                       
.buildInputs(txInputBuilder)                       
.andThen(otherTxBuilder)                       ...                       
.andThen(feeCalculator(changeAddress, noOfSigners))

Observe: No of signers is required to calculate the price precisely. For instance, for a minting transaction with a coverage script, min no of signers is 2. (Minting account, Coverage script secret key)

Helper strategies to create TxBuilder operate on this helper class are

- TxBuilder feeCalculator(String changeAddress, int noOfSigners) 
- TxBuilder feeCalculator(int noOfSigners, UpdateOutputFunction updateOutputWithFeeFunc)

8. ChangeOutputAdjustments : Gives helper strategies to create TxBuilder operate which may modify the change output. This operate is used to confirm if the ada quantity in change output satisfies min ada requirement. If not, it tries to get further inputs and modify the change output after the price calculation. This operate is used after feeCalculation operate.

TxBuilder txBuilder = txOuputBuilder1              
.and(txOuputBuilder2)              
.buildInputs(txInputBuilder)              
.andThen(otherTxBuilder)              ...              
.andThen(feeCalculator(changeAddress, noOfSigners))              
.andThen(adjustChangeOutput(senderAddress, changeAddress, noOfSigners))

9. SignerProviders : Gives helper strategies to create TxSigner operate to signal a transaction.

TxSigner signer = signerFrom(sender1, sender2, ..., sendern)            .andThen(signerFrom(secretKey1, ..., secretKeyn))

A few of the helper strategies obtainable on this class are

- TxSigner signerFrom(Account... signers)
- TxSigner signerFrom(SecretKey... secretKeys)
- TxSigner signerFrom(Coverage... insurance policies)

10. MinAdaCheckers : Gives a helper methodology to return MinAdaChecker operate. MinAdaChecker operate returns the extra lovelace quantity required for a TransactionOutput to satisfy the min ada requirement. This operate is used internally by implementations of different capabilities. Chances are you’ll not want to make use of this operate instantly.

After TxBuilder is created by composing completely different capabilities, a Transaction object may be constructed and signed.

TxBuilder txBuilder = createFromOutput(output)         .buildInputs(createFromSender(senderAddress, senderAddress))         
.andThen(metadataProvider(metadata))         
.andThen(feeCalculator(senderAddress, 1))         
.andThen(adjustChangeOutput(senderAddress, 1));
TxSigner signer = SignerProviders.signerFrom(sender);
/**** Construct and Signal in a single step ****/ 
Transaction signedTxn = TxBuilderContext.init(backendService)                                 .buildAndSign(txBuilder, signer);
/**** OR, Construct Txn after which signal utilizing signer *****/ 
Transaction transaction = TxBuilderContext.init(backendService)                             
.construct(txBuilder); 
Transaction signedTxn = signer.signal(transaction);

As soon as a transaction is signed, you possibly can submit it to the community utilizing TransactionService.

Outcome<String> consequence =           transactionService.submitTransaction(signedTxn.serialize());

In some eventualities, that you must present your individual TxBuilder and different capabilities to remodel the transaction object.

Instance :
Proper now, there isn’t any TxBuilder operate to set ttl parameter within the transaction object. However you possibly can simply present your individual implementation to set ttl or add/replace different parameters.

TxBuilder txBuilder = txOuputBuilder1              
.and(txOuputBuilder2)              
.buildInputs(txInputBuilder)              
.andThen(otherTxBuilder)              
.andThen((context, transaction) -> {                    
transaction.getBody().setTtl(100000);                   
//set or replace different transaction parameters              
})              
.andThen(feeCalculator(changeAddress, noOfSigners))

So in abstract, to make use of the composable operate API, observe these under steps to construct a transaction

  1. Outline anticipated outputs
  2. Create a number of TxOutputBuilder from outputs
  3. Create a TxInputBuilder which selects inputs for a sender
  4. Step-1 to Step-3 may be repeated for a number of senders
  5. Create further TxBuilder(s) so as to add / replace completely different attributes within the transaction.
  6. Create TxSigner
  7. Invoke TxBuilderContext.init() to initialize the context after which invoke buildAndSign() to construct and signal the transaction.

Within the subsequent few posts of this sequence, I’ll undergo particular examples from common switch to token minting to Plutus contract calls utilizing composable operate APIs.

In the meantime, yow will discover completely different examples utilizing composable capabilities on this GitHub repo

  1. Cardano Shopper Lib Challenge GitHub
  2. Cardano Shopper Instance GitHub

Be a part of Coinmonks Telegram Channel and Youtube Channel study crypto buying and selling and investing

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments