|
| 1 | +import { assertContentTypeJson, assertResponseOk } from '@/lib/url' |
| 2 | +export * from 'wallets/lnc' |
| 3 | + |
| 4 | +export async function testCreateInvoice (credentials, { signal }) { |
| 5 | + await checkPerms(credentials, { signal }) |
| 6 | + return await createInvoice({ msats: 1000, expiry: 1 }, credentials, { signal }) |
| 7 | +} |
| 8 | + |
| 9 | +export async function createInvoice ({ msats, description, expiry }, credentials, { signal }) { |
| 10 | + const result = await rpcCall(credentials, 'lnrpc.Lightning.AddInvoice', { memo: description, valueMsat: msats, expiry }, { signal }) |
| 11 | + return result.payment_request |
| 12 | +} |
| 13 | + |
| 14 | +async function checkPerms (credentials, { signal }) { |
| 15 | + const enforcePerms = [ |
| 16 | + { 'lnrpc.Lightning.SendPaymentSync': false }, |
| 17 | + { 'lnrpc.Lightning.AddInvoice': true }, |
| 18 | + { 'lnrpc.Wallet.SendCoins': false } |
| 19 | + ] |
| 20 | + |
| 21 | + const results = await rpcCall(credentials, 'checkPerms', enforcePerms.map(perm => Object.keys(perm)[0]), { signal }) |
| 22 | + for (let i = 0; i < enforcePerms.length; i++) { |
| 23 | + const [key, expected] = Object.entries(enforcePerms[i])[0] |
| 24 | + const result = results[i] |
| 25 | + if (result !== expected) { |
| 26 | + if (expected) { |
| 27 | + throw new Error(`missing permission: ${key}`) |
| 28 | + } else { |
| 29 | + throw new Error(`too broad permission: ${key}`) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +async function rpcCall (credentials, method, payload, { signal }) { |
| 36 | + const body = { |
| 37 | + Connection: { |
| 38 | + Mailbox: credentials.serverHostRecv || 'mailbox.terminal.lightning.today:443', |
| 39 | + PairingPhrase: credentials.pairingPhraseRecv, |
| 40 | + LocalKey: credentials.localKeyRecv, |
| 41 | + RemoteKey: credentials.remoteKeyRecv |
| 42 | + }, |
| 43 | + Method: method, |
| 44 | + Payload: JSON.stringify(payload) |
| 45 | + } |
| 46 | + |
| 47 | + let res = await fetch(process.env.LNCD_URL + '/rpc', { |
| 48 | + method: 'POST', |
| 49 | + signal, |
| 50 | + headers: { |
| 51 | + 'Content-Type': 'application/json' |
| 52 | + }, |
| 53 | + body: JSON.stringify(body) |
| 54 | + }) |
| 55 | + |
| 56 | + assertResponseOk(res) |
| 57 | + assertContentTypeJson(res) |
| 58 | + |
| 59 | + res = await res.json() |
| 60 | + |
| 61 | + // cache auth credentials |
| 62 | + credentials.localKeyRecv = res.Connection.LocalKey |
| 63 | + credentials.remoteKeyRecv = res.Connection.RemoteKey |
| 64 | + credentials.serverHostRecv = res.Connection.Mailbox |
| 65 | + |
| 66 | + const result = JSON.parse(res.Result) |
| 67 | + return result |
| 68 | +} |
0 commit comments