diff --git a/README.md b/README.md index cffead35..368487ee 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,14 @@ --- +# Channel management + +Open a channel's details to set a private label, copy its counterparty's advertised connection addresses, or review a splice. Labels are stored in the node's `cln-application/channel-labels` datastore namespace; they are not sent to peers. A credential without datastore access can still list channels, with a label-lookup warning. + +Splice in adds on-chain funds and splice out withdraws local channel funds without closing the channel. Both peers must support splicing, and the channel must be connected and active with no pending funding transaction. Enter whole sats, review the direction and amount, then confirm. CLN selects the fee using its normal safety checks. Splice RPCs are available through REST or Commando; the application's current gRPC schema does not expose them. + +An unresolved submission is retained in the browser so closing and reopening channel details does not submit it again. A lost reply is not proof of failure: check the channel and wallet before dismissing a record or attempting another splice. Pending splice amounts and confirmations come from the node, not the browser's saved record. Confirmation lookup requires CLN's SQL plugin and RPC permission; failures are shown as unavailable instead of an invented count. CLN does not report the peer's required confirmation count, so the UI does not guess it. + # Getting started - ## Standalone diff --git a/apps/backend/source/controllers/lightning.ts b/apps/backend/source/controllers/lightning.ts index 7aaf650c..3ec6f69a 100755 --- a/apps/backend/source/controllers/lightning.ts +++ b/apps/backend/source/controllers/lightning.ts @@ -10,11 +10,14 @@ const ALLOWED_METHODS = new Set([ 'listfunds', 'listpeers', 'listpeerchannels', + 'setchannellabel', 'listnodes', 'sql', 'listsqlschemas', 'feerates', 'fundchannel', + 'splicein', + 'spliceout', 'close', 'withdraw', 'newaddr', @@ -22,8 +25,8 @@ const ALLOWED_METHODS = new Set([ 'keysend', 'invoice', 'offer', - 'decode', 'fetchinvoice', + 'decode', 'createrune', ]); @@ -36,6 +39,35 @@ export function validateCallRequest(method: unknown, params: unknown): string | if (params !== undefined && (typeof params !== 'object' || params === null)) { return 'Invalid params for ' + method; } + if (method === 'setchannellabel') { + const p = params as any; + if ( + !p || + Object.keys(p).some(k => !['channel_id', 'label'].includes(k)) || + typeof p.channel_id !== 'string' || + !/^[0-9a-f]{64}$/.test(p.channel_id) || + typeof p.label !== 'string' || + p.label.length > 80 || + /[\u0000-\u001f\u007f]/.test(p.label) + ) { + return 'Channel labels require a valid channel ID and at most 80 characters, without control characters'; + } + } + if (method === 'splicein' || method === 'spliceout') { + const p = params as any; + if ( + !p || + Array.isArray(p) || + Object.keys(p).some(k => !['channel', 'amount'].includes(k)) || + typeof p.channel !== 'string' || + !/^[0-9a-f]{64}$/.test(p.channel) || + typeof p.amount !== 'string' || + !/^[1-9][0-9]{0,15}$/.test(p.amount) || + !Number.isSafeInteger(Number(p.amount)) + ) { + return 'Splicing requires one channel ID and a positive whole-satoshi amount; fee overrides and scripts are not accepted'; + } + } if (method === 'createrune') { const restrictions = (params as any)?.restrictions; const valid = @@ -70,11 +102,93 @@ export class LightningController { logger.warn('Refused lightning call: ' + validationError); return handleError(new APIError(HttpStatusCode.FORBIDDEN, validationError), req, res, next); } + if (req.body.method === 'setchannellabel') { + const { channel_id, label } = req.body.params; + const channels = await this.clnService.call('listpeerchannels', {}); + if (!channels.channels?.some((c: any) => c.channel_id === channel_id)) { + throw new APIError( + HttpStatusCode.INVALID_DATA, + 'This channel is no longer available. Refresh the channel list.', + ); + } + await this.clnService.call('datastore', { + key: ['cln-application', 'channel-labels', channel_id], + string: label.trim(), + mode: 'create-or-replace', + }); + return res.status(200).json({ channel_id, label: label.trim() }); + } + if (req.body.method === 'splicein' || req.body.method === 'spliceout') { + if (APP_CONSTANTS.APP_CONNECT === AppConnect.GRPC) { + throw new APIError( + HttpStatusCode.INVALID_DATA, + 'Splicing requires a REST or Commando connection; this application’s gRPC schema does not expose splicein/spliceout.', + ); + } + const channels = await this.clnService.call('listpeerchannels', {}); + const channel = channels.channels.find( + (c: any) => c.channel_id === req.body.params.channel, + ); + if ( + !channel || + channel.state !== 'CHANNELD_NORMAL' || + !channel.peer_connected || + channel.inflight?.length + ) { + throw new APIError( + HttpStatusCode.INVALID_DATA, + 'Splice requires a connected, active channel with no pending funding transaction. Inspect channel status before retrying.', + ); + } + const peers = await this.clnService.call('listpeers', { id: channel.peer_id }); + const features = peers.peers?.[0]?.features; + if ( + typeof features !== 'string' || + !/^[0-9a-fA-F]+$/.test(features) || + !(BigInt('0x' + features) & (3n << 62n)) + ) { + throw new APIError( + HttpStatusCode.INVALID_DATA, + 'The peer has not negotiated splice support (feature 62/63). Enable splicing on the peer and reconnect.', + ); + } + } logger.info('Calling method: ' + req.body.method); - this.clnService + return this.clnService .call(req.body.method, req.body.params) - .then((commandRes: any) => { + .then(async (commandRes: any) => { logger.info('Controller received response for ' + req.body.method); + if (req.body.method === 'listpeerchannels') { + try { + const stored = await this.clnService.call('listdatastore', { + key: ['cln-application', 'channel-labels'], + }); + const labels = new Map( + (stored.datastore || []) + .filter( + (v: any) => + v.key?.length === 3 && + v.key[0] === 'cln-application' && + v.key[1] === 'channel-labels' && + typeof v.string === 'string', + ) + .map((v: any) => [v.key[2], v.string]), + ); + commandRes.channels = commandRes.channels.map((c: any) => ({ + ...c, + channel_label: labels.get(c.channel_id) || '', + })); + } catch (error) { + commandRes.channels = commandRes.channels.map((c: any) => ({ + ...c, + channel_label_error: 'Could not load channel labels: ' + String(error), + })); + } + commandRes.channels = commandRes.channels.map((c: any) => ({ + ...c, + splice_supported: APP_CONSTANTS.APP_CONNECT !== AppConnect.GRPC, + })); + } if ( APP_CONSTANTS.APP_CONNECT == AppConnect.COMMANDO && req.body.method && diff --git a/apps/backend/source/service/grpc.service.ts b/apps/backend/source/service/grpc.service.ts index bf2b5963..a848e79e 100644 --- a/apps/backend/source/service/grpc.service.ts +++ b/apps/backend/source/service/grpc.service.ts @@ -313,6 +313,20 @@ export class GRPCService { payload.amount_msat = this.transformTypes('Amount', payload.amount_msat); } + // CLN JSON-RPC uses hyphenated names; protobuf expects the numeric enum. + if (method?.toLowerCase() === 'datastore' && typeof payload.mode === 'string') { + const modes: Record = { + 'must-create': 0, + 'must-replace': 1, + 'create-or-replace': 2, + 'must-append': 3, + 'create-or-append': 4, + }; + if (!Object.prototype.hasOwnProperty.call(modes, payload.mode)) + throw new Error('Invalid datastore mode'); + payload.mode = modes[payload.mode]; + } + // Map values with their Enums const enumsMapping: Record = { Feerates: ['style'], diff --git a/apps/backend/test/channel-management.test.mjs b/apps/backend/test/channel-management.test.mjs new file mode 100644 index 00000000..ff1df188 --- /dev/null +++ b/apps/backend/test/channel-management.test.mjs @@ -0,0 +1,144 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +process.env.APP_LOG_FILE = join(mkdtempSync(join(tmpdir(), 'channel-test-')), 'app.log'); +const { LightningController, validateCallRequest } = await import( + '../dist/controllers/lightning.js' +); +const { APP_CONSTANTS, AppConnect } = await import('../dist/shared/consts.js'); +const id = 'ab'.repeat(32); +const peer = '02' + 'cd'.repeat(32); +const channel = { channel_id: id, peer_id: peer, state: 'CHANNELD_NORMAL', peer_connected: true }; +async function request(method, params, call, connection = AppConnect.REST) { + APP_CONSTANTS.APP_CONNECT = connection; + const controller = new LightningController({ call }); + const res = { + statusCode: 200, + status(value) { + this.statusCode = value; + return this; + }, + json(value) { + this.body = value; + return this; + }, + }; + await controller.callMethod({ body: { method, params } }, res, () => {}); + return res; +} +test('splice input accepts only a channel and positive whole-satoshi amount', () => { + for (const method of ['splicein', 'spliceout']) { + assert.equal(validateCallRequest(method, { channel: id, amount: '1000000' }), null); + for (const amount of ['0', '-1', '1.5', '1sat', '9007199254740992']) + assert.ok(validateCallRequest(method, { channel: id, amount })); + assert.ok(validateCallRequest(method, { channel: id, amount: '1', force_feerate: true })); + assert.ok(validateCallRequest(method, { channel: 'not a channel', amount: '1' })); + } + assert.equal(validateCallRequest('offer', {}), null); + assert.equal(validateCallRequest('fetchinvoice', {}), null); +}); +test('splice checks connection, pending funding and peer features before mutation', async () => { + for (const changed of [{ peer_connected: false }, { state: 'ONCHAIN' }, { inflight: [{}] }]) { + const calls = []; + const res = await request('splicein', { channel: id, amount: '1' }, async method => { + calls.push(method); + return { channels: [{ ...channel, ...changed }] }; + }); + assert.notEqual(res.statusCode, 200); + assert.deepEqual(calls, ['listpeerchannels']); + } + for (const features of ['00', 'invalid']) { + const calls = []; + const res = await request('spliceout', { channel: id, amount: '1' }, async method => { + calls.push(method); + return method === 'listpeerchannels' ? { channels: [channel] } : { peers: [{ features }] }; + }); + assert.notEqual(res.statusCode, 200); + assert.deepEqual(calls, ['listpeerchannels', 'listpeers']); + } + const calls = []; + const res = await request( + 'splicein', + { channel: id, amount: '1000000' }, + async (method, params) => { + calls.push([method, params]); + return method === 'listpeerchannels' + ? { channels: [channel] } + : method === 'listpeers' + ? { peers: [{ features: (1n << 63n).toString(16) }] } + : { txid: id }; + }, + ); + assert.equal(res.statusCode, 200); + assert.deepEqual(calls.at(-1), ['splicein', { channel: id, amount: '1000000' }]); +}); +test('gRPC splice refusal happens before any node operation', async () => { + const res = await request( + 'splicein', + { channel: id, amount: '1' }, + () => { + throw Error('must not call'); + }, + AppConnect.GRPC, + ); + assert.match(res.body, /gRPC/); +}); +test('labels are limited to the application namespace and existing channels', async () => { + assert.ok(validateCallRequest('setchannellabel', { channel_id: id, label: 'x'.repeat(81) })); + assert.ok(validateCallRequest('setchannellabel', { channel_id: id, label: 'bad\nlabel' })); + const calls = []; + const res = await request( + 'setchannellabel', + { channel_id: id, label: ' Savings ' }, + async (method, params) => { + calls.push([method, params]); + return { channels: [channel] }; + }, + ); + assert.deepEqual(res.body, { channel_id: id, label: 'Savings' }); + assert.deepEqual(calls[1], [ + 'datastore', + { + key: ['cln-application', 'channel-labels', id], + string: 'Savings', + mode: 'create-or-replace', + }, + ]); + const missing = await request( + 'setchannellabel', + { channel_id: id, label: 'test' }, + async method => { + assert.equal(method, 'listpeerchannels'); + return { channels: [] }; + }, + ); + assert.notEqual(missing.statusCode, 200); +}); +test('label lookup failure retains channels and exposes the failure', async () => { + const res = await request('listpeerchannels', {}, async method => { + if (method === 'listdatastore') throw Error('permission denied'); + return { channels: [channel] }; + }); + assert.equal(res.statusCode, 200); + assert.equal(res.body.channels[0].channel_id, id); + assert.match(res.body.channels[0].channel_label_error, /permission denied/); +}); + +test('gRPC encodes JSON-RPC datastore modes as the protobuf enum', async () => { + const { GRPCService } = await import('../dist/service/grpc.service.js'); + const service = Object.create(GRPCService.prototype); + assert.equal( + service.transformPayload('Datastore', { + key: ['app'], + string: 'label', + mode: 'create-or-replace', + }).mode, + 2, + ); + assert.throws( + () => service.transformPayload('Datastore', { mode: 'unknown' }), + /Invalid datastore mode/, + ); +}); diff --git a/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.scss b/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.scss index ec4248da..4c6beea3 100644 --- a/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.scss +++ b/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.scss @@ -3,6 +3,19 @@ .channel-scroll-container { max-height: 53vh; + min-width: 0; + & .channel-balance-summary, & .channel-peer-heading, & .channel-peer-name { + min-width: 0; + max-width: 100%; + } + & .channel-peer-name { + overflow-wrap: anywhere; + white-space: normal; + } + & .channel-peer-heading .dot { + flex-shrink: 0; + margin-top: 0.45em; + } & .progress { height: 6px; } diff --git a/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.tsx b/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.tsx index cb3254ee..25d55e61 100755 --- a/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.tsx +++ b/apps/frontend/src/components/cln/ChannelDetails/ChannelDetails.tsx @@ -1,4 +1,8 @@ +import { localLiquidityPercent } from '../../../utilities/channel-status'; import './ChannelDetails.scss'; +import ChannelLabel from './ChannelLabel'; +import SpliceChannel from './SpliceChannel'; +import SpliceStatus from './SpliceStatus'; import { useState } from 'react'; import PerfectScrollbar from 'react-perfect-scrollbar'; import { Spinner, Card, Row, Col, ProgressBar, OverlayTrigger, Tooltip } from 'react-bootstrap'; @@ -24,12 +28,12 @@ const ChannelDetails = (props) => { const nodeInfo = useSelector(selectNodeInfo); const showToast = useSelector(selectShowToast); const [showToastState, setShowToastState] = useState(false); - const [channelClosed, setChannelClosed] = useState(props.selChannel.current_state !== 'ACTIVE' && props.selChannel.state !== 'CHANNELD_NORMAL'); + const [channelClosed, setChannelClosed] = useState(false); const [responseStatus, setResponseStatus] = useState(CallStatus.NONE); const [responseMessage, setResponseMessage] = useState(''); const openLinkHandler = (event) => { - window.open('https://blockstream.info/' + (nodeInfo.network === 'testnet' ? 'testnet/' : '') + 'tx/' + event.target.id, '_blank', 'noopener,noreferrer'); + window.open('https://mempool.guide/' + (nodeInfo.network === 'testnet' ? 'testnet/' : '') + 'tx/' + event.target.id, '_blank', 'noopener,noreferrer'); }; const ChannelCloseHandler = event => { @@ -115,20 +119,20 @@ const ChannelDetails = (props) => { - + {titleCase(props.selChannel.current_state) + ' - ' + (channelStateMap[props.selChannel.state] ?? titleCase(props.selChannel.state?.replaceAll('_', ' ')))}} > - +
- {props.selChannel.node_alias} + {props.selChannel.channel_label || props.selChannel.node_alias || props.selChannel.peer_id}
- 1000000 || props.selChannel.to_them_sat > 1000000) ? (props.selChannel.to_us_sat / 1000) : props.selChannel.to_us_sat} key={1} /> - 1000000 || props.selChannel.to_them_sat > 1000000) ? (props.selChannel.to_them_sat / 1000) : props.selChannel.to_them_sat} key={2} /> + + @@ -139,6 +143,22 @@ const ChannelDetails = (props) => { + + + + Counterparty node ID + {props.selChannel.peer_id} + + + + Node URI + + {props.selChannel.node_uris?.length ? props.selChannel.node_uris.map(uri =>
+
{uri}
+ +
) : This peer has not advertised a connection address. Ask its operator for a node URI.} + +
Short Channel Id @@ -193,6 +213,7 @@ const ChannelDetails = (props) => {
+ { <> )}
- {channelClosed ? ( + {channelClosed || !['ACTIVE', 'INACTIVE'].includes(props.selChannel.current_state) ? ( <> ) : ( diff --git a/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.test.tsx b/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.test.tsx new file mode 100644 index 00000000..33675784 --- /dev/null +++ b/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.test.tsx @@ -0,0 +1,27 @@ +import { fireEvent, screen, render } from '@testing-library/react'; +import ChannelLabel from './ChannelLabel'; +import { HttpService } from '../../../services/http.service'; +jest.mock('../../../services/http.service', () => ({ HttpService: { clnCall: jest.fn() } })); +jest.mock('react-redux', () => ({ useDispatch: () => jest.fn() })); +const call = HttpService.clnCall as jest.Mock; +const channel = { channel_id: 'ab'.repeat(32), channel_label: 'Savings' }; +beforeEach(() => call.mockReset()); +test('clearing a private label saves an empty label and reports removal', async () => { + call.mockResolvedValue({ channel_id: channel.channel_id, label: '' }); + render(); + fireEvent.change(screen.getByLabelText('Channel label'), { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save label' })); + await screen.findByText('Channel label removed.'); + expect(call).toHaveBeenCalledWith('setchannellabel', { + channel_id: channel.channel_id, + label: '', + }); +}); +test('save failure retains editable text and shows the reason', async () => { + call.mockRejectedValue(new Error('permission denied')); + render(); + fireEvent.change(screen.getByLabelText('Channel label'), { target: { value: 'New label' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save label' })); + await screen.findByText(/Could not save channel label: Error: permission denied/); + expect(screen.getByLabelText('Channel label')).toHaveValue('New label'); +}); diff --git a/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.tsx b/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.tsx new file mode 100644 index 00000000..813a42a1 --- /dev/null +++ b/apps/frontend/src/components/cln/ChannelDetails/ChannelLabel.tsx @@ -0,0 +1,96 @@ +import { useEffect, useState } from 'react'; +import { Form, Alert, InputGroup } from 'react-bootstrap'; +import { useDispatch } from 'react-redux'; +import { HttpService } from '../../../services/http.service'; +import { setChannelLabel } from '../../../store/rootSlice'; + +export default function ChannelLabel({ channel }) { + const dispatch = useDispatch(); + const [label, setLabel] = useState(channel.channel_label || ''); + const [editing, setEditing] = useState(false); + const [saving, setSaving] = useState(false); + const [message, setMessage] = useState(''); + const [error, setError] = useState(''); + useEffect(() => { + if (!editing) setLabel(channel.channel_label || ''); + }, [channel.channel_label, editing]); + const save = async () => { + if (saving) return; + setSaving(true); + setMessage(''); + setError(''); + try { + const result: any = await HttpService.clnCall('setchannellabel', { + channel_id: channel.channel_id, + label, + }); + dispatch(setChannelLabel(result)); + setEditing(false); + setMessage(result.label ? 'Channel label saved.' : 'Channel label removed.'); + } catch (e) { + setError('Could not save channel label: ' + String(e)); + } finally { + setSaving(false); + } + }; + return ( +
+ {channel.channel_label_error && ( + {channel.channel_label_error} + )} + + Channel label + + + { + setLabel(e.target.value); + setEditing(true); + setMessage(''); + }} + /> + +
+ Private to your node. Leave blank to use the peer alias. +
+
+ + {editing && ( + + )} +
+ {message && ( +

+ {message} +

+ )} + {error && ( + + {error} + + )} +
+ ); +} diff --git a/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.test.tsx b/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.test.tsx new file mode 100644 index 00000000..53360e5d --- /dev/null +++ b/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.test.tsx @@ -0,0 +1,105 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import SpliceChannel from './SpliceChannel'; +import { HttpService } from '../../../services/http.service'; +jest.mock('../../../services/http.service', () => ({ HttpService: { clnCall: jest.fn() } })); +const call = HttpService.clnCall as jest.Mock; +const channel = { + channel_id: 'ab'.repeat(32), + peer_id: '02' + 'cd'.repeat(32), + funding_txid: 'ef'.repeat(32), + state: 'CHANNELD_NORMAL', + peer_connected: true, +}; +beforeEach(() => { + localStorage.clear(); + call.mockReset(); +}); +function review() { + fireEvent.change(screen.getByLabelText('Amount in sats'), { target: { value: '1000000' } }); + fireEvent.click(screen.getByRole('button', { name: 'Review splice' })); +} +test('review does not mutate; confirmation submits once and survives remount', async () => { + let finish: (value: any) => void = () => {}; + call.mockImplementation( + () => + new Promise(resolve => { + finish = resolve; + }), + ); + const view = render(); + review(); + expect(call).not.toHaveBeenCalled(); + const confirm = screen.getByRole('button', { name: 'Confirm splice' }); + fireEvent.click(confirm); + fireEvent.click(confirm); + expect(call).toHaveBeenCalledTimes(1); + expect(call).toHaveBeenCalledWith('splicein', { channel: channel.channel_id, amount: '1000000' }); + finish({ txid: '12'.repeat(32) }); + await screen.findByText(/Broadcast; waiting for confirmations/); + view.unmount(); + render(); + expect(screen.queryByRole('button', { name: 'Review splice' })).not.toBeInTheDocument(); + expect(call).toHaveBeenCalledTimes(1); +}); +test('lost reply is retained and never automatically retried', async () => { + call.mockRejectedValue(new Error('connection lost')); + const view = render(); + review(); + fireEvent.click(screen.getByRole('button', { name: 'Confirm splice' })); + await screen.findByText(/Error: connection lost/); + view.unmount(); + render(); + expect(screen.getByText(/Error: connection lost/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Review splice' })).not.toBeInTheDocument(); + expect(call).toHaveBeenCalledTimes(1); +}); +test('unreadable recovery record blocks a new submission without crashing', () => { + localStorage.setItem('splice:' + channel.channel_id, '{broken'); + render(); + expect(screen.getByText(/saved splice record cannot be read/)).toBeInTheDocument(); + expect(call).not.toHaveBeenCalled(); +}); +test('storage failure prevents submission and reports it', async () => { + render(); + review(); + const spy = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw Error('quota'); + }); + fireEvent.click(screen.getByRole('button', { name: 'Confirm splice' })); + expect(screen.getByText(/No splice was submitted/)).toBeInTheDocument(); + expect(call).not.toHaveBeenCalled(); + spy.mockRestore(); +}); +test('disconnected channels and gRPC transport cannot submit', () => { + const view = render(); + fireEvent.change(screen.getByLabelText('Amount in sats'), { target: { value: '1' } }); + expect(screen.getByRole('button', { name: 'Review splice' })).toBeDisabled(); + view.rerender(); + expect( + screen.getByText(/unavailable through this application’s gRPC schema/), + ).toBeInTheDocument(); + expect(call).not.toHaveBeenCalled(); +}); + +test('failed dismissal keeps the saved result and displays the storage error', () => { + localStorage.setItem( + 'splice:' + channel.channel_id, + JSON.stringify({ + direction: 'splicein', + amount: '1', + funding: 'previous', + txid: channel.funding_txid, + }), + ); + render(); + const spy = jest.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { + throw Error('storage'); + }); + fireEvent.click(screen.getByRole('button', { name: 'Splice confirmed — dismiss result' })); + expect(screen.getByText(/Could not dismiss the saved splice record/)).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'Splice confirmed — dismiss result' }), + ).toBeInTheDocument(); + expect(call).not.toHaveBeenCalled(); + spy.mockRestore(); +}); diff --git a/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.tsx b/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.tsx new file mode 100644 index 00000000..344d6064 --- /dev/null +++ b/apps/frontend/src/components/cln/ChannelDetails/SpliceChannel.tsx @@ -0,0 +1,294 @@ +import { useRef, useState } from 'react'; +import { Alert, Form, InputGroup } from 'react-bootstrap'; +import { HttpService } from '../../../services/http.service'; + +// Keep an unresolved submission visible even after closing the channel drawer. +export default function SpliceChannel({ channel }) { + const key = 'splice:' + channel.channel_id; + const [direction, setDirection] = useState('splicein'); + const [amount, setAmount] = useState(''); + const [review, setReview] = useState(false); + const [record, setRecord] = useState(() => { + try { + const raw = localStorage.getItem(key); + if (!raw) return null; + const value = JSON.parse(raw); + if ( + !value || + !['splicein', 'spliceout'].includes(value.direction) || + typeof value.amount !== 'string' || + typeof value.funding !== 'string' + ) + throw new Error('Invalid saved splice'); + return value; + } catch { + return { storageError: true }; + } + }); + const [settled, setSettled] = useState(false); + const [aborted, setAborted] = useState(false); + const [status, setStatus] = useState(''); + const submitting = useRef(false); + const confirmed = + settled || + (!!record?.txid && channel.state === 'CHANNELD_NORMAL' && channel.funding_txid === record.txid); + const save = value => { + localStorage.setItem(key, JSON.stringify(value)); + setRecord(value); + }; + const valid = /^[1-9][0-9]{0,15}$/.test(amount) && Number.isSafeInteger(Number(amount)); + const available = + channel.state === 'CHANNELD_NORMAL' && + channel.peer_connected === true && + !channel.inflight?.length; + const submit = async () => { + if (!valid || !available || record || submitting.current) return; + submitting.current = true; + setReview(false); + const pending = { + direction, + amount, + funding: channel.funding_txid, + time: new Date().toISOString(), + }; + try { + save(pending); + } catch { + setStatus('Cannot save the splice record in this browser. No splice was submitted.'); + submitting.current = false; + return; + } + setStatus('Negotiating splice with the peer. Do not submit another splice.'); + try { + const result: any = await HttpService.clnCall(direction, { + channel: channel.channel_id, + amount, + }); + const completed = { + ...pending, + txid: result.txid, + result: result.txid + ? 'Broadcast; waiting for confirmations.' + : 'Node returned without a transaction ID; check channel status before retrying.', + }; + setRecord(completed); + try { + save(completed); + } catch { + setStatus( + 'The node replied, but the result could not be saved in this browser. Keep the transaction ID and check the node before another splice.', + ); + return; + } + setStatus(''); + } catch (error) { + setStatus(''); + const failed = { ...pending, error: String(error) }; + setRecord(failed); + try { + save(failed); + } catch { + setStatus( + 'Browser storage is unavailable. Check the node before submitting any further splice.', + ); + } + } finally { + submitting.current = false; + } + }; + const refresh = async () => { + try { + const result: any = await HttpService.clnCall('listpeerchannels', { id: channel.peer_id }); + const current = result.channels.find(c => c.channel_id === channel.channel_id); + if (!current) { + setStatus('Channel not found. Do not repeat the splice.'); + return; + } + setAborted( + !!record?.error && + current.state === 'CHANNELD_NORMAL' && + !current.inflight?.length && + current.funding_txid === record.funding, + ); + setSettled( + current.state === 'CHANNELD_NORMAL' && + !current.inflight?.length && + !!record?.txid && + current.funding_txid === record.txid, + ); + setStatus( + 'State: ' + + current.state + + '; capacity: ' + + (Number(current.total_msat) / 1000).toLocaleString() + + ' sats; funding transaction: ' + + current.funding_txid + + '; pending splices: ' + + (current.inflight?.length || 0), + ); + } catch (error) { + setStatus('Status check failed: ' + String(error)); + } + }; + const dismiss = (archive = false) => { + try { + if (archive) { + let history: any[] = []; + try { + const stored = JSON.parse(localStorage.getItem(key + ':history') || '[]'); + if (Array.isArray(stored)) history = stored; + } catch { + /* Keep the current record in the replacement history. */ + } + localStorage.setItem(key + ':history', JSON.stringify([...history, record].slice(-20))); + } + localStorage.removeItem(key); + setRecord(null); + setAborted(false); + setSettled(false); + setStatus(''); + } catch { + setStatus( + 'Could not dismiss the saved splice record. It has been kept; no new splice was submitted.', + ); + } + }; + if (record?.storageError) + return ( + + The saved splice record cannot be read. Check the node’s channel and wallet history before + attempting another splice. + + ); + if (channel.splice_supported === false) + return ( +

+ Splicing requires a REST or Commando connection. It is unavailable through this + application’s gRPC schema. +

+ ); + if (!record && channel.state === 'CHANNELD_AWAITING_SPLICE') return null; + return ( +
+
Splice channel
+

+ Add on-chain funds or withdraw local funds without closing the channel. Both nodes must + support splicing. +

+ {record ? ( + +
+ {record.direction === 'splicein' ? 'Splice in' : 'Splice out'}:{' '} + {Number(record.amount).toLocaleString()} sats +
+
{record.time}
+
+ {confirmed + ? 'Splice confirmed.' + : record.error || record.result || 'Submission in progress or outcome unknown.'} +
+ {record.txid && ( +
Transaction: {record.txid}
+ )} +

+ Check the channel and transaction before any further splice. A lost reply does not mean + it failed. +

+ + {aborted && ( +
+

+ The node reports the original funding transaction and no pending splice. Check + wallet transactions and allow outstanding node operations to finish before + dismissing this record. A missing inflight entry alone does not prove a lost request + failed. +

+ +
+ )} + {confirmed && ( + + )} +
+ ) : ( + <> + + Direction + + + { + setDirection(e.target.value); + setReview(false); + }} + > + + + + + + Amount in sats + + + { + setAmount(e.target.value); + setReview(false); + }} + /> + +

+ {direction === 'splicein' + ? 'The network fee is paid separately from the on-chain wallet.' + : 'The network fee is also deducted from channel funds.'}{' '} + Core Lightning selects the fee rate with its normal fee safety checks. +

+ {!available && ( +

Connect the peer and wait for the channel to become active before splicing.

+ )} + {review ? ( + +

+ Confirm {direction === 'splicein' ? 'adding' : 'withdrawing'}{' '} + {Number(amount).toLocaleString()} sats {direction === 'splicein' ? 'to' : 'from'}{' '} + this channel, plus the network fee? +

+ + +
+ ) : ( + + )} + + )} + {status && ( +

+ {status} +

+ )} +
+ ); +} diff --git a/apps/frontend/src/components/cln/ChannelDetails/SpliceStatus.tsx b/apps/frontend/src/components/cln/ChannelDetails/SpliceStatus.tsx new file mode 100644 index 00000000..bc032ae3 --- /dev/null +++ b/apps/frontend/src/components/cln/ChannelDetails/SpliceStatus.tsx @@ -0,0 +1,50 @@ +export default function SpliceStatus({ channel, detailed = false }) { + if (channel.state !== 'CHANNELD_AWAITING_SPLICE') return null; + const pending = channel.pending_splices || []; + return ( +
+ {pending.length ? ( + pending.map(splice => ( +
+
+ Splice pending: {splice.delta > 0 ? '+' : ''} + {splice.delta.toLocaleString()} sats +
+
+ {splice.confirmations === null + ? 'Confirmation count unavailable' + : splice.confirmations === 0 + ? '0 confirmations · waiting to be mined' + : splice.confirmations.toLocaleString() + + (splice.confirmations === 1 ? ' confirmation' : ' confirmations') + + ' · waiting for both peers to lock the splice'} +
+ {detailed && ( + <> +
+ Channel capacity after splice: {splice.capacity.toLocaleString()} sats +
+
+ Splice transaction: {splice.txid} +
+ + )} +
+ )) + ) : ( +
+ Splice pending · waiting for both peers to lock the splice +
+ )} + {detailed && ( +
+ Balances above show the current funding. The new capacity is pending. The peer’s required + confirmation count is not reported by Core Lightning. +
+ )} + {channel.splice_status_error && ( +
Confirmation lookup failed: {channel.splice_status_error}
+ )} +
+ ); +} diff --git a/apps/frontend/src/components/cln/Channels/Channels.scss b/apps/frontend/src/components/cln/Channels/Channels.scss index aa5069fe..c03f959f 100644 --- a/apps/frontend/src/components/cln/Channels/Channels.scss +++ b/apps/frontend/src/components/cln/Channels/Channels.scss @@ -3,6 +3,18 @@ .channels-scroll-container { overflow: hidden; + min-width: 0; + & .list-item-div { + min-width: 0; + max-width: 100%; + } + & .channel-peer-name { + overflow-wrap: anywhere; + } + & .list-item-channel { + min-width: 0; + max-width: 100%; + } & .scrollbar-container.ps.ps--active-y .list-channels { & .list-item-channel { margin-right: 0.5rem; diff --git a/apps/frontend/src/components/cln/Channels/Channels.test.tsx b/apps/frontend/src/components/cln/Channels/Channels.test.tsx index fe7054fb..648abdbf 100644 --- a/apps/frontend/src/components/cln/Channels/Channels.test.tsx +++ b/apps/frontend/src/components/cln/Channels/Channels.test.tsx @@ -1,5 +1,6 @@ import { screen } from '@testing-library/react'; import Channels from './Channels'; +import { localLiquidityPercent } from '../../../utilities/channel-status'; import { mockAppStore, mockBKPRStoreData, mockCLNStoreData, mockListChannels, mockRootStoreData } from '../../../utilities/test-utilities/mockData'; import { renderWithProviders } from '../../../utilities/test-utilities/mockStore'; @@ -71,3 +72,15 @@ describe('Channels component ', () => { }) }); + +describe('channel liquidity proportions', () => { + it('keeps small and large channels on the same percentage scale', () => { + expect(localLiquidityPercent(75, 25)).toBe(75); + expect(localLiquidityPercent(7500000, 2500000)).toBe(75); + expect(localLiquidityPercent(0, 10000000)).toBe(0); + expect(localLiquidityPercent(10000000, 0)).toBe(100); + expect(localLiquidityPercent(0, 0)).toBe(0); + expect(localLiquidityPercent(NaN, 100)).toBe(0); + expect(localLiquidityPercent(-1, 100)).toBe(0); + }); +}); diff --git a/apps/frontend/src/components/cln/Channels/Channels.tsx b/apps/frontend/src/components/cln/Channels/Channels.tsx index e60274b1..1385030c 100755 --- a/apps/frontend/src/components/cln/Channels/Channels.tsx +++ b/apps/frontend/src/components/cln/Channels/Channels.tsx @@ -1,4 +1,6 @@ +import { localLiquidityPercent } from '../../../utilities/channel-status'; import './Channels.scss'; +import SpliceStatus from '../ChannelDetails/SpliceStatus'; import { motion } from 'framer-motion'; import PerfectScrollbar from 'react-perfect-scrollbar'; import { Spinner, Card, Row, Col, ListGroup, Alert, ProgressBar, OverlayTrigger, Tooltip } from 'react-bootstrap'; @@ -34,7 +36,7 @@ const Channels = (props) => { {listChannels.mergedChannels.map((channel, idx) => ( (props.onChannelClick(channel))} @@ -47,15 +49,16 @@ const Channels = (props) => { delay={{ show: 250, hide: 250 }} overlay={{titleCase(channel.current_state) + ' - ' + (channelStateMap[channel.state] ?? titleCase(channel.state?.replaceAll('_', ' ')))}} > - +
- {channel.node_alias} + {channel.channel_label || channel.node_alias || channel.peer_id}
+ - 1000000 || channel.to_them_sat > 1000000) ? (channel.to_us_sat / 1000) : channel.to_us_sat} key={1} /> - 1000000 || channel.to_them_sat > 1000000) ? (channel.to_them_sat / 1000) : channel.to_them_sat} key={2} /> + + diff --git a/apps/frontend/src/components/cln/ChannelsCard/ChannelsCard.tsx b/apps/frontend/src/components/cln/ChannelsCard/ChannelsCard.tsx index d53af4da..b878f6d2 100755 --- a/apps/frontend/src/components/cln/ChannelsCard/ChannelsCard.tsx +++ b/apps/frontend/src/components/cln/ChannelsCard/ChannelsCard.tsx @@ -1,5 +1,7 @@ import './ChannelsCard.scss'; import { useState } from 'react'; +import { useSelector } from 'react-redux'; +import { selectListChannels } from '../../../store/rootSelectors'; import { motion, AnimatePresence } from 'framer-motion'; import { Card } from 'react-bootstrap'; @@ -12,6 +14,8 @@ import { PeerChannel } from '../../../types/root.type'; const ChannelsCard = () => { const [selChannelCard, setSelChannelCard] = useState('channels'); const [selChannel, setSelChannel] = useState(null); + const channels = useSelector(selectListChannels); + const liveChannel = channels.mergedChannels?.find(c => c.channel_id === selChannel?.channel_id) || selChannel; const [newlyOpenedChannelId, setNewlyOpenedChannelId] = useState(''); const onCloseHandler = channelId => { @@ -38,7 +42,7 @@ const ChannelsCard = () => { ) : selChannelCard === 'details' ? ( setSelChannelCard('channels')} - selChannel={selChannel} + selChannel={liveChannel} onChannelStateChange={(newState) => setSelChannel(prev => prev ? { ...prev, current_state: newState } as PeerChannel : null )} diff --git a/apps/frontend/src/components/modals/NodeInfo/NodeInfo.tsx b/apps/frontend/src/components/modals/NodeInfo/NodeInfo.tsx index b169e27f..5209d8f8 100755 --- a/apps/frontend/src/components/modals/NodeInfo/NodeInfo.tsx +++ b/apps/frontend/src/components/modals/NodeInfo/NodeInfo.tsx @@ -1,5 +1,6 @@ import './NodeInfo.scss'; import { useEffect, useState } from 'react'; +import { nodeUris } from '../../../utilities/channel-status'; import { motion, AnimatePresence } from 'framer-motion'; import { QRCodeCanvas } from 'qrcode.react'; import { Modal, Row, InputGroup, Form } from 'react-bootstrap'; @@ -20,20 +21,15 @@ const NodeInfo = () => { const [nodeURI, setNodeURI] = useState(''); useEffect(() => { - let uri = (nodeInfo.id || ''); - if (nodeInfo.address && nodeInfo.address?.length && nodeInfo.address.length > 0) { - uri = uri + '@' + nodeInfo.address[0].address + ':' + nodeInfo.address[0].port; - } else if (nodeInfo.binding && nodeInfo.binding?.length && nodeInfo.binding.length > 0) { - uri = uri + '@' + nodeInfo.binding[0].address + ':' + nodeInfo.binding[0].port; - } else { - uri = uri + '@ : '; - } - setNodeURI(uri); + const uris = nodeUris(nodeInfo.id || '', nodeInfo.address || []); + setNodeURI(previous => uris.includes(previous) ? previous : (uris[0] || '')); }, [nodeInfo]); + const uris = nodeUris(nodeInfo.id || '', nodeInfo.address || []); + const copyHandler = () => { - copyTextToClipboard(nodeURI).then(() => { - dispatch(setShowToast({show: true, message: 'Node ID Copied Successfully!', bg: 'success'})); + copyTextToClipboard(nodeURI || nodeInfo.id || '').then(() => { + dispatch(setShowToast({show: true, message: nodeURI ? 'Node URI copied' : 'Node ID copied', bg: 'success'})); }).catch((err) => { logger.error(err); }); @@ -49,7 +45,7 @@ const NodeInfo = () => { - + {nodeURI && { /> - + } -

Node ID

+

{nodeURI ? 'Node URI' : 'Node ID'}

- Other Lightning nodes can open payment channels to your node following this Node ID. + {nodeURI ? 'Use this URI to connect to your node. LAN addresses require access to the same network or VPN.' : 'No reachable peer address is configured. Configure an advertised address on your Core Lightning node. A node ID alone is not a connection endpoint.'}

+ {uris.length > 1 && setNodeURI(event.target.value)}> + {uris.map(uri => )} + }
- ( nodes.nodes?.map(node => [node.nodeid, node]) || [] ); + let txRows: any[][] | null = null; + let tip: number | null = null; + let spliceStatusError: string | null = null; + if (peerChannels.channels?.some(channel => channel.state === 'CHANNELD_AWAITING_SPLICE')) { + try { + const txids = peerChannels.channels.flatMap(channel => (channel.inflight || []).map(f => f.funding_txid)).filter(txid => typeof txid === 'string' && /^[0-9a-f]{64}$/i.test(txid)); + if (!txids.length) throw new Error('Pending splice transaction ID unavailable'); + const [transactions, info]: [any, any] = await Promise.all([ + HttpService.clnCall('sql', { query: "SELECT hash, blockheight FROM transactions WHERE hash IN (" + [...new Set(txids)].map(txid => "'" + txid + "'").join(',') + ")" }), + HttpService.clnCall('getinfo') + ]); + if (!Array.isArray(transactions.rows) || !Number.isInteger(info.blockheight)) throw new Error('Invalid confirmation response from node'); + txRows = transactions.rows; + tip = info.blockheight; + } catch (error) { spliceStatusError = String(error); } + } const merged = peerChannels.channels?.map(channel => ({ ...channel, - node_alias: nodesMap.get(channel.peer_id)?.alias ?? '' + node_alias: nodesMap.get(channel.peer_id)?.alias ?? '', + node_uris: nodeUris(channel.peer_id, nodesMap.get(channel.peer_id)?.addresses), + pending_splices: pendingSplices(channel, txRows, tip), + splice_status_error: spliceStatusError })) || []; return { channels: merged }; // // No pagination, need full data for active, pending and inactive channels calculations diff --git a/apps/frontend/src/store/rootSlice.tsx b/apps/frontend/src/store/rootSlice.tsx index 1d971e16..cdc4bf4f 100644 --- a/apps/frontend/src/store/rootSlice.tsx +++ b/apps/frontend/src/store/rootSlice.tsx @@ -121,6 +121,13 @@ const rootSlice = createSlice({ const aggr = aggregatePeerChannels(listChannels); state.listChannels = { ...aggr, isLoading: false }; }, + setChannelLabel(state, action: PayloadAction<{channel_id: string; label: string}>) { + for (const key of ['mergedChannels', 'activeChannels', 'pendingChannels', 'inactiveChannels'] as const) { + for (const channel of state.listChannels[key]) { + if (channel.channel_id === action.payload.channel_id) channel.channel_label = action.payload.label; + } + } + }, clearRootStore(state) { return { ...defaultRootState, appConfig: state.appConfig }; }, @@ -138,6 +145,7 @@ export const { setNodeInfo, setListFunds, setListChannels, + setChannelLabel, clearRootStore, } = rootSlice.actions; diff --git a/apps/frontend/src/types/root.type.ts b/apps/frontend/src/types/root.type.ts index 968cc30c..474c0a83 100755 --- a/apps/frontend/src/types/root.type.ts +++ b/apps/frontend/src/types/root.type.ts @@ -176,7 +176,13 @@ export type ChannelType = { }; export type PeerChannel = { + node_uris?: string[]; + pending_splices?: { txid: string; delta: number; capacity: number; confirmations: number | null }[]; + splice_status_error?: string | null; node_alias: string; + channel_label?: string; + channel_label_error?: string; + splice_supported?: boolean; peer_id: string; channel_id: string; short_channel_id?: string; diff --git a/apps/frontend/src/utilities/channel-status.test.ts b/apps/frontend/src/utilities/channel-status.test.ts new file mode 100644 index 00000000..55032d4a --- /dev/null +++ b/apps/frontend/src/utilities/channel-status.test.ts @@ -0,0 +1,55 @@ +import { nodeUris, pendingSplices } from './channel-status'; + +const id = '02' + 'a'.repeat(64); +test('only advertised listening endpoints become node URIs, including IPv6 and Tor', () => { + expect( + nodeUris(id, [ + { type: 'ipv4', address: '192.168.8.102', port: 9735 }, + { type: 'ipv6', address: '2001:db8::1', port: 9735 }, + { type: 'torv3', address: 'a'.repeat(56) + '.onion', port: 9735 }, + { type: 'ipv4', address: '127.0.0.1', port: 0 }, + { type: 'ipv4', address: '0.0.0.0', port: 9735 }, + { type: 'ipv6', address: '::', port: 9735 }, + { type: 'ipv4', address: '127.0.0.1', port: 9735 }, + { type: 'websocket', address: 'unknown', port: 9735 }, + ]), + ).toEqual([ + id + '@192.168.8.102:9735', + id + '@[2001:db8::1]:9735', + id + '@' + 'a'.repeat(56) + '.onion:9735', + ]); + expect(nodeUris(id)).toEqual([]); + expect(nodeUris('invalid', [{ type: 'ipv4', address: '127.0.0.1', port: 9735 }])).toEqual([]); +}); +const channel = { + state: 'CHANNELD_AWAITING_SPLICE', + total_msat: 9999834000, + inflight: [{ funding_txid: 'tx', total_funding_msat: 10999834000 }], +}; +test('pending amount and confirmations come from node state without browser history', () => { + expect(pendingSplices(channel, [['tx', 0]], 100)[0]).toEqual({ + txid: 'tx', + delta: 1000000, + capacity: 10999834, + confirmations: 0, + }); + expect(pendingSplices(channel, [['tx', 98]], 100)[0].confirmations).toBe(3); + expect(pendingSplices(channel, null, null)[0].confirmations).toBeNull(); + expect(pendingSplices(channel, [], 100)[0].confirmations).toBeNull(); + expect(pendingSplices({ ...channel, state: 'CHANNELD_NORMAL' }, [['tx', 98]], 100)).toEqual([]); + expect(pendingSplices({ ...channel, total_msat: 11999834000 }, [['tx', 98]], 100)[0].delta).toBe( + -1000000, + ); +}); + +test('node connection URIs preserve advertised external port and never use a wildcard', () => { + expect(nodeUris(id, [{ type: 'ipv4', address: '192.168.8.102', port: 64774 }])).toEqual([ + id + '@192.168.8.102:64774', + ]); + expect(nodeUris(id, [{ type: 'ipv4', address: '0.0.0.0', port: 9735 }])).toEqual([]); +}); + +test('invalid block heights never become fabricated confirmation counts', () => { + expect(pendingSplices(channel, [['tx', 'unknown']], 100)[0].confirmations).toBeNull(); + expect(pendingSplices(channel, [['tx', -1]], 100)[0].confirmations).toBeNull(); +}); diff --git a/apps/frontend/src/utilities/channel-status.ts b/apps/frontend/src/utilities/channel-status.ts new file mode 100644 index 00000000..a92fbe11 --- /dev/null +++ b/apps/frontend/src/utilities/channel-status.ts @@ -0,0 +1,65 @@ +import { Address } from '../types/root.type'; + +export function nodeUris(id: string, addresses: Address[] = []): string[] { + if (!/^(02|03)[0-9a-f]{64}$/i.test(id)) return []; + return [ + ...new Set( + addresses + .filter( + a => + ['ipv4', 'ipv6', 'torv3', 'dns'].includes(a.type || '') && + typeof a.address === 'string' && + !['0.0.0.0', '::', '[::]', '::1', '[::1]', 'localhost'].includes( + a.address.toLowerCase(), + ) && + !a.address.startsWith('127.') && + /^[a-z0-9.:[\]-]+$/i.test(a.address) && + Number.isInteger(a.port) && + a.port! > 0 && + a.port! <= 65535, + ) + .map(a => { + const host = + a.address!.includes(':') && !a.address!.startsWith('[') + ? '[' + a.address + ']' + : a.address; + return id + '@' + host + ':' + a.port; + }), + ), + ]; +} + +export function pendingSplices(channel: any, rows: any[][] | null, tip: number | null) { + if (channel.state !== 'CHANNELD_AWAITING_SPLICE') return []; + return (channel.inflight || []).map((f: any) => { + const row = rows?.find(row => row[0] === f.funding_txid); + const height = row ? Number(row[1]) : null; + const confirmations = + height !== null && + Number.isInteger(height) && + height >= 0 && + tip !== null && + Number.isInteger(tip) && + tip >= 0 + ? height > 0 + ? Math.max(0, tip - height + 1) + : 0 + : null; + const capacity = Number(f.total_funding_msat) / 1000; + return { + txid: f.funding_txid, + delta: capacity - Number(channel.total_msat) / 1000, + capacity, + confirmations, + }; + }); +} + +// Balances are sats, while ProgressBar expects a percentage. Normalize before +// rendering so large channels and one-sided balances use the same scale. +export const localLiquidityPercent = (local: number, remote: number): number => { + const safeLocal = Number.isFinite(local) ? Math.max(0, local) : 0; + const safeRemote = Number.isFinite(remote) ? Math.max(0, remote) : 0; + const total = safeLocal + safeRemote; + return total > 0 ? (safeLocal / total) * 100 : 0; +};