packages feed

cardano-c-clib-0.1.1.0: vendor/src/transaction_builder/internals/builder_build.c

/**
 * \file builder_build.c
 *
 * \author angel.castillo
 * \date   Jul 18, 2026
 *
 * Copyright 2026 Biglup Labs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* INCLUDES ******************************************************************/

#include "builder_build.h"

#include <cardano/address/address.h>
#include <cardano/common/credential.h>
#include <cardano/common/guard_set.h>
#include <cardano/common/protocol_version.h>
#include <cardano/common/utxo.h>
#include <cardano/common/utxo_list.h>
#include <cardano/crypto/blake2b_hash.h>
#include <cardano/crypto/blake2b_hash_set.h>
#include <cardano/protocol_params/cost_model.h>
#include <cardano/protocol_params/costmdls.h>
#include <cardano/scripts/plutus_scripts/plutus_language_version.h>
#include <cardano/transaction/sub_transaction.h>
#include <cardano/transaction_body/required_guards_map.h>
#include <cardano/transaction_body/sub_transaction_body.h>
#include <cardano/transaction_body/sub_transaction_set.h>
#include <cardano/transaction_body/transaction_body.h>
#include <cardano/transaction_body/transaction_input_set.h>
#include <cardano/transaction_body/transaction_output.h>
#include <cardano/transaction_builder/balancing/transaction_balancing.h>
#include <cardano/transaction_builder/script_data_hash.h>
#include <cardano/witness_set/plutus_data_set.h>
#include <cardano/witness_set/redeemer_list.h>
#include <cardano/witness_set/witness_set.h>

#include "../balancing/internals/collateral.h"
#include "../balancing/internals/scripts_needed.h"
#include "../balancing/internals/unique_signers.h"

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>

/* STATIC DECLARATIONS *******************************************************/

/**
 * \brief Reports whether CIP-172 script sources are enabled by the protocol parameters.
 * \param[in] state The builder state.
 * \return True for Dijkstra and later.
 */
static bool
uses_created_output_scripts(cardano_builder_state_t* state)
{
  cardano_protocol_version_t* version = cardano_protocol_parameters_get_protocol_version(state->params);
  const bool                  enabled = cardano_protocol_version_get_major(version) >= 12U;
  cardano_protocol_version_unref(&version);
  return enabled;
}

/**
 * \brief Retrieves the cost model for a specified Plutus language version.
 *
 * This function searches for the cost model matching the specified Plutus language version within a
 * provided set of source cost models and, if found, copies it into a destination cost model set.
 *
 * \param[in] source_models A pointer to the \ref cardano_costmdls_t object containing the source cost models.
 * \param[out] dest_models A pointer to the \ref cardano_costmdls_t object where the matching cost model
 *                         for the specified version will be copied. This parameter must not be NULL.
 * \param[in] version The Plutus language version of the cost model to retrieve.
 *
 * \return \ref cardano_error_t indicating the result of the operation. Returns \ref CARDANO_SUCCESS if the cost model
 *         was successfully found and copied, or an appropriate error code if an internal error occurs.
 */
static cardano_error_t
get_cost_model_for_version(
  cardano_costmdls_t*                     source_models,
  cardano_costmdls_t*                     dest_models,
  const cardano_plutus_language_version_t version)
{
  assert(source_models != NULL);
  assert(dest_models != NULL);

  cardano_cost_model_t* cost_model = NULL;

  cardano_error_t result = cardano_costmdls_get(source_models, version, &cost_model);
  cardano_cost_model_unref(&cost_model);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  result = cardano_costmdls_insert(dest_models, cost_model);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Checks whether a guard set holds a credential.
 *
 * Two credentials are the same guard only when both their type and their hash match.
 *
 * \param[in] guards A pointer to the \ref cardano_guard_set_t to search, or NULL when the transaction
 *                   carries no guards.
 * \param[in] credential A pointer to the \ref cardano_credential_t to look up.
 *
 * \return true if the guard set holds the credential, false otherwise.
 */
static bool
has_guard(const cardano_guard_set_t* guards, const cardano_credential_t* credential)
{
  const size_t length = cardano_guard_set_get_length(guards);
  bool         found  = false;

  for (size_t i = 0U; (i < length) && !found; ++i)
  {
    cardano_credential_t* guard = NULL;

    const cardano_error_t result = cardano_guard_set_get(guards, i, &guard);
    cardano_credential_unref(&guard);

    found = (result == CARDANO_SUCCESS) && cardano_credential_equals(guard, credential);
  }

  return found;
}

/**
 * \brief Checks that a guard set holds every top level guard a sub transaction requires.
 *
 * \param[in] guards A pointer to the \ref cardano_guard_set_t of the top level transaction, or NULL
 *                   when it carries no guards.
 * \param[in] sub_transaction A pointer to the \ref cardano_sub_transaction_t whose required top level
 *                            guards are checked.
 * \param[out] error_message A pointer that receives a static string describing the failure when a
 *                           required guard is missing.
 *
 * \return \ref CARDANO_SUCCESS if every required guard is present or the sub transaction requires
 *         none, \ref CARDANO_ERROR_ELEMENT_NOT_FOUND if a required guard is missing, or an appropriate
 *         error code indicating the failure reason.
 */
static cardano_error_t
check_sub_transaction_required_guards(
  const cardano_guard_set_t* guards,
  cardano_sub_transaction_t* sub_transaction,
  const char**               error_message)
{
  cardano_sub_transaction_body_t* sub_body = cardano_sub_transaction_get_body(sub_transaction);
  cardano_sub_transaction_body_unref(&sub_body);

  cardano_required_guards_map_t* required_guards = cardano_sub_transaction_body_get_required_top_level_guards(sub_body);
  cardano_required_guards_map_unref(&required_guards);

  const size_t length = cardano_required_guards_map_get_length(required_guards);

  for (size_t i = 0U; i < length; ++i)
  {
    cardano_credential_t* credential = NULL;

    const cardano_error_t result = cardano_required_guards_map_get_key_at(required_guards, i, &credential);
    cardano_credential_unref(&credential);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    if (!has_guard(guards, credential))
    {
      *error_message = "A sub transaction requires a top level guard that the transaction does not carry. You must add it with `cardano_tx_builder_add_guard` before calling `build`.";

      return CARDANO_ERROR_ELEMENT_NOT_FOUND;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Checks that the transaction carries every top level guard its sub transactions require.
 *
 * A sub transaction can list the guards it requires from the transaction that carries it, and the
 * batch is only valid when each of them is among the guards of that transaction. Guards are never
 * added on behalf of the batcher, since a key hash guard is also a required signer. Transactions
 * without sub transactions always pass.
 *
 * \param[in] tx A pointer to the \ref cardano_transaction_t to check.
 * \param[out] error_message A pointer that receives a static string describing the failure when a
 *                           required guard is missing.
 *
 * \return \ref CARDANO_SUCCESS if no required guard is missing, \ref CARDANO_ERROR_ELEMENT_NOT_FOUND
 *         if the transaction lacks a guard required by one of its sub transactions, or an appropriate
 *         error code indicating the failure reason.
 */
static cardano_error_t
check_required_top_level_guards(cardano_transaction_t* tx, const char** error_message)
{
  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_guard_set_t* guards = cardano_transaction_body_get_guards(body);
  cardano_guard_set_unref(&guards);

  cardano_sub_transaction_set_t* sub_transactions = cardano_transaction_body_get_sub_transactions(body);
  cardano_sub_transaction_set_unref(&sub_transactions);

  const size_t length = cardano_sub_transaction_set_get_length(sub_transactions);

  for (size_t i = 0U; i < length; ++i)
  {
    cardano_sub_transaction_t* sub_transaction = NULL;

    cardano_error_t result = cardano_sub_transaction_set_get(sub_transactions, i, &sub_transaction);
    cardano_sub_transaction_unref(&sub_transaction);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    result = check_sub_transaction_required_guards(guards, sub_transaction, error_message);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Callback that checks whether a UTXO belongs to a transaction input.
 *
 * \param[in] item A pointer to the \ref cardano_utxo_t to evaluate.
 * \param[in] context A pointer to the \ref cardano_transaction_input_t to match against.
 *
 * \return true if the UTXO belongs to the transaction input, false otherwise.
 */
static bool
find_utxo(cardano_utxo_t* item, const void* context)
{
  const cardano_transaction_input_t* input      = (const cardano_transaction_input_t*)context;
  cardano_transaction_input_t*       utxo_input = cardano_utxo_get_input(item);

  bool found = cardano_transaction_input_equals(utxo_input, input);

  cardano_transaction_input_unref(&utxo_input);

  return found;
}

/**
 * \brief Adds to a list the UTXOs of another list whose input the list does not hold yet.
 *
 * \param[in,out] list A pointer to the \ref cardano_utxo_list_t that receives the UTXOs.
 * \param[in] utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs to add.
 *
 * \return \ref CARDANO_SUCCESS if the UTXOs were added, or an appropriate error code indicating the
 *         failure reason.
 */
static cardano_error_t
add_utxos_with_new_inputs(cardano_utxo_list_t* list, cardano_utxo_list_t* utxos)
{
  const size_t length = cardano_utxo_list_get_length(utxos);

  for (size_t i = 0U; i < length; ++i)
  {
    cardano_utxo_t* utxo = NULL;

    cardano_error_t result = cardano_utxo_list_get(utxos, i, &utxo);
    cardano_utxo_unref(&utxo);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }

    cardano_transaction_input_t* input = cardano_utxo_get_input(utxo);
    cardano_transaction_input_unref(&input);

    cardano_utxo_t* listed_utxo = cardano_utxo_list_find(list, find_utxo, input);
    cardano_utxo_unref(&listed_utxo);

    if (listed_utxo == NULL)
    {
      result = cardano_utxo_list_add(list, utxo);
    }

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return CARDANO_SUCCESS;
}

/**
 * \brief Checks whether the protocol version forbids a transaction to spend one of its reference inputs.
 *
 * The ledger rejects a transaction that spends and references the same UTXO only under protocol
 * versions 9 and 10. Earlier versions and the versions from 11 on allow the overlap.
 *
 * \param[in] params A pointer to the \ref cardano_protocol_parameters_t the transaction is built with.
 *
 * \return true if the major protocol version is 9 or 10, false otherwise.
 */
static bool
are_spent_reference_inputs_forbidden(cardano_protocol_parameters_t* params)
{
  cardano_protocol_version_t* version = cardano_protocol_parameters_get_protocol_version(params);
  cardano_protocol_version_unref(&version);

  const uint64_t major = cardano_protocol_version_get_major(version);

  return (major == 9U) || (major == 10U);
}

/**
 * \brief Checks whether a UTXO is one of the top level reference inputs of the transaction.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[in] utxo A pointer to the \ref cardano_utxo_t to look up.
 *
 * \return true if the input of the UTXO was added as a reference input, false otherwise.
 */
static bool
is_reference_input(const cardano_builder_state_t* state, cardano_utxo_t* utxo)
{
  cardano_transaction_input_t* input = cardano_utxo_get_input(utxo);
  cardano_transaction_input_unref(&input);

  cardano_utxo_t* reference_utxo = cardano_utxo_list_find(state->reference_inputs, find_utxo, input);
  cardano_utxo_unref(&reference_utxo);

  return reference_utxo != NULL;
}

/**
 * \brief Checks whether a UTXO list holds one of the top level reference inputs of the transaction.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[in] utxos A pointer to the \ref cardano_utxo_list_t to search.
 *
 * \return true if the list holds a UTXO that was added as a reference input, false otherwise.
 */
static bool
has_reference_input(const cardano_builder_state_t* state, const cardano_utxo_list_t* utxos)
{
  const size_t length = cardano_utxo_list_get_length(utxos);
  bool         found  = false;

  for (size_t i = 0U; (i < length) && !found; ++i)
  {
    cardano_utxo_t* utxo = NULL;

    const cardano_error_t result = cardano_utxo_list_get(utxos, i, &utxo);
    cardano_utxo_unref(&utxo);

    found = (result == CARDANO_SUCCESS) && is_reference_input(state, utxo);
  }

  return found;
}

/**
 * \brief Checks that no explicitly added input of the transaction is also one of its reference inputs.
 *
 * Under protocol versions 9 and 10 the ledger rejects a transaction that spends and references the
 * same UTXO, so a UTXO added both as an input and as a reference input makes the build fail. Only the
 * top level is checked, since sub transactions exist only from protocol version 12.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[out] error_message A pointer that receives a static string describing the failure when a
 *                           UTXO is both spent and referenced.
 *
 * \return \ref CARDANO_SUCCESS if the added inputs and the reference inputs are disjoint or the
 *         protocol version allows the overlap, or \ref CARDANO_ERROR_DUPLICATED_KEY if a UTXO is both
 *         spent and referenced under protocol versions 9 and 10.
 */
static cardano_error_t
check_disjoint_reference_inputs(cardano_builder_state_t* state, const char** error_message)
{
  if (!are_spent_reference_inputs_forbidden(state->params) || !has_reference_input(state, state->pre_selected_inputs))
  {
    return CARDANO_SUCCESS;
  }

  *error_message = "A UTXO can not be both spent and referenced by the same transaction under protocol versions 9 and 10.";

  return CARDANO_ERROR_DUPLICATED_KEY;
}

/**
 * \brief Creates the list of available UTXOs coin selection may spend at the top level.
 *
 * Under protocol versions 9 and 10 the ledger rejects a transaction that spends one of its reference
 * inputs, so the UTXOs added as reference inputs are left out of the available UTXOs. The order of the
 * remaining UTXOs is preserved and the list of the state is never modified.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[out] utxos On success, this will point to the selectable UTXOs, which is the list of available
 *                   UTXOs of the state itself when the protocol version allows the overlap or when no
 *                   available UTXO is a reference input. The caller is responsible for releasing it
 *                   with \ref cardano_utxo_list_unref.
 *
 * \return \ref CARDANO_SUCCESS if the list was created, or an appropriate error code indicating the
 *         failure reason.
 */
static cardano_error_t
exclude_reference_inputs(cardano_builder_state_t* state, cardano_utxo_list_t** utxos)
{
  if (!are_spent_reference_inputs_forbidden(state->params) || !has_reference_input(state, state->available_utxos))
  {
    cardano_utxo_list_ref(state->available_utxos);
    *utxos = state->available_utxos;

    return CARDANO_SUCCESS;
  }

  cardano_utxo_list_t* selectable_utxos = NULL;
  cardano_error_t      result           = cardano_utxo_list_new(&selectable_utxos);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  const size_t length = cardano_utxo_list_get_length(state->available_utxos);

  for (size_t i = 0U; i < length; ++i)
  {
    cardano_utxo_t* utxo = NULL;

    result = cardano_utxo_list_get(state->available_utxos, i, &utxo);
    cardano_utxo_unref(&utxo);

    if ((result == CARDANO_SUCCESS) && !is_reference_input(state, utxo))
    {
      result = cardano_utxo_list_add(selectable_utxos, utxo);
    }

    if (result != CARDANO_SUCCESS)
    {
      cardano_utxo_list_unref(&selectable_utxos);

      return result;
    }
  }

  *utxos = selectable_utxos;

  return CARDANO_SUCCESS;
}

/**
 * \brief Creates the list of available UTXOs the transaction is balanced with.
 *
 * The balancer takes the resolved UTXOs of the sub transactions from the available UTXOs, so the UTXOs
 * the sub transactions spend and reference are added to the ones available for input selection. The
 * batcher can also be a party of the batch, so a UTXO that is already available is not listed again.
 * Under protocol versions 9 and 10 the UTXOs added as top level reference inputs are left out of the
 * available UTXOs, since the ledger does not allow a transaction to spend them. The list of the state
 * is never modified.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[out] utxos On success, this will point to the list to balance the transaction with, which is
 *                   the list of available UTXOs of the state itself when the transaction carries no sub
 *                   transactions and no available UTXO has to be left out. The caller is responsible for
 *                   releasing it with \ref cardano_utxo_list_unref.
 *
 * \return \ref CARDANO_SUCCESS if the list was created, or an appropriate error code indicating the
 *         failure reason.
 */
static cardano_error_t
get_balancing_utxos(cardano_builder_state_t* state, cardano_utxo_list_t** utxos)
{
  cardano_utxo_list_t* selectable_utxos = NULL;

  cardano_error_t result = exclude_reference_inputs(state, &selectable_utxos);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  const size_t sub_transaction_utxo_count = cardano_utxo_list_get_length(state->sub_transaction_inputs) +
    cardano_utxo_list_get_length(state->sub_transaction_reference_inputs);

  if (sub_transaction_utxo_count == 0U)
  {
    *utxos = selectable_utxos;

    return CARDANO_SUCCESS;
  }

  cardano_utxo_list_t* balancing_utxos = cardano_utxo_list_clone(selectable_utxos);
  cardano_utxo_list_unref(&selectable_utxos);

  if (balancing_utxos == NULL)
  {
    return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
  }

  result = add_utxos_with_new_inputs(balancing_utxos, state->sub_transaction_inputs);

  if (result == CARDANO_SUCCESS)
  {
    result = add_utxos_with_new_inputs(balancing_utxos, state->sub_transaction_reference_inputs);
  }

  if (result != CARDANO_SUCCESS)
  {
    cardano_utxo_list_unref(&balancing_utxos);

    return result;
  }

  *utxos = balancing_utxos;

  return CARDANO_SUCCESS;
}

/**
 * \brief Adds to a list the resolved UTXO of an input the transaction spends, unless the list holds it.
 *
 * The UTXO is looked up among the available UTXOs and the resolved spend inputs of the sub
 * transactions, which hold every UTXO coin selection can add to the inputs of the transaction.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[in] input A pointer to the \ref cardano_transaction_input_t spent by the transaction.
 * \param[in,out] spent_utxos A pointer to the \ref cardano_utxo_list_t that receives the UTXO.
 *
 * \return \ref CARDANO_SUCCESS if the list holds the UTXO, \ref CARDANO_ERROR_ELEMENT_NOT_FOUND if
 *         the input is not resolved, or an appropriate error code indicating the failure reason.
 */
static cardano_error_t
add_spent_utxo(
  const cardano_builder_state_t*     state,
  const cardano_transaction_input_t* input,
  cardano_utxo_list_t*               spent_utxos)
{
  cardano_utxo_t* utxo = cardano_utxo_list_find(spent_utxos, find_utxo, input);

  if (utxo != NULL)
  {
    cardano_utxo_unref(&utxo);

    return CARDANO_SUCCESS;
  }

  utxo = cardano_utxo_list_find(state->available_utxos, find_utxo, input);

  if (utxo == NULL)
  {
    utxo = cardano_utxo_list_find(state->sub_transaction_inputs, find_utxo, input);
  }

  if (utxo == NULL)
  {
    return CARDANO_ERROR_ELEMENT_NOT_FOUND;
  }

  const cardano_error_t result = cardano_utxo_list_add(spent_utxos, utxo);
  cardano_utxo_unref(&utxo);

  return result;
}

/**
 * \brief Creates the list of resolved UTXOs a transaction spends.
 *
 * Those are the pre selected inputs, which a sub transaction spends even though the body of the
 * transaction held by its state does not list them, and the inputs of the body, which at the top
 * level also hold the inputs chosen by coin selection.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[in] tx A pointer to the \ref cardano_transaction_t whose inputs are resolved.
 * \param[out] spent_utxos On success, this will point to the resolved UTXOs. The caller is
 *                         responsible for releasing it with \ref cardano_utxo_list_unref.
 *
 * \return \ref CARDANO_SUCCESS if every input was resolved, \ref CARDANO_ERROR_ELEMENT_NOT_FOUND if
 *         an input is not resolved, or an appropriate error code indicating the failure reason.
 */
static cardano_error_t
get_spent_utxos(
  cardano_builder_state_t* state,
  cardano_transaction_t*   tx,
  cardano_utxo_list_t**    spent_utxos)
{
  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_transaction_input_set_t* inputs = cardano_transaction_body_get_inputs(body);
  cardano_transaction_input_set_unref(&inputs);

  cardano_utxo_list_t* utxos = cardano_utxo_list_clone(state->pre_selected_inputs);

  if (utxos == NULL)
  {
    return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
  }

  cardano_error_t result = CARDANO_SUCCESS;
  const size_t    length = cardano_transaction_input_set_get_length(inputs);

  for (size_t i = 0U; (i < length) && (result == CARDANO_SUCCESS); ++i)
  {
    cardano_transaction_input_t* input = NULL;

    result = cardano_transaction_input_set_get(inputs, i, &input);
    cardano_transaction_input_unref(&input);

    if (result == CARDANO_SUCCESS)
    {
      result = add_spent_utxo(state, input, utxos);
    }
  }

  if (result != CARDANO_SUCCESS)
  {
    cardano_utxo_list_unref(&utxos);

    return result;
  }

  *spent_utxos = utxos;

  return CARDANO_SUCCESS;
}

/**
 * \brief Adds to a set the payment script hash of every spent UTXO locked by a script.
 *
 * \param[in,out] script_hashes A pointer to the \ref cardano_blake2b_hash_set_t that receives the
 *                              script hashes. A hash the set already holds is not added again.
 * \param[in] spent_utxos A pointer to the \ref cardano_utxo_list_t with the spent UTXOs.
 *
 * \return \ref CARDANO_SUCCESS if the UTXOs were inspected, or an appropriate error code indicating
 *         the failure reason.
 */
static cardano_error_t
add_spent_script_hashes(cardano_blake2b_hash_set_t* script_hashes, cardano_utxo_list_t* spent_utxos)
{
  cardano_error_t result = CARDANO_SUCCESS;
  const size_t    length = cardano_utxo_list_get_length(spent_utxos);

  for (size_t i = 0U; (i < length) && (result == CARDANO_SUCCESS); ++i)
  {
    cardano_utxo_t* utxo = NULL;

    result = cardano_utxo_list_get(spent_utxos, i, &utxo);
    cardano_utxo_unref(&utxo);

    cardano_address_t* address = NULL;

    if (result == CARDANO_SUCCESS)
    {
      cardano_transaction_output_t* output = cardano_utxo_get_output(utxo);
      cardano_transaction_output_unref(&output);

      address = cardano_transaction_output_get_address(output);
      cardano_address_unref(&address);
    }

    if ((result == CARDANO_SUCCESS) && _cardano_has_payment_script(address))
    {
      cardano_blake2b_hash_t* script_hash = _cardano_get_payment_script_hash(address);

      result = (script_hash != NULL) ? CARDANO_SUCCESS : CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;

      if ((result == CARDANO_SUCCESS) && !_cardano_blake2b_hash_set_has(script_hashes, script_hash))
      {
        result = cardano_blake2b_hash_set_add(script_hashes, script_hash);
      }

      cardano_blake2b_hash_unref(&script_hash);
    }
  }

  return result;
}

/**
 * \brief Collects the hashes of the scripts a transaction needs.
 *
 * Those are the scripts of the spent UTXOs locked by a script, its mint, withdrawals, certificates, voters, proposal
 * guardrails and guards.
 *
 * \param[in] tx A pointer to the \ref cardano_transaction_t whose needed scripts are collected.
 * \param[in] spent_utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs the transaction spends.
 * \param[out] needed_scripts On success, this will point to the needed script hashes. The caller is responsible for
 *                            releasing them with \ref cardano_blake2b_hash_set_unref.
 *
 * \return \ref CARDANO_SUCCESS if the hashes were collected, or an appropriate error code indicating the failure
 *         reason.
 */
static cardano_error_t
get_needed_scripts(
  cardano_transaction_t*       tx,
  cardano_utxo_list_t*         spent_utxos,
  cardano_blake2b_hash_set_t** needed_scripts)
{
  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_blake2b_hash_set_t* script_hashes = NULL;

  cardano_error_t result = _cardano_get_script_hashes_needed(body, NULL, &script_hashes);

  if (result == CARDANO_SUCCESS)
  {
    result = add_spent_script_hashes(script_hashes, spent_utxos);
  }

  if (result != CARDANO_SUCCESS)
  {
    cardano_blake2b_hash_set_unref(&script_hashes);

    return result;
  }

  *needed_scripts = script_hashes;

  return CARDANO_SUCCESS;
}

/**
 * \brief Finds the Plutus languages of the scripts a transaction needs.
 *
 * Like the ledger, only the scripts the body needs count: the scripts of its spent inputs, mint,
 * withdrawals, certificates, voters, proposal guardrails and guards. Each one is looked up among the
 * scripts provided to the batch: the ones of the witness set of the transaction and of the witness
 * sets of its sub transactions, and the reference scripts of the reference inputs, the spent inputs
 * and the UTXOs the sub transactions spend or reference. A provided script that no field of the body
 * needs adds no language, and a needed script that is not provided adds none either, since its
 * language is unknown.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t tracking the transaction under
 *                  construction.
 * \param[in] tx A pointer to the \ref cardano_transaction_t whose needed scripts are inspected.
 * \param[out] has_plutus_v1 Set to true if a needed script is a PlutusV1 script.
 * \param[out] has_plutus_v2 Set to true if a needed script is a PlutusV2 script.
 * \param[out] has_plutus_v3 Set to true if a needed script is a PlutusV3 script.
 * \param[out] has_plutus_v4 Set to true if a needed script is a PlutusV4 script.
 *
 * \return \ref CARDANO_SUCCESS if the languages were found, or an appropriate error code indicating
 *         the failure reason.
 */
static cardano_error_t
get_plutus_languages_used(
  cardano_builder_state_t* state,
  cardano_transaction_t*   tx,
  bool*                    has_plutus_v1,
  bool*                    has_plutus_v2,
  bool*                    has_plutus_v3,
  bool*                    has_plutus_v4)
{
  cardano_utxo_list_t* spent_utxos = NULL;

  cardano_error_t result = get_spent_utxos(state, tx, &spent_utxos);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  cardano_blake2b_hash_set_t* needed_scripts = NULL;

  result = get_needed_scripts(tx, spent_utxos, &needed_scripts);

  if (result != CARDANO_SUCCESS)
  {
    cardano_utxo_list_unref(&spent_utxos);

    return result;
  }

  cardano_utxo_list_t* sub_transaction_utxos = cardano_utxo_list_concat(state->sub_transaction_inputs, state->sub_transaction_reference_inputs);

  if (sub_transaction_utxos == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
  }
  else
  {
    bool has_missing_scripts = false;

    result = _cardano_get_plutus_languages_used(
      tx,
      uses_created_output_scripts(state),
      needed_scripts,
      state->reference_inputs,
      spent_utxos,
      NULL,
      sub_transaction_utxos,
      has_plutus_v1,
      has_plutus_v2,
      has_plutus_v3,
      has_plutus_v4,
      &has_missing_scripts);
  }

  cardano_utxo_list_unref(&sub_transaction_utxos);
  cardano_blake2b_hash_set_unref(&needed_scripts);
  cardano_utxo_list_unref(&spent_utxos);

  return result;
}

/**
 * \brief Retrieves the cost models of the Plutus languages a transaction uses.
 *
 * The script data hash carries the language view of each Plutus language of the scripts the
 * transaction needs, so the cost model of every such language is copied from the protocol parameters.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t holding the protocol parameters and
 *                  the resolved UTXOs of the transaction.
 * \param[in] tx A pointer to the \ref cardano_transaction_t whose languages are retrieved.
 * \param[out] costmdls A pointer to an initialized \ref cardano_costmdls_t object where the cost models will be stored.
 *                      This parameter must not be NULL.
 *
 * \return \ref cardano_error_t indicating the result of the operation. Returns \ref CARDANO_SUCCESS if the cost models
 *         were successfully retrieved and stored, or an appropriate error code if an error occurs during retrieval.
 */
static cardano_error_t
get_cost_models(cardano_builder_state_t* state, cardano_transaction_t* tx, cardano_costmdls_t* costmdls)
{
  bool has_plutus_v1 = false;
  bool has_plutus_v2 = false;
  bool has_plutus_v3 = false;
  bool has_plutus_v4 = false;

  cardano_error_t result = get_plutus_languages_used(state, tx, &has_plutus_v1, &has_plutus_v2, &has_plutus_v3, &has_plutus_v4);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  cardano_costmdls_t* pparams_costmdls = cardano_protocol_parameters_get_cost_models(state->params);
  cardano_costmdls_unref(&pparams_costmdls);

  if (has_plutus_v1)
  {
    result = get_cost_model_for_version(pparams_costmdls, costmdls, CARDANO_PLUTUS_LANGUAGE_VERSION_V1);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  if (has_plutus_v2)
  {
    result = get_cost_model_for_version(pparams_costmdls, costmdls, CARDANO_PLUTUS_LANGUAGE_VERSION_V2);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  if (has_plutus_v3)
  {
    result = get_cost_model_for_version(pparams_costmdls, costmdls, CARDANO_PLUTUS_LANGUAGE_VERSION_V3);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  if (has_plutus_v4)
  {
    result = get_cost_model_for_version(pparams_costmdls, costmdls, CARDANO_PLUTUS_LANGUAGE_VERSION_V4);

    if (result != CARDANO_SUCCESS)
    {
      return result;
    }
  }

  return result;
}

/**
 * \brief Retrieves the name of the script purpose of a redeemer tag.
 *
 * \param[in] tag The redeemer tag.
 *
 * \return A static string naming the purpose.
 */
static const char*
get_purpose_name(const cardano_redeemer_tag_t tag)
{
  const char* name = "unknown";

  switch (tag)
  {
    case CARDANO_REDEEMER_TAG_SPEND:
    {
      name = "spending";
      break;
    }
    case CARDANO_REDEEMER_TAG_MINT:
    {
      name = "minting";
      break;
    }
    case CARDANO_REDEEMER_TAG_CERTIFYING:
    {
      name = "certifying";
      break;
    }
    case CARDANO_REDEEMER_TAG_REWARD:
    {
      name = "rewarding";
      break;
    }
    case CARDANO_REDEEMER_TAG_VOTING:
    {
      name = "voting";
      break;
    }
    case CARDANO_REDEEMER_TAG_PROPOSING:
    {
      name = "proposing";
      break;
    }
    case CARDANO_REDEEMER_TAG_GUARDING:
    {
      name = "guarding";
      break;
    }
    default:
    {
      break;
    }
  }

  return name;
}

/**
 * \brief Sets the last error of a transaction to describe a script purpose that has no redeemer.
 *
 * \param[in,out] tx A pointer to the \ref cardano_transaction_t that receives the error message.
 * \param[in] tag The redeemer tag of the purpose.
 * \param[in] index The redeemer index of the purpose.
 * \param[in] script_hash A pointer to the \ref cardano_blake2b_hash_t of the Plutus script of the purpose.
 */
static void
set_missing_redeemer_error(
  cardano_transaction_t*        tx,
  const cardano_redeemer_tag_t  tag,
  const uint64_t                index,
  const cardano_blake2b_hash_t* script_hash)
{
  char hash_hex[65] = { 0 };

  CARDANO_UNUSED(cardano_blake2b_hash_to_hex(script_hash, hash_hex, sizeof(hash_hex)));

  char buffer[256] = { 0 };

  const int32_t written = snprintf(
    buffer,
    sizeof(buffer),
    "The %s purpose at index %" PRIu64 " needs a redeemer for the Plutus script %s, but the transaction carries none.",
    get_purpose_name(tag),
    index,
    hash_hex);

  assert(written > 0);
  CARDANO_UNUSED(written);

  cardano_transaction_set_last_error(tx, buffer);
}

/**
 * \brief Sets the last error of a transaction to describe a script purpose of one of its sub transactions that has
 * no redeemer.
 *
 * \param[in,out] tx A pointer to the \ref cardano_transaction_t that receives the error message.
 * \param[in] sub_transaction A pointer to the \ref cardano_sub_transaction_t the purpose belongs to.
 * \param[in] batch_index The zero based index of the sub transaction in the batch.
 * \param[in] tag The redeemer tag of the purpose.
 * \param[in] index The redeemer index of the purpose.
 * \param[in] script_hash A pointer to the \ref cardano_blake2b_hash_t of the Plutus script of the purpose.
 */
static void
set_sub_transaction_missing_redeemer_error(
  cardano_transaction_t*        tx,
  cardano_sub_transaction_t*    sub_transaction,
  const size_t                  batch_index,
  const cardano_redeemer_tag_t  tag,
  const uint64_t                index,
  const cardano_blake2b_hash_t* script_hash)
{
  char hash_hex[65] = { 0 };
  char id_hex[65]   = { 0 };

  CARDANO_UNUSED(cardano_blake2b_hash_to_hex(script_hash, hash_hex, sizeof(hash_hex)));

  cardano_blake2b_hash_t* id = cardano_sub_transaction_get_id(sub_transaction);

  CARDANO_UNUSED(cardano_blake2b_hash_to_hex(id, id_hex, sizeof(id_hex)));
  cardano_blake2b_hash_unref(&id);

  char buffer[384] = { 0 };

  const int32_t written = snprintf(
    buffer,
    sizeof(buffer),
    "The %s purpose at index %" PRIu64 " of the sub transaction %s (index %" PRIu64 " in the batch) needs a redeemer for the Plutus script %s, but the sub transaction carries none.",
    get_purpose_name(tag),
    index,
    id_hex,
    (uint64_t)batch_index,
    hash_hex);

  assert(written > 0);
  CARDANO_UNUSED(written);

  cardano_transaction_set_last_error(tx, buffer);
}

/**
 * \brief Checks that every script purpose of a sub transaction whose script is a Plutus script has a redeemer.
 *
 * The purposes come from the body of the sub transaction, its spend indices are positions in its own sorted inputs
 * and its redeemers are the ones of its own witness set, while the scripts are looked up among the ones provided to
 * the whole batch.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t holding the resolved UTXOs of the batch.
 * \param[in,out] tx A pointer to the \ref cardano_transaction_t carrying the sub transaction. Its last error describes
 *                   the purpose that has no redeemer.
 * \param[in] spent_utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs the transaction spends.
 * \param[in] sub_transaction_utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs the sub transactions spend
 *                                  or reference.
 * \param[in] sub_transaction A pointer to the \ref cardano_sub_transaction_t to check.
 * \param[in] batch_index The zero based index of the sub transaction in the batch.
 *
 * \return \ref CARDANO_SUCCESS if every such purpose has a redeemer, \ref CARDANO_ERROR_MISSING_REDEEMER if one of
 *         them has none, or an appropriate error code indicating the failure reason.
 */
static cardano_error_t
check_sub_transaction_redeemers(
  cardano_builder_state_t*   state,
  cardano_transaction_t*     tx,
  cardano_utxo_list_t*       spent_utxos,
  cardano_utxo_list_t*       sub_transaction_utxos,
  cardano_sub_transaction_t* sub_transaction,
  const size_t               batch_index)
{
  cardano_blake2b_hash_set_t* needed_scripts = NULL;
  cardano_blake2b_hash_set_t* plutus_scripts = NULL;
  cardano_blake2b_hash_t*     script_hash    = NULL;
  cardano_redeemer_tag_t      tag            = CARDANO_REDEEMER_TAG_SPEND;
  uint64_t                    index          = 0U;

  cardano_sub_transaction_body_t* sub_body = cardano_sub_transaction_get_body(sub_transaction);
  cardano_sub_transaction_body_unref(&sub_body);

  cardano_error_t result = _cardano_get_sub_transaction_script_hashes_needed(sub_body, state->sub_transaction_inputs, &needed_scripts);

  if (result == CARDANO_SUCCESS)
  {
    result = _cardano_get_plutus_scripts_provided(tx, uses_created_output_scripts(state), needed_scripts, state->reference_inputs, spent_utxos, NULL, sub_transaction_utxos, &plutus_scripts);
  }

  if (result == CARDANO_SUCCESS)
  {
    cardano_witness_set_t* witness_set = cardano_sub_transaction_get_witness_set(sub_transaction);
    cardano_witness_set_unref(&witness_set);

    cardano_redeemer_list_t* redeemers = cardano_witness_set_get_redeemers(witness_set);
    cardano_redeemer_list_unref(&redeemers);

    result = _cardano_find_sub_transaction_missing_redeemer(sub_body, state->sub_transaction_inputs, plutus_scripts, redeemers, &tag, &index, &script_hash);
  }

  if (script_hash != NULL)
  {
    set_sub_transaction_missing_redeemer_error(tx, sub_transaction, batch_index, tag, index, script_hash);

    result = CARDANO_ERROR_MISSING_REDEEMER;
  }

  cardano_blake2b_hash_unref(&script_hash);
  cardano_blake2b_hash_set_unref(&plutus_scripts);
  cardano_blake2b_hash_set_unref(&needed_scripts);

  return result;
}

/**
 * \brief Checks the redeemers of every sub transaction of a transaction.
 *
 * \param[in] state A pointer to the \ref cardano_builder_state_t holding the resolved UTXOs of the batch.
 * \param[in,out] tx A pointer to the \ref cardano_transaction_t whose sub transactions are checked. Its last error
 *                   describes the purpose that has no redeemer.
 * \param[in] spent_utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs the transaction spends.
 * \param[in] sub_transaction_utxos A pointer to the \ref cardano_utxo_list_t with the UTXOs the sub transactions spend
 *                                  or reference.
 *
 * \return \ref CARDANO_SUCCESS if every Plutus script purpose of every sub transaction has a redeemer,
 *         \ref CARDANO_ERROR_MISSING_REDEEMER if one of them has none, or an appropriate error code indicating the
 *         failure reason.
 */
static cardano_error_t
check_sub_transactions_redeemers(
  cardano_builder_state_t* state,
  cardano_transaction_t*   tx,
  cardano_utxo_list_t*     spent_utxos,
  cardano_utxo_list_t*     sub_transaction_utxos)
{
  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_sub_transaction_set_t* sub_transactions = cardano_transaction_body_get_sub_transactions(body);
  cardano_sub_transaction_set_unref(&sub_transactions);

  cardano_error_t result = CARDANO_SUCCESS;
  const size_t    length = cardano_sub_transaction_set_get_length(sub_transactions);

  for (size_t i = 0U; (i < length) && (result == CARDANO_SUCCESS); ++i)
  {
    cardano_sub_transaction_t* sub_transaction = NULL;

    result = cardano_sub_transaction_set_get(sub_transactions, i, &sub_transaction);
    cardano_sub_transaction_unref(&sub_transaction);

    if (result == CARDANO_SUCCESS)
    {
      result = check_sub_transaction_redeemers(state, tx, spent_utxos, sub_transaction_utxos, sub_transaction, i);
    }
  }

  return result;
}

/* IMPLEMENTATION ************************************************************/

cardano_error_t
cardano_builder_set_dummy_script_data_hash(cardano_transaction_t* tx)
{
  if (!cardano_transaction_has_script_data(tx))
  {
    return CARDANO_SUCCESS;
  }

  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  static byte_t           dummy_hash[32] = { 0 };
  cardano_blake2b_hash_t* hash           = NULL;

  cardano_error_t new_hash_result = cardano_blake2b_hash_from_bytes(dummy_hash, sizeof(dummy_hash), &hash);

  if (new_hash_result != CARDANO_SUCCESS)
  {
    return new_hash_result;
  }

  new_hash_result = cardano_transaction_body_set_script_data_hash(body, hash);
  cardano_blake2b_hash_unref(&hash);

  if (new_hash_result != CARDANO_SUCCESS)
  {
    return new_hash_result;
  }

  return CARDANO_SUCCESS;
}

cardano_error_t
cardano_builder_update_script_data_hash(cardano_builder_state_t* state, cardano_transaction_t* tx)
{
  if (!cardano_transaction_has_script_data(tx))
  {
    return CARDANO_SUCCESS;
  }

  cardano_costmdls_t* costmdls = NULL;

  cardano_error_t result = cardano_costmdls_new(&costmdls);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  result = get_cost_models(state, tx, costmdls);

  if (result != CARDANO_SUCCESS)
  {
    cardano_costmdls_unref(&costmdls);
    return result;
  }

  cardano_blake2b_hash_t* hash = NULL;

  cardano_witness_set_t* witness_set = cardano_transaction_get_witness_set(tx);
  cardano_witness_set_unref(&witness_set);

  cardano_redeemer_list_t* redeemers = cardano_witness_set_get_redeemers(witness_set);
  cardano_redeemer_list_unref(&redeemers);

  cardano_plutus_data_set_t* datums = cardano_witness_set_get_plutus_data(witness_set);
  cardano_plutus_data_set_unref(&datums);

  result = cardano_compute_script_data_hash(costmdls, redeemers, datums, &hash);
  cardano_costmdls_unref(&costmdls);

  if (result != CARDANO_SUCCESS)
  {
    cardano_blake2b_hash_unref(&hash);

    return result;
  }

  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  result = cardano_transaction_body_set_script_data_hash(body, hash);
  cardano_blake2b_hash_unref(&hash);

  return result;
}

cardano_error_t
cardano_builder_check_redeemers(
  cardano_builder_state_t*         state,
  cardano_transaction_t*           tx,
  cardano_transaction_input_set_t* inputs,
  const char**                     error_message)
{
  cardano_utxo_list_t*        spent_utxos           = NULL;
  cardano_blake2b_hash_set_t* needed_scripts        = NULL;
  cardano_utxo_list_t*        sub_transaction_utxos = NULL;
  cardano_blake2b_hash_set_t* plutus_scripts        = NULL;
  cardano_blake2b_hash_t*     script_hash           = NULL;
  cardano_redeemer_tag_t      tag                   = CARDANO_REDEEMER_TAG_SPEND;
  uint64_t                    index                 = 0U;

  cardano_error_t result = get_spent_utxos(state, tx, &spent_utxos);

  if (result == CARDANO_SUCCESS)
  {
    result = get_needed_scripts(tx, spent_utxos, &needed_scripts);
  }

  if (result == CARDANO_SUCCESS)
  {
    sub_transaction_utxos = cardano_utxo_list_concat(state->sub_transaction_inputs, state->sub_transaction_reference_inputs);
    result                = (sub_transaction_utxos != NULL) ? CARDANO_SUCCESS : CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
  }

  if (result == CARDANO_SUCCESS)
  {
    result = _cardano_get_plutus_scripts_provided(tx, uses_created_output_scripts(state), needed_scripts, state->reference_inputs, spent_utxos, NULL, sub_transaction_utxos, &plutus_scripts);
  }

  if (result == CARDANO_SUCCESS)
  {
    cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
    cardano_transaction_body_unref(&body);

    cardano_witness_set_t* witness_set = cardano_transaction_get_witness_set(tx);
    cardano_witness_set_unref(&witness_set);

    cardano_redeemer_list_t* redeemers = cardano_witness_set_get_redeemers(witness_set);
    cardano_redeemer_list_unref(&redeemers);

    result = _cardano_find_missing_redeemer(body, inputs, spent_utxos, plutus_scripts, redeemers, &tag, &index, &script_hash);
  }

  if (script_hash != NULL)
  {
    set_missing_redeemer_error(tx, tag, index, script_hash);

    result = CARDANO_ERROR_MISSING_REDEEMER;
  }

  if (result == CARDANO_SUCCESS)
  {
    result = check_sub_transactions_redeemers(state, tx, spent_utxos, sub_transaction_utxos);
  }

  if (result == CARDANO_ERROR_MISSING_REDEEMER)
  {
    *error_message = cardano_transaction_get_last_error(tx);
  }

  if ((result != CARDANO_SUCCESS) && (result != CARDANO_ERROR_MISSING_REDEEMER))
  {
    *error_message = "Failed to check the redeemers of the Plutus scripts the transaction needs.";
  }

  cardano_blake2b_hash_unref(&script_hash);
  cardano_blake2b_hash_set_unref(&plutus_scripts);
  cardano_utxo_list_unref(&sub_transaction_utxos);
  cardano_blake2b_hash_set_unref(&needed_scripts);
  cardano_utxo_list_unref(&spent_utxos);

  return result;
}

cardano_error_t
cardano_builder_build(
  cardano_builder_state_t* state,
  cardano_transaction_t**  transaction,
  const char**             error_message)
{
  if (state->change_address == NULL)
  {
    *error_message = "You must set a change address before calling `build`.";

    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  if (state->available_utxos == NULL)
  {
    *error_message = "You must set the available UTXOs for input selection before calling `build`.";

    return CARDANO_ERROR_POINTER_IS_NULL;
  }

  cardano_error_t result = check_required_top_level_guards(state->transaction, error_message);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  bool is_collateral_required = false;

  result = _cardano_is_collateral_required(state->transaction, &is_collateral_required);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  if (is_collateral_required)
  {
    if (state->collateral_address == NULL)
    {
      *error_message = "This transaction interacts with plutus validators. You must set a collateral change address before calling `build`.";

      return CARDANO_ERROR_POINTER_IS_NULL;
    }

    if (state->collateral_utxos == NULL)
    {
      *error_message = "This transaction interacts with plutus validators. You must set the collateral UTXOs before calling `build`.";

      return CARDANO_ERROR_POINTER_IS_NULL;
    }

    if (cardano_utxo_list_get_length(state->collateral_utxos) == 0U)
    {
      *error_message = "This transaction interacts with plutus validators. You must set at least one collateral UTXO before calling `build`.";

      return CARDANO_ERROR_BALANCE_INSUFFICIENT;
    }
  }

  result = check_disjoint_reference_inputs(state, error_message);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  cardano_transaction_t* tx = state->transaction;

  result = cardano_builder_set_dummy_script_data_hash(tx);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  cardano_utxo_list_t* balancing_utxos = NULL;

  result = get_balancing_utxos(state, &balancing_utxos);

  if (result != CARDANO_SUCCESS)
  {
    *error_message = "Failed to gather the UTXOs the transaction is balanced with.";

    return result;
  }

  result = cardano_balance_transaction_with_pool_state(
    tx,
    state->additional_signature_count,
    state->params,
    state->reference_inputs,
    state->pre_selected_inputs,
    state->input_to_redeemer_map,
    balancing_utxos,
    state->coin_selector,
    state->change_address,
    state->collateral_utxos,
    state->collateral_address,
    state->tx_evaluator,
    state->deferred_redeemers,
    state->pool_state,
    state->pool_state_size);

  cardano_utxo_list_unref(&balancing_utxos);

  if (result != CARDANO_SUCCESS)
  {
    *error_message = cardano_transaction_get_last_error(tx);

    return result;
  }

  cardano_transaction_body_t* body = cardano_transaction_get_body(tx);
  cardano_transaction_body_unref(&body);

  cardano_transaction_input_set_t* inputs = cardano_transaction_body_get_inputs(body);
  cardano_transaction_input_set_unref(&inputs);

  result = cardano_builder_check_redeemers(state, tx, inputs, error_message);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  result = cardano_builder_update_script_data_hash(state, tx);

  if (result != CARDANO_SUCCESS)
  {
    return result;
  }

  cardano_transaction_ref(tx);
  *transaction = tx;

  return CARDANO_SUCCESS;
}