|
| 1 | +import { API_URL, PREIMAGE_AWAIT_TIMEOUT_MS } from '@/wallets/zebedee' |
| 2 | +import { assertContentTypeJson } from '@/lib/url' |
| 3 | +import { callWithTimeout } from '@/lib/time' |
| 4 | +import { fetchWithTimeout } from '@/lib/fetch' |
| 5 | + |
| 6 | +export * from '@/wallets/zebedee' |
| 7 | + |
| 8 | +export async function testSendPayment ({ apiKey }, { signal }) { |
| 9 | + const wallet = await apiCall('wallet', { apiKey, method: 'GET' }, { signal }) |
| 10 | + if (!wallet.data) throw new Error('wallet not found') |
| 11 | +} |
| 12 | + |
| 13 | +export async function sendPayment (bolt11, { apiKey }, { signal }) { |
| 14 | + const res = await apiCall('payments', { body: { invoice: bolt11 }, apiKey }, { signal }) |
| 15 | + const { id, preimage } = res?.data |
| 16 | + if (preimage) return preimage |
| 17 | + // the api might return before the invoice is paid, so we'll wait for the preimage |
| 18 | + return await waitForPreimage(id, { apiKey }, { signal }) |
| 19 | +} |
| 20 | + |
| 21 | +async function waitForPreimage (id, { apiKey }, { signal }) { |
| 22 | + return await callWithTimeout(async () => { |
| 23 | + let preimage |
| 24 | + while (true) { |
| 25 | + const res = await apiCall('payments/{id}', { body: { id }, apiKey, method: 'GET' }, { signal }) |
| 26 | + preimage = res?.data?.preimage |
| 27 | + if (preimage) break |
| 28 | + await new Promise(resolve => setTimeout(resolve, 10)) |
| 29 | + } |
| 30 | + return preimage |
| 31 | + }, PREIMAGE_AWAIT_TIMEOUT_MS) |
| 32 | +} |
| 33 | + |
| 34 | +export async function apiCall (api, { body, apiKey, method = 'POST' }, { signal }) { |
| 35 | + const headers = { |
| 36 | + apikey: apiKey, |
| 37 | + 'Content-Type': 'application/json' |
| 38 | + } |
| 39 | + if (method === 'GET' && body) { |
| 40 | + for (const [k, v] of Object.entries(body)) { |
| 41 | + api = api.replace('{' + k + '}', v) |
| 42 | + } |
| 43 | + } |
| 44 | + const res = await fetchWithTimeout(API_URL + api, { |
| 45 | + method, |
| 46 | + headers, |
| 47 | + signal, |
| 48 | + body: method === 'POST' ? JSON.stringify(body) : undefined |
| 49 | + }) |
| 50 | + // https://zbd.dev/api-reference/errors |
| 51 | + if (res.status !== 200) { |
| 52 | + let error |
| 53 | + try { |
| 54 | + assertContentTypeJson(res) |
| 55 | + const json = await res.json() |
| 56 | + if (json?.message) error = json.message |
| 57 | + } catch (e) { |
| 58 | + error = res.statusText || 'error ' + res.status |
| 59 | + } |
| 60 | + throw new Error(error) |
| 61 | + } |
| 62 | + return res.json() |
| 63 | +} |
0 commit comments