decodeNaddr static method
Decode naddr and return Naddr object
Implementation
static Naddr decodeNaddr(String naddrStr) {
var decoder = Bech32Decoder();
var bech32Result = decoder.convert(naddrStr, naddrStr.length);
if (bech32Result.hrp != Hrps.kNaddr) {
throw ArgumentError(
"Invalid HRP: expected '${Hrps.kNaddr}', got '${bech32Result.hrp}'");
}
var data = Nip19Utils.convertBits(bech32Result.data, 5, 8, false);
final tlv = Nip19TLV.parseTLV(data);
String? identifier;
List<String> relays = [];
String? pubkey;
int? kind;
for (var t in tlv) {
switch (t.type) {
case 0: // identifier
try {
identifier = utf8.decode(t.value);
} catch (e) {
// Ignore invalid UTF-8 per spec
}
break;
case 1: // relay
try {
relays.add(utf8.decode(t.value));
} catch (e) {
// Ignore invalid UTF-8 per spec
}
break;
case 2: // author pubkey
if (t.value.length == 32) {
pubkey = hex.encode(t.value);
}
break;
case 3: // kind
if (t.value.length == 4) {
kind = (t.value[0] << 24) |
(t.value[1] << 16) |
(t.value[2] << 8) |
t.value[3];
}
break;
default:
// Ignore unrecognized TLV types per spec
break;
}
}
// Validate required fields
if (identifier == null) {
throw ArgumentError('Missing required identifier field (type 0)');
}
if (pubkey == null) {
throw ArgumentError('Missing required author pubkey field (type 2)');
}
if (kind == null) {
throw ArgumentError('Missing required kind field (type 3)');
}
return Naddr(
identifier: identifier,
pubkey: pubkey,
kind: kind,
relays: relays.isEmpty ? null : relays,
);
}