Add LNURL utils

This commit is contained in:
Alex Gleason 2024-01-15 16:20:10 -06:00
parent e16e81da86
commit 786d9914af
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 32 additions and 0 deletions

14
src/utils/lnurl.test.ts Normal file
View File

@ -0,0 +1,14 @@
import { assertEquals } from '@/deps-test.ts';
import { lnurlDecode, lnurlEncode } from './lnurl.ts';
const lnurl = 'lnurl1dp68gurn8ghj7um5v93kketj9ehx2amn9uh8wetvdskkkmn0wahz7mrww4excup0dajx2mrv92x9xp';
const url = 'https://stacker.news/.well-known/lnurlp/odell';
Deno.test('lnurlEncode', () => {
assertEquals(lnurlEncode(url), lnurl);
});
Deno.test('lnurlDecode', () => {
assertEquals(lnurlDecode(lnurl), url);
});

18
src/utils/lnurl.ts Normal file
View File

@ -0,0 +1,18 @@
import { bech32 } from '@/deps.ts';
/** Encode a URL to LNURL format. */
function lnurlEncode(url: string): `lnurl1${string}` {
const data = new TextEncoder().encode(url);
const words = bech32.toWords(data);
return bech32.encode('lnurl', words);
}
/** Decode a LNURL into a URL. */
function lnurlDecode(lnurl: string): string {
const { prefix, words } = bech32.decode(lnurl);
if (prefix !== 'lnurl') throw new Error('Invalid LNURL');
const data = new Uint8Array(bech32.fromWords(words));
return new TextDecoder().decode(data);
}
export { lnurlDecode, lnurlEncode };