From 3e2b756e5b97db690b9a707049060805ca88c9de Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Fri, 30 Jan 2026 17:18:39 +0000 Subject: relay reconnect logic --- lib/nwc.ts | 80 +++++++++++++++++++++++++++++++++------------------------ lib/payments.ts | 3 +++ 2 files changed, 50 insertions(+), 33 deletions(-) diff --git a/lib/nwc.ts b/lib/nwc.ts index f04c2dde..c7f8d7e9 100644 --- a/lib/nwc.ts +++ b/lib/nwc.ts @@ -43,40 +43,51 @@ const handledKey = "handled:nwc"; const handledMaxSize = 200000; export default () => { - const r = new Relay("ws://sf:7777"); - - r.on("open", async (_) => { - r.subscribe("nwc", { kinds: [23194], "#p": [serverPubkey, serverPubkey2] }); - const info = await finalizeEvent( - { - created_at: Math.floor(Date.now() / 1000), - kind: 13194, - tags: [ - ["p", serverPubkey], - ["notifications", "payment_received payment_sent"], - ], - content: methods.join(" "), - }, - hexToBytes(serverSecret), - ); - r.send(["EVENT", info]); - - const info2 = await finalizeEvent( - { - created_at: Math.floor(Date.now() / 1000), - kind: 13194, - tags: [ - ["p", serverPubkey2], - ["notifications", "payment_received payment_sent"], - ], - content: methods.join(" "), - }, - hexToBytes(serverSecret2), - ); - r.send(["EVENT", info2]); - }); + let r: any; + + function connect() { + r = new Relay("ws://sf:7777", { reconnect: false }); + + r.on("open", async (_) => { + l("nwc connected to strfry"); + r.subscribe("nwc", { kinds: [23194], "#p": [serverPubkey, serverPubkey2] }); + const info = await finalizeEvent( + { + created_at: Math.floor(Date.now() / 1000), + kind: 13194, + tags: [ + ["p", serverPubkey], + ["notifications", "payment_received payment_sent"], + ], + content: methods.join(" "), + }, + hexToBytes(serverSecret), + ); + r.send(["EVENT", info]); - r.on("event", async (sub, ev) => { + const info2 = await finalizeEvent( + { + created_at: Math.floor(Date.now() / 1000), + kind: 13194, + tags: [ + ["p", serverPubkey2], + ["notifications", "payment_received payment_sent"], + ], + content: methods.join(" "), + }, + hexToBytes(serverSecret2), + ); + r.send(["EVENT", info2]); + }); + + r.on("close", () => { + warn("nwc strfry connection lost, reconnecting in 5s"); + setTimeout(connect, 5000); + }); + + r.on("error", () => {}); + + r.on("event", async (sub, ev) => { try { if (sub !== "nwc") return; const now = Math.floor(Date.now() / 1000); @@ -135,6 +146,9 @@ export default () => { // err("problem with nwc", e.message); } }); + } + + connect(); }; const handle = (method, params, ev, app, user) => diff --git a/lib/payments.ts b/lib/payments.ts index 1a886988..931bf167 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -849,6 +849,9 @@ export const check = async () => { else if (failed) await reverse(p); } catch (e) { err("failed to finalize", p.id, e.message); + if (e.message?.includes("already been reversed")) { + await db.sRem("pending", p.hash); + } } } } catch (e) { -- cgit v1.2.3