0

I want to use this function as coin selection for my transactions:

txBuilder.add_inputs_from(unspentOutputs, 3);

The problem I have is I'm using cardano-graphql to retrieve UTxOs:

{
  "data": {
    "utxos": [
      {
        "transaction": {
          "hash": "ae6a7f64b2ce09ac0f0ffd8f92dda8af15367e02801057b4be40ca1d199e74b0"
        },
        "index": 1,
        "value": "2592591",
        "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
        "tokens": [
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303033",
              "assetName": "47616d654368616e676572303033"
            },
            "quantity": "10"
          },
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303034",
              "assetName": "47616d654368616e676572303034"
            },
            "quantity": "10"
          }
        ]
      },
      {
        "transaction": {
          "hash": "ae6a7f64b2ce09ac0f0ffd8f92dda8af15367e02801057b4be40ca1d199e74b0"
        },
        "index": 2,
        "value": "2481480",
        "address": "addr_test1qpypxf9jma2lkmzwn6nhypmynqpmus7x0ekwp2jfdrxqgm8vecdcssszlmywlyn7h0nkqp9jyk8p7dhjecglhu9m75xq4mwl9v",
        "tokens": [
          {
            "asset": {
              "policyId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d8900",
              "assetId": "4223e84e15c5fc65bd4959ef84264ea53133b782fc176b2c538d890047616d654368616e676572303035",
              "assetName": "47616d654368616e676572303035"
            },
            "quantity": "10"
          }
        ]
      }
   ]
}

How do I convert from this format to TransactionUnspentOutputs?

export class TransactionUnspentOutputs {
  free(): void;
/**
* @returns {TransactionUnspentOutputs}
*/
  static new(): TransactionUnspentOutputs;
/**
* @returns {number}
*/
  len(): number;
/**
* @param {number} index
* @returns {TransactionUnspentOutput}
*/
  get(index: number): TransactionUnspentOutput;
/**
* @param {TransactionUnspentOutput} elem
*/
  add(elem: TransactionUnspentOutput): void;
}

Is there a function or helper I could use?

1 Answer 1

0

This is the function I use to convert the UTxOs from graphql to TransactionUnspentOutputs:

async function getUTxOs(address: string) {

  const url = `https://d.graphql-api.${process.env.ENVIRONMENT}.dandelion.link`;

  const headers = {
    "content-type": "application/json"
  };

  const query = `
  {
    utxos(where: { address: { _in: "${address}" } }) {
      transaction {
        hash
      }
      index
      value
      address
      tokens {
        asset {
          policyId
          assetId
          assetName
        }
        quantity
      }
    }
  }
  `;

  const graphqlQuery = {
    "query": query
  };

  const response = await axios({
    url,
    method: 'post',
    headers: headers,
    data: graphqlQuery
  });

  const Utxos = []
  
  try {
    const rawUtxos = response.data.data.utxos
    for (const rawUtxo of rawUtxos) {
      var utxo: CardanoWasm.TransactionUnspentOutput;
      if(rawUtxo.tokens.length > 0) {
        const multiAsset = CardanoWasm.MultiAsset.new()
        const assets = CardanoWasm.Assets.new()
        for (const token of rawUtxo.tokens) {
          assets.insert(
            CardanoWasm.AssetName.new(Buffer.from(token.asset.assetName, "hex")),
            CardanoWasm.BigNum.from_str(token.quantity)
          )
          multiAsset.insert(CardanoWasm.ScriptHash.from_bytes(Buffer.from(token.asset.policyId, "hex")), assets)
        }
        utxo = CardanoWasm.TransactionUnspentOutput.new(
          CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(rawUtxo.transaction.hash, "hex")), rawUtxo.index), 
          CardanoWasm.TransactionOutputBuilder.new()
            .with_address(CardanoWasm.Address.from_bech32(rawUtxo.address))
            .next()
            .with_coin_and_asset(CardanoWasm.BigNum.from_str(rawUtxo.value), multiAsset)
            .build()          
        )
      } else {
        utxo = CardanoWasm.TransactionUnspentOutput.new(
          CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(rawUtxo.transaction.hash, "hex")), rawUtxo.index), 
          CardanoWasm.TransactionOutputBuilder.new()
            .with_address(CardanoWasm.Address.from_bech32(rawUtxo.address))
            .next()
            .with_value(CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(rawUtxo.value)))
            .build()          
        )
      }

      const input = utxo.input()
      const txid = input.transaction_id().to_bytes().toString();
      const txindx = input.index()
      const output = utxo.output()
      const amount = output.amount().coin().to_str() // amount in lovelace
      const multiasset = output.amount().multiasset()
      let multiAssetStr = ''

      if (multiasset) {
        const keys = multiasset.keys() // policy Ids of the multiassets
        const N = keys.len()
        // console.log(`${N} Multiassets in the UTXO`)

        for (let i = 0; i < N; i++) {
          const policyId = keys.get(i)
          const policyIdHex = policyId.to_bytes().toString();
          const assets = multiasset.get(policyId)
          const assetNames = assets?.keys()
          const K = assetNames?.len() ?? 0

          for (let j = 0; j < K; j++) {
            const assetName = assetNames?.get(j)
            const assetNameString = assetName?.name().toString()
            const assetNameHex = assetName?.name().toString()
            const multiassetAmt = multiasset.get_asset(policyId, assetName!)
            multiAssetStr += `+ ${multiassetAmt.to_str()} + ${policyIdHex}.${assetNameHex} (${assetNameString})`
          }
        }
      }

      const utxoObj = {
        txid: txid,
        txindx: txindx,
        amount: amount,
        str: `${txid} #${txindx} = ${amount}`,
        multiAssetStr: multiAssetStr,
        TransactionUnspentOutput: utxo,
      }
      Utxos.push(utxoObj)
    }
    return Utxos
  } catch (error) {
    console.log(error)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.