broadcastTransaction function

Future<String> broadcastTransaction({
  1. required String rawTxHex,
  2. required UTXONetworkType type,
})

Implementation

Future<String> broadcastTransaction({
  required String rawTxHex,
  required UTXONetworkType type,
}) async {
  final (result, client, error) = await fetchFromRandomElectrumXNode(
    (client) async {
      final broadcastResult =
          await client.broadcastTransaction(rawTxHex: rawTxHex);
      return broadcastResult;
    },
    client: null,
    token: type.coin,
    endpoints: type.endpoints,
  );

  final host = "${client?.host}:${client?.port}";

  if (result == null) {
    throw SendFailure("Broadcasting failed for $host: ${error?.message}");
  }

  final json = jsonDecode(result);

  if (result.contains('error')) {
    if (json
        case {
          "error": {"error": {"code": int code, "message": String message}}
        }) {
      throw SendFailure("$host $code $message");
    }
    if (json case {"error": {"code": int code, "message": String message}}) {
      throw SendFailure("$host $code $message");
    }
    throw SendFailure("Unknown error for $host: $result");
  }

  if (result.contains('result') == false) {
    throw SendFailure("Unknown error for $host: $result");
  }

  final hash = json['result'];

  return hash;
}