selectUtxos method

List<Utxo> selectUtxos({
  1. required List<ValueTransferOutput> outputs,
  2. required UtxoSelectionStrategy utxoStrategy,
})

Implementation

List<Utxo> selectUtxos({
  required List<ValueTransferOutput> outputs,
  required UtxoSelectionStrategy utxoStrategy,
}) {
  List<Utxo> utxos = sortUtxos(utxoStrategy);
  if (utxos.isEmpty) {
    print('Error -> no Utxos to select.');
    return [];
  }
  int utxoValue = 0;
  int outputValue = 0;

  utxos.forEach((utxo) {
    utxoValue += utxo.value;
  });

  // total the output value
  outputs.forEach((output) {
    outputValue += output.value.toInt();
  });
  List<Utxo> selectedUtxos = [];
  print('selecting Utxos to cover ${nanoWitToWit(outputValue)}');

  if (outputValue > utxoValue) {
    print('Insufficient funds.');
    return [];
  }

  while (outputValue > 0) {
    // since the list is sorted - take the first item
    Utxo utxo = utxos.first;
    utxos.removeAt(0);
    selectedUtxos.add(utxo);
    outputValue -= utxo.value;
  }

  return selectedUtxos;
}