Saturday, May 11, 2024
HomeJavaCardano Mempool monitoring with Yaci Java Library - Java Code Geeks

Cardano Mempool monitoring with Yaci Java Library – Java Code Geeks


On this submit, I’m going to elucidate tips on how to monitor a neighborhood Cardano node’s mempool utilizing Java or any JVM language. To do this we’re going to use a small Java library referred to as “Yaci” and we want an occasion of Cardano node.

An opensource challenge which implements Cardano mini-protocol.

Mini-protocols are a set of protocols that are used to allow communication between completely different Cardano nodes. These protocols may also be utilized by different consumer purposes like indexer, explorer, wallets to fetch knowledge from a node and create their very own knowledge retailer. There are two classes: node-to-node and node-to-client. The node-to-client protocol suite is generally for trusted purchasers like wallets and chain customers.

Yaci implements many of the mini protocols together with native transaction submission.

To seek out the listing of mini-protocols presently supported by Yaci, please go to challenge’s GitHub web page.

https://github.com/bloxbean/yaci#standing

To simplify the utilization of mini protocol, it additionally gives varied excessive degree apis for various situations. So Java builders don’t want to know the low degree protocol particulars. There are two forms of excessive degree apis

Utilizing listener primarily based apis, you possibly can simply get callbacks for various occasions like new blocks, rollback and so on.

Utilizing reactive apis, you possibly can obtain blocks knowledge by way of a Flux and may compose functionalities utilizing obtainable operators like filter, map and so on.

Utilization Eventualities Examples :

The followings are few examples the place Yaci can be utilized

  • To hear real-time occasions from a node (Instance: Token minting, Token minted for a coverage, Transactions …)
  • Obtain block/transaction knowledge and create your personal knowledge retailer or question layer
  • Alert or notification primarily based on occasions in blockchain
  • Create your personal indexer
  • Implement a Tx submission service by submitting transactions to a neighborhood Cardano node or a distant node with node-to-client protocol uncovered by way of a relay like “socat”

As talked about earlier, we are going to undergo the steps required for native mempool monitoring.

Pre-requisites

  1. Native Tx Monitor is a node-to-client protocol. Node-to-client protocols are uncovered by way of Unix area socket. So {that a} native trusted consumer can join and entry these data from Cardano node. However you should utilize a relay like “socat” to show Unix area socket by way of a TCP socket for distant purchasers.

Instance :

socat TCP-LISTEN:31001,fork UNIX-CONNECT:/knowledge/cardano/pre-prod/db/node.socket

The apis for native tx monitoring in yaci accepts each path host / port and native socket file.

2. Create a Java app and add Yaci dependency to it

<dependency>
     <groupId>com.bloxbean.cardano</groupId>
     <artifactId>yaci</artifactId>
     <model>0.1.2</model>
</dependency>

Notice: Get the newest launched model of Yaci from challenge’s GitHub.

As we can be getting transaction bytes from the mempool, we are going to use “cardano-client-lib” to get transaction hash and to de-serialize transaction. That is solely required for our instance.

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

Configure and begin the connection

First we have to setup the connection to a Cardano node by way of node-to-client protocol. So let’s get the trail to Cardano’s nodeSocketFile and community’s protocol magic.

 String nodeSocketFile = "~/cardano-node/preprod/db/node.socket";
 lengthy protocolMagic = Constants.PREPROD_PROTOCOL_MAGIC;

Notice: You should utilize com.bloxbean.cardano.yaci.core.frequent.Fixed class to get protocol magics for public networks.

Alternatively, if the node-to-client protocol is uncovered by way of a relay like “socat”, get host and port.

Now, create an occasion of LocalClientProvider and begin the consumer.
As LocalClientProvider helps each native state question and native tx monitor mini protocols, now you can execute supported queries on a node.

 LocalClientProvider localClientProvider = new LocalClientProvider(nodeSocketFile, protocolMagic);
 localClientProvider.begin();

Within the above code snippet, we’re creating a neighborhood consumer after which beginning the consumer.

Let’s get “LocalTxMonitorClient” from localClientProvider.

LocalTxMonitorClient localTxMonitorClient = localClientProvider.getTxMonitorClient();

Now we’re prepared to question the node.

Question Mempool Transactions

To get the listing of transactions presently within the mempool, we have to first purchase a mempool snapshot after which question the snapshot. You may purchase and question in two methodology calls or simply use “acquireAndGetMempoolTransactionsAsMono()” which wraps each steps in a single methodology name.

On this instance, let’s monitor the mempool in a loop. Purchase methodology is a blocking name, so this system waits there until the supply of latest snapshot.

whereas (true) {
     // native tx monitor code
}

Let’s add the next code snippets within the above whereas(true) loop.

Listing<byte[]> txBytesList = localTxMonitorClient.acquireAndGetMempoolTransactionsAsMono().block();

The above code will purchase a brand new snapshot when obtainable and return an inventory of transactions as bytes in a Mono. We’re utilizing “block()” to get the listing of transactions by way of a blocking name.
Notice: It is best to use Mono’s non-blocking api like “subscribe” in your software to keep away from blocking.

Now that we’ve an inventory of transactions as bytes, we are able to loop by way of the listing to get transaction hashes and de-serialize obtainable transactions. This may be simply finished utilizing Cardano Consumer Lib.

for(byte[] txBytes: txBytesList) {
    String txHash = TransactionUtil.getTxHash(txBytes);
    System.out.println("Tx Hash >> " + txHash);

    Transaction transaction = Transaction.deserialize(txBytes);
    System.out.println("Tx Physique >> " + transaction);
}

Lastly, let’s get the mempool dimension and capability. Native tx monitor additionally gives data like mempool capability, dimension and no of txs.

The next code snippet is getting the mempool standing. You may see that we’re utilizing “getMempoolSizeAndCapacity()” within the under code snippet. This methodology doesn’t purchase a brand new snapshot and it makes use of the already acquired snapshot within the earlier name.
However if you wish to purchase a brand new snapshot and question mempool standing, then you should utilize “acquireAndGetMempoolSizeAndCapacity()”.

MempoolStatus mempoolStatus = localTxMonitorClient.getMempoolSizeAndCapacity().block();
System.out.println("Mem Pool >> " + mempoolStatus);

Our mempool monitoring app is now prepared. Run this program after which submit few transactions to this node by way of one other program or Cardano CLI, it is best to begin seeing the transactions as quickly as these can be found in mempool.

Pattern Output:

Ready to accumulate subsequent snapshot ...
Mem Pool >> MempoolStatus(capacityInBytes=178176, sizeInBytes=0, numberOfTxs=0)
Ready to accumulate subsequent snapshot ...
Tx Hash >> 4d7ce3ece2f9aa36550763753df3885344b1f15ea1e67dd7c9f3f49924f0f480
Tx Physique >> Transaction(physique=TransactionBody(inputs=[TransactionInput{transactionId=7e36a90a9b85902d5b42599f831d...
Waiting to acquire next snapshot ...

That’s it. We covered only one use case in this post, but Yaci provides different apis which can support many different types of use cases.

Here’s a list of few major high level apis in Yaci that you may find interesting

  • BlockStreamer : Reactive api to start getting blocks from current tip or from a given point.
  • BlockSync : Get latest block data starting from current tip through a listener.
  • BlockRangeSync : Get blocks data from point-1 to poin-2 through a listener
  • LocalTxSubmissionClient : To submit a transaction to Cardano node
  • TipFinder To find the tip through a simple method call

Full source code of mempool monitoring example

import com.bloxbean.cardano.client.exception.CborDeserializationException;
import com.bloxbean.cardano.client.transaction.spec.Transaction;
import com.bloxbean.cardano.client.transaction.util.TransactionUtil;
import com.bloxbean.cardano.yaci.core.common.Constants;
import com.bloxbean.cardano.yaci.helper.LocalClientProvider;
import com.bloxbean.cardano.yaci.helper.LocalTxMonitorClient;
import com.bloxbean.cardano.yaci.helper.model.MempoolStatus;

import java.util.List;

public class LocalTxMonitorSample {

    public static void main(String[] args) throws CborDeserializationException {
        String nodeSocketFile = "~/cardano-node/preprod/db/node.socket";
        lengthy protocolMagic = Constants.PREPROD_PROTOCOL_MAGIC;

        LocalClientProvider localClientProvider = new LocalClientProvider(nodeSocketFile, protocolMagic);
        localClientProvider.begin();
        LocalTxMonitorClient localTxMonitorClient = localClientProvider.getTxMonitorClient();

        whereas (true) {
            System.out.println("Ready to accumulate subsequent snapshot ...");
            Listing<byte[]> txBytesList = localTxMonitorClient.acquireAndGetMempoolTransactionsAsMono().block();

            for(byte[] txBytes: txBytesList) {
                String txHash = TransactionUtil.getTxHash(txBytes);
                System.out.println("Tx Hash >> " + txHash);

                Transaction transaction = Transaction.deserialize(txBytes);
                System.out.println("Tx Physique >> " + transaction);
            }

            MempoolStatus mempoolStatus = localTxMonitorClient.getMempoolSizeAndCapacity().block();
            System.out.println("Mem Pool >> " + mempoolStatus);
        }
    }
}
<dependency>
     <groupId>com.bloxbean.cardano</groupId>
     <artifactId>yaci</artifactId>
     <model>0.1.2</model>
</dependency>
     <dependency>
     <groupId>com.bloxbean.cardano</groupId>
     <artifactId>cardano-client-lib</artifactId>
     <model>0.4.0</model>
</dependency>

References:
1. Yaci : A Cardano Mini Protocols implementation in Java (https://github.com/bloxbean/yaci)

2. Cardano Consumer Lib : Cardano consumer library in Java (https://github.com/bloxbean/cardano-client-lib)

3. Yaci CLI : A CLI instance utilizing Yaci (https://github.com/bloxbean/yaci-cli)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments