@@ -3,6 +3,7 @@ import { bech32 } from 'bech32'
3
3
import { lnAddrSchema } from './validate'
4
4
import { FetchTimeoutError } from '@/lib/fetch'
5
5
import { WALLET_CREATE_INVOICE_TIMEOUT_MS } from './constants'
6
+ import { assertContentTypeJson , assertResponseOk , ResponseAssertError } from '@/lib/url'
6
7
7
8
export function encodeLNUrl ( url ) {
8
9
const words = bech32 . toWords ( Buffer . from ( url . toString ( ) , 'utf8' ) )
@@ -35,25 +36,33 @@ export async function lnAddrOptions (addr, { signal } = {}) {
35
36
// support HTTP and HTTPS during development
36
37
protocol = process . env . NEXT_PUBLIC_URL . split ( '://' ) [ 0 ]
37
38
}
38
- const unexpectedErrorMessage = `An unexpected error occurred fetching the Lightning Address metadata for ${ addr } . Check the address and try again.`
39
- let res
39
+
40
+ const unexpectedErrorMessage = 'Lightning address validation failed. Make sure you entered the correct address.'
41
+ let body
40
42
const url = `${ protocol } ://${ domain } /.well-known/lnurlp/${ name } `
41
43
try {
42
- const req = await fetch ( url , { signal } )
43
- res = await req . json ( )
44
+ const res = await fetch ( url , { signal } )
45
+ assertResponseOk ( res )
46
+ assertContentTypeJson ( res )
47
+ body = await res . json ( )
44
48
} catch ( err ) {
45
- console . log ( 'Error fetching lnurlp' , err )
49
+ console . log ( 'Error fetching lnurlp:' , err )
50
+ if ( err instanceof ResponseAssertError ) {
51
+ throw err
52
+ }
46
53
if ( err . name === 'TimeoutError' ) {
47
54
throw new FetchTimeoutError ( 'GET' , url , WALLET_CREATE_INVOICE_TIMEOUT_MS )
48
55
}
49
- // If `fetch` fails, or if `req.json` fails, catch it here and surface a reasonable error
56
+ if ( err . name === 'SyntaxError' ) {
57
+ throw new Error ( `GET ${ url } : invalid JSON` )
58
+ }
50
59
throw new Error ( unexpectedErrorMessage )
51
60
}
52
- if ( res . status === 'ERROR' ) {
61
+ if ( body . status === 'ERROR' ) {
53
62
// if the response doesn't adhere to spec by providing a `reason` entry, returns a default error message
54
- throw new Error ( res . reason ?? unexpectedErrorMessage )
63
+ throw new Error ( body . reason ?? unexpectedErrorMessage )
55
64
}
56
65
57
- const { minSendable, maxSendable, ...leftOver } = res
66
+ const { minSendable, maxSendable, ...leftOver } = body
58
67
return { min : minSendable / 1000 , max : maxSendable / 1000 , ...leftOver }
59
68
}
0 commit comments