packages feed

cometa-0.2.0.0: cbits/cometa_transaction_builder.c

/**
 * \file cometa_transaction_builder.c
 *
 * Copyright 2026 Biglup Labs
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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
 *
 *     https://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 "cometa_transaction_builder.h"
#include "cometa_coin_selection.h"
#include "cometa_evaluation.h"
#include "cometa_parameters.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>

/* TYPES *********************************************************************/

/* Deferred contexts borrow the grouped runtime. Storage is allocated before
 * registration and freed only after builder destruction; native lists neither
 * retain nor release user_context. Each reply transfers a fresh payload. */
typedef struct
{
    cometa_runtime_t* runtime;
    uint64_t          index;
    bool              deferred_mint;
    bool              deferred_vote;
} deferred_context_t;

/* STATIC FUNCTIONS **********************************************************/

/** \brief Reject trailing bytes in every embedded native object. */
static cardano_error_t
complete(cardano_cbor_reader_t* reader)
{
  size_t          remaining = 0U;
  cardano_error_t result    = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);
  return result == CARDANO_SUCCESS && remaining != 0U ? CARDANO_ERROR_DECODING : result;
}

/** \brief Read one complete definite array with the expected arity. */
static cardano_error_t
array(cardano_cbor_reader_t* reader, int64_t expected)
{
  int64_t         count  = 0;
  cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);
  return result == CARDANO_SUCCESS && count != expected ? CARDANO_ERROR_DECODING : result;
}

/** \brief Decode a byte-string-wrapped native object; empty data means absence
 * only for explicitly optional datum arguments. Each returned object is owned. */
#define READ_OBJECT(NAME, TYPE, FROM)                                                                   \
  static cardano_error_t NAME(cardano_cbor_reader_t* reader, TYPE** output)                             \
  {                                                                                                     \
    cardano_buffer_t*      bytes  = NULL;                                                               \
    cardano_cbor_reader_t* nested = NULL;                                                               \
    cardano_error_t        result = cardano_cbor_reader_read_bytestring(reader, &bytes);                \
    *output                       = NULL;                                                               \
    if (result == CARDANO_SUCCESS && cardano_buffer_get_size(bytes) != 0U)                              \
    {                                                                                                   \
      nested = cardano_cbor_reader_new(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes)); \
      result = nested == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : FROM(nested, output);          \
      if (result == CARDANO_SUCCESS)                                                                    \
        result = complete(nested);                                                                      \
    }                                                                                                   \
    cardano_cbor_reader_unref(&nested);                                                                 \
    cardano_buffer_unref(&bytes);                                                                       \
    return result;                                                                                      \
  }

/**
 * \brief Decode the array framing used by Haskell-owned pool values.
 * \param reader Borrowed reader positioned at the parameter array.
 * \param output Receives an owned reference, including on trailing-framing failure.
 * \return Decoding status.
 */
static cardano_error_t
pool_parameters_from_array(cardano_cbor_reader_t* reader, cardano_pool_params_t** output)
{
  int64_t         count  = 0;
  cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);
  if (result != CARDANO_SUCCESS)
  {
    return result;
  }
  if (count != 9 && count != 10)
  {
    return CARDANO_ERROR_DECODING;
  }
  result = cardano_pool_params_from_cbor(reader, output);
  return result == CARDANO_SUCCESS ? cardano_cbor_reader_read_end_array(reader) : result;
}

READ_OBJECT(read_pool_parameters, cardano_pool_params_t, pool_parameters_from_array)
READ_OBJECT(read_balance_input, cardano_transaction_input_t, cardano_transaction_input_from_cbor)
READ_OBJECT(read_balance_transaction, cardano_transaction_t, cardano_transaction_from_cbor)
READ_OBJECT(read_output, cardano_transaction_output_t, cardano_transaction_output_from_cbor)
READ_OBJECT(read_utxo, cardano_utxo_t, cardano_utxo_from_cbor)
READ_OBJECT(read_script, cardano_script_t, cardano_script_from_cbor)
READ_OBJECT(read_data, cardano_plutus_data_t, cardano_plutus_data_from_cbor)
READ_OBJECT(read_certificate, cardano_certificate_t, cardano_certificate_from_cbor)
READ_OBJECT(read_metadata, cardano_metadatum_t, cardano_metadatum_from_cbor)
READ_OBJECT(read_credential, cardano_credential_t, cardano_credential_from_cbor)
READ_OBJECT(read_interval, cardano_account_balance_interval_t, cardano_account_balance_interval_from_cbor)
READ_OBJECT(read_proposal, cardano_proposal_procedure_t, cardano_proposal_procedure_from_cbor)
READ_OBJECT(read_voter, cardano_voter_t, cardano_voter_from_cbor)
READ_OBJECT(read_action_id, cardano_governance_action_id_t, cardano_governance_action_id_from_cbor)
READ_OBJECT(read_procedure, cardano_voting_procedure_t, cardano_voting_procedure_from_cbor)
READ_OBJECT(read_sub, cardano_sub_transaction_t, cardano_sub_transaction_from_cbor)
#undef READ_OBJECT

/** \brief Address factories copy their byte-string input before buffer release. */
static cardano_error_t
read_address(cardano_cbor_reader_t* reader, cardano_address_t** output)
{
  cardano_buffer_t* bytes  = NULL;
  cardano_error_t   result = cardano_cbor_reader_read_bytestring(reader, &bytes);
  if (result == CARDANO_SUCCESS && cardano_buffer_get_size(bytes) != 0U)
  {
    result = cardano_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), output);
  }
  cardano_buffer_unref(&bytes);
  return result;
}

/** \brief Materialize a list; list insertion retains each locally released item. */
static cardano_error_t
read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)
{
  int64_t         count  = 0;
  cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);
  if (result == CARDANO_SUCCESS && count < 0)
  {
    result = CARDANO_ERROR_DECODING;
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_utxo_list_new(output);
  }
  for (int64_t i = 0; result == CARDANO_SUCCESS && i < count; ++i)
  {
    cardano_utxo_t* item = NULL;
    result               = cardano_utxo_from_cbor(reader, &item);
    if (result == CARDANO_SUCCESS)
    {
      result = cardano_utxo_list_add(*output, item);
    }
    cardano_utxo_unref(&item);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_end_array(reader);
  }
  return result;
}

/** \brief Copy a balanced draft into the protected callback and transfer its argument. */
static cardano_error_t
deferred_callback(void* opaque, cardano_transaction_t* transaction, cardano_utxo_list_t* inputs, cardano_plutus_data_t** output)
{
  deferred_context_t*    context = (deferred_context_t*)opaque;
  cardano_cbor_writer_t* writer  = cardano_cbor_writer_new();
  cardano_cbor_reader_t* reader  = NULL;
  cardano_buffer_t*      request = NULL;
  cardano_buffer_t*      reply   = NULL;
  cardano_error_t        result  = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
  *output                        = NULL;
  if (writer == NULL)
  {
    goto cleanup;
  }
  result = cardano_cbor_writer_write_start_array(writer, 3);
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_writer_write_uint(writer, context->index);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_transaction_to_cbor(transaction, writer);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_writer_write_start_array(writer, (int64_t)cardano_utxo_list_get_length(inputs));
  }
  for (size_t i = 0; result == CARDANO_SUCCESS && i < cardano_utxo_list_get_length(inputs); ++i)
  {
    cardano_utxo_t* input = NULL;
    result                = cardano_utxo_list_get(inputs, i, &input);
    if (result == CARDANO_SUCCESS)
    {
      result = cardano_utxo_to_cbor(input, writer);
    }
    cardano_utxo_unref(&input);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_writer_encode_in_buffer(writer, &request);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = (cardano_error_t)cometa_runtime_dispatch(context->runtime, 110, cardano_buffer_get_data(request), cardano_buffer_get_size(request), &reply, NULL, 0);
  }
  if (result == CARDANO_SUCCESS && reply == NULL)
  {
    result = CARDANO_ERROR_POINTER_IS_NULL;
  }
  if (result == CARDANO_SUCCESS)
  {
    reader = cardano_cbor_reader_new(cardano_buffer_get_data(reply), cardano_buffer_get_size(reply));
    result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_plutus_data_from_cbor(reader, output);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = complete(reader);
  }
cleanup:
  if (result != CARDANO_SUCCESS)
  {
    cardano_plutus_data_unref(output);
  }
  cardano_cbor_reader_unref(&reader);
  cardano_cbor_writer_unref(&writer);
  cardano_buffer_unref(&request);
  cardano_buffer_unref(&reply);
  return result;
}

/** \brief Apply one instruction, releasing local references after builder retention. */
static cardano_error_t
instruction(cardano_tx_builder_t* builder, cardano_cbor_reader_t* reader, cardano_utxo_list_t* resolved, deferred_context_t* contexts, size_t position)
{
  deferred_context_t*                 context   = &contexts[position];
  static const int64_t                arities[] = { 2, 4, 2, 2, 5, 3, 2, 3, 4, 2, 2, 2, 4, 5, 3, 4, 3, 0, 3, 3, 3, 2, 3, 5, 5, 3, 0, 2, 3 };
  int64_t                             count     = 0;
  uint64_t                            tag = 0U, number = 0U;
  int64_t                             signed_number = 0;
  cardano_transaction_output_t*       output        = NULL;
  cardano_utxo_t*                     utxo          = NULL;
  cardano_script_t*                   script        = NULL;
  cardano_plutus_data_t*              redeemer      = NULL;
  cardano_plutus_data_t*              datum         = NULL;
  cardano_certificate_t*              certificate   = NULL;
  cardano_metadatum_t*                metadata      = NULL;
  cardano_blake2b_hash_t*             hash          = NULL;
  cardano_asset_name_t*               asset_name    = NULL;
  cardano_reward_address_t*           reward        = NULL;
  cardano_credential_t*               credential    = NULL;
  cardano_account_balance_interval_t* interval      = NULL;
  cardano_proposal_procedure_t*       proposal      = NULL;
  cardano_voter_t*                    voter         = NULL;
  cardano_governance_action_id_t*     action_id     = NULL;
  cardano_voting_procedure_t*         procedure     = NULL;
  cardano_sub_transaction_t*          sub           = NULL;
  cardano_utxo_list_t*                sub_resolved  = NULL;
  cardano_buffer_t*                   bytes         = NULL;
  cardano_error_t                     result        = cardano_cbor_reader_read_start_array(reader, &count);
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_uint(reader, &tag);
  }
  if (result == CARDANO_SUCCESS && (tag >= sizeof(arities) / sizeof(arities[0]) || count != arities[tag]))
  {
    result = CARDANO_ERROR_DECODING;
  }
  if (result != CARDANO_SUCCESS)
  {
    return result;
  }
#define TRY(CALL)                  \
  do                               \
  {                                \
    result = (CALL);               \
    if (result != CARDANO_SUCCESS) \
    {                              \
      goto cleanup;                \
    }                              \
  }                                \
  while (0)
  switch (tag)
  {
    case 0:
      TRY(read_output(reader, &output));
      cardano_tx_builder_add_output(builder, output);
      break;
    case 12:
    case 1:
      TRY(read_utxo(reader, &utxo));
      if (tag == 12)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
      }
      else
      {
        TRY(read_data(reader, &redeemer));
      }
      TRY(read_data(reader, &datum));
      TRY(cardano_utxo_list_add(resolved, utxo));
      if (tag == 12)
      {
        cardano_tx_builder_add_input_with_deferred_redeemer(builder, utxo, deferred_callback, context, datum);
      }
      else
      {
        cardano_tx_builder_add_input(builder, utxo, redeemer, datum);
      }
      break;
    case 2:
      TRY(read_utxo(reader, &utxo));
      TRY(cardano_utxo_list_add(resolved, utxo));
      cardano_tx_builder_add_reference_input(builder, utxo);
      break;
    case 3:
      TRY(read_script(reader, &script));
      cardano_tx_builder_add_script(builder, script);
      break;
    case 13:
    case 4:
      TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));
      TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));
      cardano_buffer_unref(&bytes);
      TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));
      TRY(cardano_asset_name_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &asset_name));
      TRY(cardano_cbor_reader_read_int(reader, &signed_number));
      if (tag == 13)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
        bool registered = false;
        for (size_t i = 0; i < position; ++i)
        {
          if (contexts[i].deferred_mint && contexts[i].index == context->index)
          {
            registered = true;
          }
        }
        context->deferred_mint = true;
        if (registered)
        {
          cardano_tx_builder_mint_token(builder, hash, asset_name, signed_number, NULL);
        }
        else
        {
          cardano_tx_builder_mint_token_with_deferred_redeemer(builder, hash, asset_name, signed_number, deferred_callback, context);
        }
      }
      else
      {
        TRY(read_data(reader, &redeemer));
        cardano_tx_builder_mint_token(builder, hash, asset_name, signed_number, redeemer);
      }
      break;
    case 5:
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      TRY(read_metadata(reader, &metadata));
      cardano_tx_builder_set_metadata(builder, number, metadata);
      break;
    case 6:
      TRY(read_data(reader, &datum));
      cardano_tx_builder_add_datum(builder, datum);
      break;
    case 14:
    case 7:
      TRY(read_certificate(reader, &certificate));
      if (tag == 14)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
        cardano_tx_builder_add_certificate_with_deferred_redeemer(builder, certificate, deferred_callback, context);
      }
      else
      {
        TRY(read_data(reader, &redeemer));
        cardano_tx_builder_add_certificate(builder, certificate, redeemer);
      }
      break;
    case 15:
    case 8:
      TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));
      TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      if (number > INT64_MAX)
      {
        result = CARDANO_ERROR_INTEGER_OVERFLOW;
        goto cleanup;
      }
      if (tag == 15)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
        cardano_tx_builder_withdraw_rewards_with_deferred_redeemer(builder, reward, (int64_t)number, deferred_callback, context);
      }
      else
      {
        TRY(read_data(reader, &redeemer));
        cardano_tx_builder_withdraw_rewards(builder, reward, (int64_t)number, redeemer);
      }
      break;
    case 9:
      TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));
      TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));
      cardano_tx_builder_add_signer(builder, hash);
      break;
    case 10:
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      cardano_tx_builder_set_invalid_before(builder, number);
      break;
    case 11:
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      cardano_tx_builder_set_invalid_after(builder, number);
      break;
    case 16:
      TRY(read_credential(reader, &credential));
      TRY(read_data(reader, &redeemer));
      if (redeemer == NULL)
      {
        cardano_tx_builder_add_guard(builder, credential);
      }
      else
      {
        cardano_tx_builder_add_guard_with_redeemer(builder, credential, redeemer);
      }
      break;
    case 18:
    case 19:
    case 20:
      TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));
      TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));
      if (tag == 18)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &number));
        cardano_tx_builder_add_direct_deposit(builder, reward, number);
      }
      else
      {
        TRY(read_interval(reader, &interval));
        if (tag == 19)
        {
          cardano_tx_builder_add_account_balance_interval(builder, reward, interval);
        }
        else
        {
          cardano_tx_builder_add_starting_account_balance_interval(builder, reward, interval);
        }
      }
      break;
    case 21:
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      cardano_tx_builder_set_donation(builder, number);
      break;
    case 22:
    case 28:
      TRY(read_proposal(reader, &proposal));
      if (tag == 28U)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
        cardano_tx_builder_add_proposal_with_deferred_redeemer(builder, proposal, deferred_callback, context);
      }
      else
      {
        TRY(read_data(reader, &redeemer));
        cardano_tx_builder_add_proposal(builder, proposal, redeemer);
      }
      break;
    case 23:
    case 24:
      TRY(read_voter(reader, &voter));
      TRY(read_action_id(reader, &action_id));
      TRY(read_procedure(reader, &procedure));
      if (tag == 24)
      {
        TRY(cardano_cbor_reader_read_uint(reader, &context->index));
        bool registered = false;
        for (size_t i = 0; i < position; ++i)
        {
          if (contexts[i].deferred_vote && contexts[i].index == context->index)
          {
            registered = true;
          }
        }
        context->deferred_vote = true;
        if (registered)
        {
          cardano_tx_builder_vote(builder, voter, action_id, procedure, NULL);
        }
        else
        {
          cardano_tx_builder_vote_with_deferred_redeemer(builder, voter, action_id, procedure, deferred_callback, context);
        }
      }
      else
      {
        TRY(read_data(reader, &redeemer));
        cardano_tx_builder_vote(builder, voter, action_id, procedure, redeemer);
      }
      break;
    case 27:
      TRY(cardano_cbor_reader_read_uint(reader, &number));
      cardano_tx_builder_set_current_treasury_value(builder, number);
      break;
    case 25:
      TRY(read_sub(reader, &sub));
      TRY(read_utxos(reader, &sub_resolved));
      for (size_t i = 0; i < cardano_utxo_list_get_length(sub_resolved); ++i)
      {
        cardano_utxo_t* item = NULL;
        result               = cardano_utxo_list_get(sub_resolved, i, &item);
        if (result == CARDANO_SUCCESS)
        {
          result = cardano_utxo_list_add(resolved, item);
        }
        cardano_utxo_unref(&item);
        if (result != CARDANO_SUCCESS)
        {
          goto cleanup;
        }
      }
      cardano_tx_builder_add_sub_transaction(builder, sub, sub_resolved);
      break;
    default:
      result = CARDANO_ERROR_DECODING;
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_end_array(reader);
  }
cleanup:
  cardano_credential_unref(&credential);
  cardano_account_balance_interval_unref(&interval);
  cardano_proposal_procedure_unref(&proposal);
  cardano_voter_unref(&voter);
  cardano_governance_action_id_unref(&action_id);
  cardano_voting_procedure_unref(&procedure);
  cardano_sub_transaction_unref(&sub);
  cardano_utxo_list_unref(&sub_resolved);
  cardano_transaction_output_unref(&output);
  cardano_utxo_unref(&utxo);
  cardano_script_unref(&script);
  cardano_plutus_data_unref(&redeemer);
  cardano_plutus_data_unref(&datum);
  cardano_certificate_unref(&certificate);
  cardano_metadatum_unref(&metadata);
  cardano_blake2b_hash_unref(&hash);
  cardano_asset_name_unref(&asset_name);
  cardano_reward_address_unref(&reward);
  cardano_buffer_unref(&bytes);
  return result;
}

/**
 * \brief Decode an owned pool snapshot, including partial results on failure.
 * \param reader Borrowed configuration reader.
 * \param pools Receives a zero-initialized owned array.
 * \param size Receives the array length; callers unref every entry and free the array.
 * \return Decoding or allocation status.
 */
static cardano_error_t
read_pool_state(cardano_cbor_reader_t* reader, cardano_pool_params_t*** pools, size_t* size)
{
  int64_t         count  = 0;
  cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);
  if (result != CARDANO_SUCCESS)
  {
    return result;
  }
  if (count < 0 || (uint64_t)count > SIZE_MAX / sizeof(cardano_pool_params_t*))
  {
    return CARDANO_ERROR_DECODING;
  }
  if (count > 0)
  {
    *pools = calloc((size_t)count, sizeof(cardano_pool_params_t*));
    if (*pools == NULL)
    {
      return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    }
  }
  *size = (size_t)count;
  for (size_t i = 0; result == CARDANO_SUCCESS && i < *size; ++i)
  {
    result = read_pool_parameters(reader, &(*pools)[i]);
  }
  return result == CARDANO_SUCCESS ? cardano_cbor_reader_read_end_array(reader) : result;
}

/**
 * \brief Read the protocol version and release the retained version reference.
 * \param parameters Borrowed protocol parameters.
 * \return Major version, or zero when unspecified.
 */
static uint64_t
protocol_major(cardano_protocol_parameters_t* parameters)
{
  cardano_protocol_version_t* version = cardano_protocol_parameters_get_protocol_version(parameters);
  uint64_t                    major   = cardano_protocol_version_get_major(version);
  cardano_protocol_version_unref(&version);
  return major;
}

/* DEFINITIONS ***************************************************************/

unsigned int
cometa_transaction_builder_build(cometa_runtime_t* selector_runtime, cometa_runtime_t* evaluator_runtime, cometa_runtime_t* deferred_runtime, const unsigned char* config, size_t config_size, const unsigned char* plan, size_t plan_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count)
{
  if (output == NULL || diagnostic == NULL || key_count == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }
  cardano_pool_params_t** pools                    = NULL;
  size_t                  pool_count               = 0U;
  *key_count                                       = 0U;
  *output                                          = NULL;
  *diagnostic                                      = NULL;
  cardano_cbor_reader_t*         reader            = cardano_cbor_reader_new(config, config_size);
  cardano_cbor_reader_t*         instructions      = NULL;
  cardano_cbor_writer_t*         writer            = NULL;
  cardano_buffer_t*              parameter_bytes   = NULL;
  cardano_protocol_parameters_t* parameters        = NULL;
  cardano_address_t*             change            = NULL;
  cardano_address_t*             collateral_change = NULL;
  cardano_utxo_list_t*           available         = NULL;
  cardano_utxo_list_t*           collateral        = NULL;
  cardano_utxo_list_t*           resolved          = NULL;
  cardano_blake2b_hash_set_t*    unique_signers    = NULL;
  cardano_tx_builder_t*          builder           = NULL;
  cardano_transaction_t*         transaction       = NULL;
  cardano_coin_selector_t*       selector          = NULL;
  cardano_tx_evaluator_t*        evaluator         = NULL;
  uint64_t                       fee = 0U, padding = 0U;
  cardano_slot_config_t          slots    = { 0 };
  int64_t                        count    = 0;
  deferred_context_t*            contexts = NULL;
  cardano_network_id_t           network;
  cardano_error_t                result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : array(reader, 11);
  if (result != CARDANO_SUCCESS)
  {
    goto cleanup;
  }
  TRY(cardano_cbor_reader_read_bytestring(reader, &parameter_bytes));
  TRY(cometa_parameters_from_snapshot(cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &parameters));
  TRY(read_address(reader, &change));
  TRY(read_utxos(reader, &available));
  TRY(read_utxos(reader, &collateral));
  TRY(read_address(reader, &collateral_change));
  TRY(cardano_cbor_reader_read_uint(reader, &fee));
  TRY(cardano_cbor_reader_read_uint(reader, &padding));
  TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_time));
  TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_slot));
  TRY(cardano_cbor_reader_read_uint(reader, &slots.slot_length));
  TRY(read_pool_state(reader, &pools, &pool_count));
  TRY(cardano_cbor_reader_read_end_array(reader));
  TRY(complete(reader));
  if (slots.slot_length == 0U || padding > SIZE_MAX)
  {
    result = CARDANO_ERROR_INVALID_ARGUMENT;
    goto cleanup;
  }
  builder = cardano_tx_builder_new(parameters, &slots);
  if (builder == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  TRY(cardano_tx_builder_set_pool_state(builder, pools, pool_count));
  TRY(cardano_address_get_network_id(change, &network));
  cardano_tx_builder_set_network_id(builder, network);
  cardano_tx_builder_set_change_address(builder, change);
  cardano_tx_builder_set_utxos(builder, available);
  cardano_tx_builder_set_collateral_utxos(builder, collateral);
  cardano_tx_builder_set_collateral_change_address(builder, collateral_change != NULL ? collateral_change : change);
  cardano_tx_builder_set_minimum_fee(builder, fee);
  cardano_tx_builder_pad_signer_count(builder, (size_t)padding);
  if (selector_runtime != NULL)
  {
    TRY(cometa_coin_selector_new(selector_runtime, cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &selector));
    cardano_tx_builder_set_coin_selector(builder, selector);
  }
  if (evaluator_runtime != NULL)
  {
    TRY(cometa_evaluation_new(evaluator_runtime, &evaluator));
    cardano_tx_builder_set_tx_evaluator(builder, evaluator);
  }
  TRY(cardano_utxo_list_new(&resolved));
  for (size_t i = 0; i < cardano_utxo_list_get_length(available) + cardano_utxo_list_get_length(collateral); ++i)
  {
    cardano_utxo_t* item   = NULL;
    const size_t    offset = cardano_utxo_list_get_length(available);
    result                 = i < offset ? cardano_utxo_list_get(available, i, &item) : cardano_utxo_list_get(collateral, i - offset, &item);
    if (result == CARDANO_SUCCESS)
    {
      result = cardano_utxo_list_add(resolved, item);
    }
    cardano_utxo_unref(&item);
    if (result != CARDANO_SUCCESS)
    {
      goto cleanup;
    }
  }
  instructions = cardano_cbor_reader_new(plan, plan_size);
  if (instructions == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  TRY(cardano_cbor_reader_read_start_array(instructions, &count));
  if (count < 0)
  {
    result = CARDANO_ERROR_DECODING;
    goto cleanup;
  }
  if ((uint64_t)count > SIZE_MAX / sizeof(deferred_context_t))
  {
    result = CARDANO_ERROR_INTEGER_OVERFLOW;
    goto cleanup;
  }
  contexts = calloc(count == 0 ? 1U : (size_t)count, sizeof(deferred_context_t));
  if (contexts == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  for (int64_t i = 0; i < count; ++i)
  {
    contexts[i].runtime = deferred_runtime;
    TRY(instruction(builder, instructions, resolved, contexts, (size_t)i));
  }
  TRY(cardano_cbor_reader_read_end_array(instructions));
  TRY(complete(instructions));
  TRY(cardano_tx_builder_build(builder, &transaction));
  TRY(cardano_transaction_get_unique_signers_with_pool_state(transaction, resolved, protocol_major(parameters), pools, pool_count, &unique_signers));
  if ((uint64_t)cardano_blake2b_hash_set_get_length(unique_signers) > UINT64_MAX - padding)
  {
    result = CARDANO_ERROR_INTEGER_OVERFLOW;
    goto cleanup;
  }
  *key_count = (uint64_t)cardano_blake2b_hash_set_get_length(unique_signers) + padding;
  writer     = cardano_cbor_writer_new();
  if (writer == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  TRY(cardano_transaction_to_cbor(transaction, writer));
  TRY(cardano_cbor_writer_encode_in_buffer(writer, output));
cleanup:
  if (result != CARDANO_SUCCESS && builder != NULL)
  {
    const char* message = cardano_tx_builder_get_last_error(builder);
    if (message != NULL && message[0] != '\0')
    {
      *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));
    }
  }
  cardano_cbor_writer_unref(&writer);
  cardano_cbor_reader_unref(&reader);
  cardano_cbor_reader_unref(&instructions);
  cardano_blake2b_hash_set_unref(&unique_signers);
  cardano_utxo_list_unref(&resolved);
  cardano_tx_builder_unref(&builder);
  free(contexts);
  cardano_transaction_unref(&transaction);
  cardano_coin_selector_unref(&selector);
  cardano_tx_evaluator_unref(&evaluator);
  for (size_t i = 0; i < pool_count; ++i)
  {
    cardano_pool_params_unref(&pools[i]);
  }
  free(pools);
  cardano_protocol_parameters_unref(&parameters);
  cardano_address_unref(&change);
  cardano_address_unref(&collateral_change);
  cardano_utxo_list_unref(&available);
  cardano_utxo_list_unref(&collateral);
  cardano_buffer_unref(&parameter_bytes);
  return result;
}

/* Parsed redeemers and their collection cache their original CBOR. Native
 * setters do not invalidate those caches, so create fresh outer wrappers before
 * changing indices, payloads or budgets. Retain the existing data owners rather
 * than clearing recursively: their exact payload encoding remains observable.
 * The witness setter retains the replacement; the caller receives another owned
 * reference. On failure the original witness set remains installed unchanged. */
static cardano_error_t
fresh_balance_redeemers(cardano_witness_set_t* witnesses, cardano_redeemer_list_t** output)
{
  if (output == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }
  *output                           = NULL;
  cardano_redeemer_list_t* original = cardano_witness_set_get_redeemers(witnesses);
  if (original == NULL)
  {
    return CARDANO_SUCCESS;
  }

  cardano_redeemer_list_t* fresh  = NULL;
  cardano_error_t          result = cardano_redeemer_list_new(&fresh);
  for (size_t i = 0U; result == CARDANO_SUCCESS && i < cardano_redeemer_list_get_length(original); ++i)
  {
    cardano_redeemer_t*    source      = NULL;
    cardano_redeemer_t*    replacement = NULL;
    cardano_plutus_data_t* data        = NULL;
    cardano_ex_units_t*    units       = NULL;
    result                             = cardano_redeemer_list_get(original, i, &source);
    if (result == CARDANO_SUCCESS)
    {
      data   = cardano_redeemer_get_data(source);
      units  = cardano_redeemer_get_ex_units(source);
      result = cardano_redeemer_new(cardano_redeemer_get_tag(source), cardano_redeemer_get_index(source), data, units, &replacement);
    }
    if (result == CARDANO_SUCCESS)
    {
      result = cardano_redeemer_list_add(fresh, replacement);
    }
    cardano_redeemer_unref(&replacement);
    cardano_plutus_data_unref(&data);
    cardano_ex_units_unref(&units);
    cardano_redeemer_unref(&source);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_witness_set_set_redeemers(witnesses, fresh);
  }
  if (result == CARDANO_SUCCESS)
  {
    *output = fresh;
    fresh   = NULL;
  }
  cardano_redeemer_list_unref(&original);
  cardano_redeemer_list_unref(&fresh);
  return result;
}

/** \brief Bind a decoded witness redeemer to its input and optional callback. */
static cardano_error_t
balance_redeemer(cardano_cbor_reader_t* reader, cardano_redeemer_list_t* redeemers, cardano_input_to_redeemer_map_t* inputs, cardano_deferred_redeemer_list_t* deferred, deferred_context_t* context)
{
  uint64_t                     tag = 0U, index = 0U;
  bool                         callback = false;
  cardano_transaction_input_t* input    = NULL;
  cardano_redeemer_t*          found    = NULL;
  cardano_error_t              result   = array(reader, 4);
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_uint(reader, &tag);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_uint(reader, &index);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = read_balance_input(reader, &input);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_bool(reader, &callback);
  }
  if (result == CARDANO_SUCCESS)
  {
    result = cardano_cbor_reader_read_end_array(reader);
  }
  for (size_t i = 0U; result == CARDANO_SUCCESS && i < cardano_redeemer_list_get_length(redeemers); ++i)
  {
    cardano_redeemer_t* item = NULL;
    result                   = cardano_redeemer_list_get(redeemers, i, &item);
    if (result == CARDANO_SUCCESS && (uint64_t)cardano_redeemer_get_tag(item) == tag && cardano_redeemer_get_index(item) == index)
    {
      if (found != NULL)
      {
        result = CARDANO_ERROR_DUPLICATED_KEY;
      }
      else
      {
        found = item;
        cardano_redeemer_ref(found);
      }
    }
    cardano_redeemer_unref(&item);
  }
  if (result == CARDANO_SUCCESS && found == NULL)
  {
    result = CARDANO_ERROR_ELEMENT_NOT_FOUND;
  }
  if (result == CARDANO_SUCCESS && input != NULL)
  {
    result = cardano_input_to_redeemer_map_insert(inputs, input, found);
  }
  if (result == CARDANO_SUCCESS && callback)
  {
    result = cardano_deferred_redeemer_list_add(deferred, found, deferred_callback, context);
  }
  cardano_transaction_input_unref(&input);
  cardano_redeemer_unref(&found);
  return result;
}

/* DEFINITIONS ***************************************************************/

unsigned int
cometa_transaction_balance(cometa_runtime_t* selector_runtime, cometa_runtime_t* evaluator_runtime, cometa_runtime_t* deferred_runtime, const unsigned char* config, size_t config_size, const unsigned char* request, size_t request_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count)
{
  if (output == NULL || diagnostic == NULL || key_count == NULL)
  {
    return CARDANO_ERROR_POINTER_IS_NULL;
  }
  cardano_pool_params_t** pools                       = NULL;
  size_t                  pool_count                  = 0U;
  *output                                             = NULL;
  *diagnostic                                         = NULL;
  *key_count                                          = 0U;
  cardano_cbor_reader_t*            reader            = cardano_cbor_reader_new(config, config_size);
  cardano_cbor_reader_t*            payload           = NULL;
  cardano_cbor_writer_t*            writer            = NULL;
  cardano_buffer_t*                 parameter_bytes   = NULL;
  cardano_protocol_parameters_t*    parameters        = NULL;
  cardano_address_t*                change            = NULL;
  cardano_address_t*                collateral_change = NULL;
  cardano_utxo_list_t*              available         = NULL;
  cardano_utxo_list_t*              collateral        = NULL;
  cardano_utxo_list_t*              references        = NULL;
  cardano_utxo_list_t*              selected          = NULL;
  cardano_utxo_list_t*              resolved          = NULL;
  cardano_transaction_t*            transaction       = NULL;
  cardano_transaction_body_t*       body              = NULL;
  cardano_witness_set_t*            witnesses         = NULL;
  cardano_redeemer_list_t*          redeemers         = NULL;
  cardano_input_to_redeemer_map_t*  input_map         = NULL;
  cardano_deferred_redeemer_list_t* deferred          = NULL;
  cardano_coin_selector_t*          selector          = NULL;
  cardano_tx_evaluator_t*           evaluator         = NULL;
  cardano_blake2b_hash_set_t*       signers           = NULL;
  deferred_context_t*               contexts          = NULL;
  uint64_t                          fee = 0U, padding = 0U, ignored = 0U;
  int64_t                           count  = 0;
  cardano_error_t                   result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : array(reader, 11);
  if (result != CARDANO_SUCCESS)
  {
    goto cleanup;
  }
  TRY(cardano_cbor_reader_read_bytestring(reader, &parameter_bytes));
  TRY(cometa_parameters_from_snapshot(cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &parameters));
  TRY(read_address(reader, &change));
  TRY(read_utxos(reader, &available));
  TRY(read_utxos(reader, &collateral));
  TRY(read_address(reader, &collateral_change));
  TRY(cardano_cbor_reader_read_uint(reader, &fee));
  TRY(cardano_cbor_reader_read_uint(reader, &padding));
  for (size_t i = 0U; i < 3U; ++i)
  {
    TRY(cardano_cbor_reader_read_uint(reader, &ignored));
  }
  TRY(read_pool_state(reader, &pools, &pool_count));
  TRY(cardano_cbor_reader_read_end_array(reader));
  TRY(complete(reader));
  if (padding > SIZE_MAX)
  {
    result = CARDANO_ERROR_INTEGER_OVERFLOW;
    goto cleanup;
  }
  payload = cardano_cbor_reader_new(request, request_size);
  if (payload == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  TRY(array(payload, 4));
  TRY(read_balance_transaction(payload, &transaction));
  if (transaction == NULL)
  {
    result = CARDANO_ERROR_POINTER_IS_NULL;
    goto cleanup;
  }
  TRY(read_utxos(payload, &references));
  TRY(read_utxos(payload, &selected));
  TRY(cardano_input_to_redeemer_map_new(&input_map));
  TRY(cardano_deferred_redeemer_list_new(&deferred));
  witnesses = cardano_transaction_get_witness_set(transaction);
  TRY(fresh_balance_redeemers(witnesses, &redeemers));
  TRY(cardano_cbor_reader_read_start_array(payload, &count));
  if (count < 0 || (uint64_t)count > SIZE_MAX / sizeof(deferred_context_t))
  {
    result = CARDANO_ERROR_DECODING;
    goto cleanup;
  }
  contexts = calloc(count == 0 ? 1U : (size_t)count, sizeof(deferred_context_t));
  if (contexts == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  for (int64_t i = 0; i < count; ++i)
  {
    contexts[i].runtime = deferred_runtime;
    contexts[i].index   = (uint64_t)i;
    TRY(balance_redeemer(payload, redeemers, input_map, deferred, &contexts[i]));
  }
  TRY(cardano_cbor_reader_read_end_array(payload));
  TRY(cardano_cbor_reader_read_end_array(payload));
  TRY(complete(payload));
  if (selector_runtime == NULL)
  {
    TRY(cardano_random_improve_coin_selector_new(&selector));
  }
  else
  {
    TRY(cometa_coin_selector_new(selector_runtime, cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &selector));
  }
  TRY(cometa_evaluation_new(evaluator_runtime, &evaluator));
  body = cardano_transaction_get_body(transaction);
  /* Invalidate only the mutable outer body; nested intent/data caches survive. */
  cardano_transaction_body_clear_cbor_cache(body);
  if (fee > cardano_transaction_body_get_fee(body))
  {
    TRY(cardano_transaction_body_set_fee(body, fee));
  }
  TRY(cardano_balance_transaction_with_pool_state(transaction, (size_t)padding, parameters, references, selected, input_map, available, selector, change, collateral, collateral_change != NULL ? collateral_change : change, evaluator, deferred, pools, pool_count));
  TRY(cardano_utxo_list_new(&resolved));
  cardano_utxo_list_t* sources[] = { available, collateral, selected, references };
  for (size_t i = 0U; i < 4U; ++i)
  {
    for (size_t j = 0U; j < cardano_utxo_list_get_length(sources[i]); ++j)
    {
      cardano_utxo_t* item = NULL;
      result               = cardano_utxo_list_get(sources[i], j, &item);
      if (result == CARDANO_SUCCESS)
      {
        result = cardano_utxo_list_add(resolved, item);
      }
      cardano_utxo_unref(&item);
      if (result != CARDANO_SUCCESS)
      {
        goto cleanup;
      }
    }
  }
  TRY(cardano_transaction_get_unique_signers_with_pool_state(transaction, resolved, protocol_major(parameters), pools, pool_count, &signers));
  if (padding > UINT64_MAX - cardano_blake2b_hash_set_get_length(signers))
  {
    result = CARDANO_ERROR_INTEGER_OVERFLOW;
    goto cleanup;
  }
  *key_count = padding + cardano_blake2b_hash_set_get_length(signers);
  writer     = cardano_cbor_writer_new();
  if (writer == NULL)
  {
    result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;
    goto cleanup;
  }
  TRY(cardano_transaction_to_cbor(transaction, writer));
  TRY(cardano_cbor_writer_encode_in_buffer(writer, output));
cleanup:
  if (result != CARDANO_SUCCESS && transaction != NULL)
  {
    const char* message = cardano_transaction_get_last_error(transaction);
    if (message != NULL && message[0] != '\0')
    {
      *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));
    }
  }
  cardano_cbor_reader_unref(&reader);
  cardano_cbor_reader_unref(&payload);
  cardano_cbor_writer_unref(&writer);
  cardano_buffer_unref(&parameter_bytes);
  for (size_t i = 0; i < pool_count; ++i)
  {
    cardano_pool_params_unref(&pools[i]);
  }
  free(pools);
  cardano_protocol_parameters_unref(&parameters);
  cardano_address_unref(&change);
  cardano_address_unref(&collateral_change);
  cardano_utxo_list_unref(&available);
  cardano_utxo_list_unref(&collateral);
  cardano_utxo_list_unref(&references);
  cardano_utxo_list_unref(&selected);
  cardano_utxo_list_unref(&resolved);
  cardano_deferred_redeemer_list_unref(&deferred);
  cardano_input_to_redeemer_map_unref(&input_map);
  cardano_redeemer_list_unref(&redeemers);
  cardano_witness_set_unref(&witnesses);
  cardano_transaction_body_unref(&body);
  cardano_transaction_unref(&transaction);
  cardano_coin_selector_unref(&selector);
  cardano_tx_evaluator_unref(&evaluator);
  cardano_blake2b_hash_set_unref(&signers);
  free(contexts);
  return result;
}

#undef TRY