validateSegwit function

Address validateSegwit(
  1. String address
)

Implementation

Address validateSegwit(String address) {
  final prefix = address.substring(0, 2).toLowerCase();
  Decoded decoded;

  /// Try to decode the address using bech32m
  try {
    final _decoded = segwit.decode(address);
    decoded = Decoded(
      prefix: prefix,
      words: Uint8List.fromList(
        _decoded.program,
      ),
    );
  } on InvalidChecksum {
    decoded = bech32m.decode(Encoded(data: address));
  } catch (e) {
    throw SegwitException(e);
  }

  late Type type;
  // other lengths result in a [SegwitException]
  switch (decoded.words.length) {
    /// P2WPKH
    case 20:
      type = Type.p2pkh;
      break;

    /// P2WSH
    case 32:
      type = Type.p2sh;
      break;

    /// P2TR
    case 53:
      type = Type.p2tr;
      break;

    /// Other
    default:
      throw SegwitException('Invalid words length: ${decoded.words.length}');
  }

  late Network network;
  switch (prefix) {
    case 'bc':
      {
        network = Network.mainnet;
      }
      break;
    case 'tb':
      {
        network = Network.testnet;
      }
  }

  return Address(type, network, true);
}