diff --git a/nip19.test.js b/nip19.test.js index 722e88e..c9842da 100644 --- a/nip19.test.js +++ b/nip19.test.js @@ -100,3 +100,12 @@ test('decode naddr from go-nostr with different TLV ordering', () => { expect(data.kind).toEqual(30023) expect(data.identifier).toEqual('banana') }) + +test('encode and decode nrelay', () => { + let url = "wss://relay.nostr.example" + let nrelay = nip19.nrelayEncode(url) + expect(nrelay).toMatch(/nrelay1\w+/) + let {type, data} = nip19.decode(nrelay) + expect(type).toEqual('nrelay') + expect(data).toEqual(url) +}) diff --git a/nip19.ts b/nip19.ts index 628abd5..82f8a7a 100644 --- a/nip19.ts +++ b/nip19.ts @@ -82,6 +82,16 @@ export function decode(nip19: string): { } } + case 'nrelay': { + let tlv = parseTLV(data) + if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay') + + return { + type: 'nrelay', + data: utf8Decoder.decode(tlv[0][0]) + } + } + case 'nsec': case 'npub': case 'note': @@ -160,6 +170,14 @@ export function naddrEncode(addr: AddressPointer): string { return bech32.encode('naddr', words, Bech32MaxSize) } +export function nrelayEncode(url: string): string { + let data = encodeTLV({ + 0: [utf8Encoder.encode(url)] + }) + let words = bech32.toWords(data) + return bech32.encode('nrelay', words, Bech32MaxSize) +} + function encodeTLV(tlv: TLV): Uint8Array { let entries: Uint8Array[] = []