Mesh LogoMesh

Hydra Provider (beta)

The Hydra Head protocol is a layer 2 scaling solution for Cardano rooted in peer-reviewed research that increases transaction throughput and ensures cost efficiency while maintaining rigorous security.

Get started:

import { HydraProvider } from "@meshsdk/hydra";

// Hydra Head URL and PORT: e.g. http://123.45.67.890:4001

const provider = new HydraProvider({
  httpUrl: <hydra-api-url>
});

connect

Establishes a connection to a Hydra Head. This is typically managed through the HydraProvider..

await provider.connect();

hydra-head messages

Listens to messages from hydra-head

provider.onMessage((message) =>
  console.log("messages received from hydra", message)
);

can be used together with connect to Receive Messages after connect

await provider.connect();
provider.onMessage((message) =>
  console.log("messages received from hydra", message)
);

disconnect

Closes the active connection to a Hydra Head. This is typically managed through the HydraProvider.

Parameter (Optional)

  • timeout: Specifies the timeout duration in milliseconds. The default timeout is 5 minutes (300,000 ms).
// Disconnect with default timeout (5 minutes)
await provider.disconnect();

// Disconnect with custom timeout (e.g., 10 minutes)
await provider.disconnect(10 * 60 * 1000);

Hydra commands APIs

Initialize

Initializes a new Head. This command is a no-op when a Head is already open and the server will output an CommandFailed message should this happen.

await provider.init();

Abort

Aborts a head before it is opened. This can only be done before all participants have committed. Once opened, the head can't be aborted anymore but it can be closed using: Close.

await provider.abort();

Commit

Commit a particular UTxO to the head. This will make the UTxO available on the layer 2. This is used together with the HydraInstance (see the Hydra Instance page for details).

await instance.commitFunds(txHash, outputIndex);

New Transaction

Submit a transaction through the head. Note that the transaction is only broadcast if well-formed and valid. The newTx method accepts the following arguments:

parameters

  • cborHex: This is the transaction in hex format usually the unsigned transaction.
  • type: Any transaction is tried to decode as a 'ConwayEra' transaction, which mostly is backward compatible to previous eras.
  • description(optional): transaction description

returns

  • txId(transaction Hash)
async provider.newTx({
    cborHex: "<unsignedTx>",
    description: "commit tx",
    type: "Tx ConwayEra",
  })

Here is an example of how to create a transaction using the Hydra provider, Mesh wallet and Mesh transaction builder:

async function makeTx() {
  const walletA = {
    addr: "addr_test1vpsthwvxgfkkm2lm8ggy0c5345u6vrfctmug6tdyx4rf4mqn2xcyw",
    key: "58201aae63d93899640e91b51c5e8bd542262df3ecf3246c3854f39c40f4eb83557d",
  };

  const wallet = new MeshWallet({
    networkId: 0,
    key: {
      type: "cli",
      payment: walletA.key,
    },
    fetcher: provider,
    submitter: provider,
  });

  const pp = await provider.fetchProtocolParameters();
  const utxos = await wallet.getUtxos("enterprise");
  const changeAddress = walletA.addr;

  const txBuilder = new MeshTxBuilder({
    fetcher: provider,
    params: pp,
    verbose: true,
  });

  const unsignedTx = await txBuilder
    .txOut("addr_test1vpd5axpq4qsh8sxvzny49cp22gc5tqx0djf6wmjv5cx7q5qyrzuw8", [
      { unit: "lovelace", quantity: "3000000" },
    ])
    .changeAddress(changeAddress)
    .selectUtxosFrom(utxos)
    .complete();

  const signedTx = await wallet.signTx(unsignedTx);
  const txHash = await wallet.submitTx(signedTx);
  console.log("txHash", txHash);
}

Decommit

Request to decommit a UTxO from a Head by providing a decommit tx. Upon reaching consensus, this will eventually result in corresponding transaction outputs becoming available on the layer 1.

The decommit method accepts the following arguments:

async decommit({
  cborHex: "<unsignedTx>",
  description: "commit tx",
  type: "Tx ConwayEra"
})

Close

Terminate a head with the latest known snapshot. This effectively moves the head from the Open state to the Close state where the contestation phase begin. As a result of closing a head, no more transactions can be submitted via NewTx.

await provider.close();

Contest

Challenge the latest snapshot announced as a result of a head closure from another participant. Note that this necessarily contest with the latest snapshot known of your local Hydra node. Participants can only contest once.

await provider.contest();

Fanout

Finalize a head UTxOs to L1 after the contestation period passed.

await provider.fanout();

Hydra Query APIs

Fetch UTxOs

Get UTxOs for a given hash. Optionally, you can specify the index of the index output.

await provider.fetchUTxOs("txHash");

Fetch Address UTxOs

Fetch UTxOs controlled by an address.

Optionally, you can filter UTXOs containing a particular asset by providing asset, where it is the concatenation of policy ID and assetname.

await provider.fetchAddressUTxOs(address: string, asset?: string)

Fetch Asset Addresses

Fetches the addresses and quantities for a given Cardano asset.

await provider.fetchAssetAddresses(asset: string):

Fetch collection Assest

Fetches the list of assets for a given policy ID.

await provider.fetchCollectionAssets(policyId: string)

Fetch Protocol Parameters

Fetch the latest protocol parameters.

await provider.fetchProtocolParameters();

Optionally, you can provide an epoch number to fetch the protocol parameters of that epoch.`

Listens for new messages from Hydra node

Listens for new messages from Hydra node. The callback function will be called with the message as the only argument. Check all events emitted by the Hydra node.

provider.onMessage((message) => {
  if (message.tag === "Greetings") {
    console.log("message.snapshotUtxo", message.snapshotUtxo);
  }
});

Submit Transaction

Submit a serialized transaction to the network.

const txHash = await provider.submitTx(signedTx);
console.log("txHash", txHash);