encodeNevent static method
Encode nevent (event reference)
eventId - 32-byte hex event ID (required)
relays - optional list of relay URLs where the event may be found
author - optional 32-byte hex public key of the event author
kind - optional event kind number
Implementation
static String encodeNevent({
required String eventId,
List<String>? relays,
String? author,
int? kind,
}) {
final tlvData = <int>[];
// Type 0: event ID (special) - 32 bytes
final eventIdBytes = hex.decode(eventId);
if (eventIdBytes.length != 32) {
throw ArgumentError('Event ID must be 32 bytes (64 hex characters)');
}
tlvData.add(0); // type
tlvData.add(32); // length
tlvData.addAll(eventIdBytes); // value
// Type 1: relays (optional, can be multiple)
if (relays != null) {
for (final relay in relays) {
final relayBytes = utf8.encode(relay);
if (relayBytes.length > 255) {
throw ArgumentError(
'Relay URL too long: ${relay.length} bytes (max 255)');
}
tlvData.add(1); // type
tlvData.add(relayBytes.length); // length
tlvData.addAll(relayBytes); // value
}
}
// Type 2: author pubkey (optional, 32 bytes)
if (author != null) {
final authorBytes = hex.decode(author);
if (authorBytes.length != 32) {
throw ArgumentError(
'Author pubkey must be 32 bytes (64 hex characters)');
}
tlvData.add(2); // type
tlvData.add(32); // length
tlvData.addAll(authorBytes); // value
}
// Type 3: kind (optional, 32-bit unsigned big-endian)
if (kind != null) {
final kindBytes = [
(kind >> 24) & 0xFF,
(kind >> 16) & 0xFF,
(kind >> 8) & 0xFF,
kind & 0xFF,
];
tlvData.add(3); // type
tlvData.add(4); // length (32-bit = 4 bytes)
tlvData.addAll(kindBytes); // value
}
// Convert to bech32
final data = Nip19Utils.convertBits(tlvData, 8, 5, true);
var encoder = Bech32Encoder();
Bech32 input = Bech32(Hrps.kNevent, data);
var encoded = encoder.convert(input, input.hrp.length + data.length + 10);
return encoded;
}