determineSendDirection function

TransactionTransferMethod determineSendDirection({
  1. required List<ElectrumInput> inputs,
  2. required List<ElectrumOutput> outputs,
  3. required Iterable<NodeWithAddress> nodes,
  4. required UTXONetworkType type,
  5. required Iterable<AddressType> addressTypes,
})

Implementation

TransactionTransferMethod determineSendDirection({
  required List<ElectrumInput> inputs,
  required List<ElectrumOutput> outputs,
  required Iterable<NodeWithAddress> nodes,
  required UTXONetworkType type,
  required Iterable<AddressType> addressTypes,
}) {
  bool anyInputsAreOurs;
  try {
    anyInputsAreOurs = inputs.any((input) {
      final inputAddress = input.getAddresses(
        addressTypes: addressTypes,
        networkType: type,
      );
      return nodes.addresses.any(
        (nodeAddress) => inputAddress.contains(nodeAddress),
      );
    });
  } catch (e) {
    anyInputsAreOurs = false;
  }

  final anyOutputsAreOurs = outputs.any((output) => output.belongsToUs);

  final outputsHaveReceive = outputs.any((output) {
    final outputAddresses = output.getAddresses(
      addressTypes: addressTypes,
      networkType: type,
    );
    return nodes.receiveNodes.addresses.any(
      (nodeAddress) => outputAddresses.contains(nodeAddress),
    );
  });

  final outputsHaveChange = outputs.any((output) {
    final outputAddresses = output.getAddresses(
      addressTypes: addressTypes,
      networkType: type,
    );
    return nodes.changeNodes.addresses.any(
      (nodeAddress) => outputAddresses.contains(nodeAddress),
    );
  });

  return switch ((anyInputsAreOurs, anyOutputsAreOurs)) {
    (true, true) when outputsHaveReceive => TransactionTransferMethod.own,
    (true, true) when outputsHaveChange && outputs.length == 1 =>
      TransactionTransferMethod.own,
    (true, true) => TransactionTransferMethod.send,
    (true, false) => TransactionTransferMethod.send,
    (false, true) => TransactionTransferMethod.receive,
    _ => TransactionTransferMethod.unknown,
  };
}