You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以编程方式将UTXO哈希转换为十六进制编码的TransactionUnspentOutput字节字符串?

How to Get Hex-Encoded TransactionUnspentOutput from Lucid's utxoToCore

Got it, let's fix this. The issue you're seeing is that the utxoToCore function returns a Cardano Serialization Library (CSL) native object, which in JavaScript shows up as a pointer (like TransactionUnspentOutput { ptr: 1247376 }) when you log it directly. To get the hex-encoded byte string you need, you have to serialize this CSL object to its canonical CBOR format first, then convert those bytes to hex.

Step 1: Serialize the CSL Object to CBOR Bytes

All CSL objects expose a to_bytes() method that converts them to raw CBOR bytes—this is the underlying format Cardano uses for transaction structures.

Step 2: Convert Bytes to Hexadecimal String

Once you have the CBOR bytes, use Lucid's built-in toHex utility (or a standard buffer conversion) to turn the byte array into a hex string matching your desired format.

Modified Code Example

Update your existing code to include the serialization step:

import { C, toHex, fromHex } from "lucid-cardano";

// Your existing utxoToCore function
export const utxoToCore = (utxo: UTxO): Core.TransactionUnspentOutput => {
  const output = C.TransactionOutput.new(
    C.Address.from_bech32(utxo.address),
    assetsToValue(utxo.assets)
  );
  if (utxo.datumHash) {
    output.set_datum(
      C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash)))
    );
  }
  return C.TransactionUnspentOutput.new(
    C.TransactionInput.new(
      C.TransactionHash.from_bytes(fromHex(utxo.txHash)),
      C.BigNum.from_str(utxo.outputIndex.toString())
    ),
    output
  );
};

// New function to get the hex-encoded string
export const utxoToCoreHex = (utxo: UTxO): string => {
  const coreUtxo = utxoToCore(utxo);
  // Serialize to CBOR bytes, then convert to hex
  return toHex(coreUtxo.to_bytes());
};

Key Details

  • coreUtxo.to_bytes(): This method handles converting the CSL TransactionUnspentOutput object into its raw, canonical CBOR byte representation.
  • toHex(): Lucid's utility takes a Uint8Array (the output of to_bytes()) and converts it to a lowercase hex string, matching the format in your example.

Validation Tips

  • Ensure your input UTxO object includes all required fields: txHash, outputIndex, address, and assets. If your UTxO has a datum, include the datumHash field too.
  • Double-check you're using compatible versions of Lucid and the Cardano Serialization Library—version mismatches can break serialization logic.

内容的提问来源于stack exchange,提问作者Jan Swoboda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:47:43