Call Plutus V2 contract from off-chain Java code using Cardano Client Lib

Satya
8 min readJul 29, 2022

--

In this post, we will go through the steps required to invoke a Plutus smart contract from a Java application using Cardano Client Lib.

Cardano-client-lib is a Java client library for Cardano blockchain. It simplifies the interaction with Cardano blockchain from Java applications. Using this library, you can perform various types of transactions including smart contract calls in a Java application.

Compatible version: Cardano Client Lib 0.3.0-beta2 and above

Plutus Contract Example

We will use a simple contract called “Sum Contract” as an example in this post. To validate, the sum contract checks the sum of 0..n, where n is the datum value. The caller can unlock the fund in a script output by guessing the correct sum.

While this is a very simple plutus contract, but through this example we will try to use some of the new exciting features available in Babbage era (after Vasil Hardfork).

  1. Reference Inputs (CIP 31)
  2. Inline Datums (CIP 32)
  3. Reference Scripts (CIP 33)
  4. Collateral Output (CIP 40)

So, in high level we will be going through the following steps :

  1. Create a reference script output to attach a script to the output. This is part of CIP 33. With reference script output, we don’t need to send the script body in the spending transaction.
  2. Send some fund to script address with inline datum. The fund will be locked in the script output. Inline datum is defined in CIP 32. So instead of storing datum hash, we can now store datum value directly in the output.
  3. Finally, create a spending transaction to unlock fund in script output. In spending transaction, we will refer to the reference script output (step-1) as a reference input. This is part of CIP 31. Also, we are going to use collateral outputs (CIP 40) in the spending transaction.

Before going through our example, let’s discuss some basic concepts in Cardano Client Lib. For more details, you can check my previous posts.

Alternatively, you can jump to the section “Invoke Guess Sum Contract” if you are already aware of these concepts.

Composable Functions

A set of FunctionalInterface which can be used to implement composable functions. These functions are used to build various different types of transactions. The library provides many useful out-of-box implementations of these functions. Most of the commonly used functions are already there. If required, application developers can write their own functions and use them with other out of box functions.

The followings are the main FunctionalInterface

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

TxBuilder : This functional interface helps to transform a transaction object. The apply method in this interface takes a TxBuilderContext and a Transaction object as input parameters. The role of this function is to transform the input transaction object with additional attributes or update existing attributes.

TxOutputBuilder : This functional interface helps to build a TransactionOutput object and adds that to the transaction output list. The accept method in this interface takes a TxBuilderContext and a list of TransactionOutput.

TxInputBuilder : This functional interface is responsible to build inputs for the expected outputs.

TxSigner : This interface is responsible to provide transaction signing capability.

Backend Service and Supplier Interfaces

The library provides a backend service layer, which is required to build and submit transaction to Cardano blockchain. By default, it provides backend service implementations for Blockfrost, Koios etc.

But, if you want to use some other providers to build and submit transaction, you can easily do so by implementing following three simple interfaces :

  1. ProtocolParameterSupplier :- Implement this functional interface to provide current protocol parameters. Protocol parameters are required to build the transaction.
public interface ProtocolParamsSupplier {
ProtocolParams getProtocolParams();
}

2. UtxoSupplier:- This interface has only one method. Implement this interface to provide utxos which are required during transaction building.

3. TransactionProcessor :- Implement this interface to submit transaction to the Cardano blockchain.

public interface TransactionProcessor {

Result<String> submitTransaction(byte[] cborData) throws ApiException;
}

Note: If you are using a supported backend provider like Blockfrost, you can just use the out-of-box backend service implementation.

Invoke Guess Sum Contract

In this section, we will go through the example step by step. You can also find the full source code of the example here.

Now, let’s start with some initialization steps.

Account setup

To submit any transaction to Cardano blockchain, we need an account to sign and pay transaction fee.

So, let’s see how to create a sender account object from a mnemonic phrase. We will be using this account to send fund to the script output and also to unlock the fund.

String senderMnemonic = "<24 words mnemonic phrase>";Account sender = new Account(Networks.testnet(), senderMnemonic);String senderAddress = sender.baseAddress();

Plutus V2 Script Object and Script address

We need to use the compiled version of our Sum contract script. The following code snippet shows how to initialize the PlutusV2Script instance and find the script address.

1. Create a reference script output

Now that we have an account and a script instance, we can build and submit a transaction to create a reference script output. The script body will be stored in the output on-chain.

Let’s first start with the expected output.

We want to create an output with script reference. For simplicity, we can set the lovelace amount in the output to 0. The library will automatically calculate the min required ada and set it accordingly. You can also see the sumScript is passed as parameter in scriptRef().

Now with the above expected output, let’s create an instance of TxBuilder using composable functions.

In the above code snippet, we are getting TxOutputBuilder from the expected output (scriptRefOutput) and then using createFromSender composable function, we are creating TxInputBuilder and finally, buildInputs method is using TxInputBuilder to return TxBuilder.

So in summary, we selected required TransactionInputs for our expected output.

In Line-3, we are using another composable function “balanceTx” to balance the transaction. This is a wrapper function which calls other low level functions like feeCalculation, changeOutputAdjustment to balance an unbalanced transaction. The “balanceTx” function takes two parameters, change address and no of signers.

Now, we can build the transaction using TxBuilder and submit it to Cardano network.

In Line-1, a TxBuilderContext is created using UtxoSupplier and ProtocolParamsSupplier as parameters. If you are using Blockfrost or Koios as provider, these implementation are provided out-of-box. But you can easily provide your own supplier implementations if required.

In Line-2, TxBuilderContext’s buildAndSign method is used to build and sign the transaction by applying the previously created TxBuilder instance (scriptRefTxBuilder) and the TxSigner instance for sender.

In Line-4, the signed transaction is then submitted through the backend service’s TransactionService implementation. Alternatively, you can use your own TransactionProcessor implementation to submit the transaction.

That’s it. Now we have an output with script body as script reference.

2. Send fund to script address with inline datum

Now it’s time to send some fund to the script address that we had generated earlier using the PlutusV2Script instance. We will set an integer as datum value for the output. But instead of setting datum hash, the datum value will be directly stored in the output.

This is a simple transaction like step-1 but with inline datum.

In Line-1, we are creating an integer type Plutus data which is used as inline datum. The datum value is 8.

In Line-3 to Line-8, the expected output is defined with the inline datum (8).

Line-10 to Line 17 are similar to step-1, where a transaction is built and signed by TxBuilder, TxBuilderContext and finally submitted through TransactionService.

Now, we have an output at the script address with some locked fund (4 ADA) .

In the next section, we are going to create a spending transaction to unlock the fund.

3. Create a spending transaction (script txn) to spend the locked fund

To spend the locked fund, let’s first find the output at the script address.

You can use one of the helper method in ScriptUtxoFinders class to find the required output.

In Line-1, we find the output using datum.

In Line-2 to Line-5, we are trying to find the claim amount from the output. It’s basically the lovelace value in this example.

Now, it’s time to find some collateral for our script transaction.

In Babbage era (after Vasil HF), we can also use an utxo with native tokens as collateral. The remaining lovelace amount and native tokens are sent back as collateral output. You can find more details about collateral outputs spec in CIP 40.

In the above code snippet, we are using UtxoSelectionStrategy to find an utxo with minimum 5 ADA for the collateral input. In this case, we are using LargestFirstUtxoSelectionStrategy implementation, but you can also use other implementations like DefaultUtxoSelectionStrategyImpl or RandomImproveSelectionStrategy.

Alternatively, you can also use DefaultUtxoSelector class by providing a predicate.

Now, let’s define the expected output and create a script call context.

Line-1 to Line-5, define an expected output with the claim amount and a receiver address.

In Line-7 to Line-8, we are creating a ScriptCallContext with all required data like script object, redeemer details and exunits.

Note that the redeemer value is set to 36 as the sum of our datum (0..8) is 36.
ExUnits value is set to 0 as we are going to evaluate the actual script cost later.

Also, we are not providing datum value as our script output has inline datum instead of datum hash.

Now we are ready to create our TxBuilder instance and then create & sign the transaction and finally submit to the Cardano network to unlock the locked value.

Line-1 & Line-2 : Use the expected output and create inputs from script utxo that we found in one of the previous step.

Line-3 : Add reference script output (from step-1) as reference input. This is part of CIP 31.

Line-4 : Create collateral and collateral outputs using collateral utxos. The sender address is used as change address for collateral outputs.

Line-5: Use ScriptCallContext instance that we created before to populate script call related attributes in the transaction.

Line-6 to Line-15 : Evaluate exact ExUints by invoking evaluateTx() of backend service. This can also be done as a separate step before building of transaction. But, please make sure it’s done before fee calculation or before balanceTx method call.

Line-22 to Line-28 : Now as usual, build the transaction and submit it to Cardano network.

That’s it. We successfully invoked our on-chain plutus contract from off-chain Java code using Cardano Client Lib.

Full source code

For more examples, you can check Cardano Client Example GitHub repo.

Resources

  1. Cardano Client Lib GitHub Repo
  2. Cardano Client Example Repo
  3. New Composable functions to build transaction

--

--

Satya
Satya

Written by Satya

A developer’s journey in blockchain world

Responses (1)