Skip to content

Commit

Permalink
feat: different CLN amount switch for swap types (#807)
Browse files Browse the repository at this point in the history
  • Loading branch information
michael1011 authored Feb 4, 2025
1 parent c652b4f commit ea4e60e
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 51 deletions.
61 changes: 52 additions & 9 deletions lib/swap/NodeSwitch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Logger from '../Logger';
import { getHexString } from '../Utils';
import { getHexString, stringify } from '../Utils';
import { SwapType, swapTypeToPrettyString } from '../consts/Enums';
import ReverseSwap, {
NodeType,
Expand All @@ -12,8 +12,13 @@ import DecodedInvoice, { InvoiceType } from '../sidecar/DecodedInvoice';
import { Currency } from '../wallet/WalletManager';
import Errors from './Errors';

type NodeAmountThreshold = {
submarine: number;
reverse: number;
};

type NodeSwitchConfig = {
clnAmountThreshold?: number;
clnAmountThreshold?: number | Partial<NodeAmountThreshold>;

swapNode?: string;
referralsIds?: Record<string, string>;
Expand All @@ -25,7 +30,10 @@ class NodeSwitch {
private static readonly defaultClnAmountThreshold = 1_000_000;
private static readonly maxClnRetries = 1;

private readonly clnAmountThreshold: number;
private readonly clnAmountThreshold: {
[SwapType.Submarine]: number;
[SwapType.ReverseSubmarine]: number;
};
private readonly referralIds = new Map<string, NodeType>();

private readonly swapNode?: NodeType;
Expand All @@ -35,9 +43,37 @@ class NodeSwitch {
private readonly logger: Logger,
cfg?: NodeSwitchConfig,
) {
this.clnAmountThreshold =
cfg?.clnAmountThreshold || NodeSwitch.defaultClnAmountThreshold;
this.logger.info(`CLN invoice threshold: ${this.clnAmountThreshold} sat`);
if (cfg?.clnAmountThreshold !== undefined) {
if (typeof cfg.clnAmountThreshold === 'number') {
this.clnAmountThreshold = {
[SwapType.Submarine]: cfg.clnAmountThreshold,
[SwapType.ReverseSubmarine]: cfg.clnAmountThreshold,
};
} else {
this.clnAmountThreshold = {
[SwapType.Submarine]:
cfg.clnAmountThreshold.submarine ||
NodeSwitch.defaultClnAmountThreshold,
[SwapType.ReverseSubmarine]:
cfg.clnAmountThreshold.reverse ||
NodeSwitch.defaultClnAmountThreshold,
};
}
} else {
this.clnAmountThreshold = {
[SwapType.Submarine]: NodeSwitch.defaultClnAmountThreshold,
[SwapType.ReverseSubmarine]: NodeSwitch.defaultClnAmountThreshold,
};
}

this.logger.info(
`CLN invoice threshold: ${stringify({
[swapTypeToPrettyString(SwapType.Submarine)]:
this.clnAmountThreshold[SwapType.Submarine],
[swapTypeToPrettyString(SwapType.ReverseSubmarine)]:
this.clnAmountThreshold[SwapType.ReverseSubmarine],
})}`,
);

const swapNode =
cfg?.swapNode !== undefined
Expand Down Expand Up @@ -103,6 +139,7 @@ class NodeSwitch {
? NodeSwitch.switchOnNodeType(currency, preferredNode)
: this.switch(
currency,
SwapType.Submarine,
msatToSat(decoded.amountMsat),
swap.referral,
)
Expand Down Expand Up @@ -155,7 +192,12 @@ class NodeSwitch {
): { nodeType: NodeType; lightningClient: LightningClient } => {
const client = NodeSwitch.fallback(
currency,
this.switch(currency, holdInvoiceAmount, referralId),
this.switch(
currency,
SwapType.ReverseSubmarine,
holdInvoiceAmount,
referralId,
),
);
this.logger.debug(
`Using node ${client.serviceName()} for Reverse Swap ${id}`,
Expand All @@ -167,8 +209,9 @@ class NodeSwitch {
};
};

public switch = (
private switch = (
currency: Currency,
swapType: SwapType.Submarine | SwapType.ReverseSubmarine,
amount?: number,
referralId?: string,
): LightningClient => {
Expand All @@ -184,7 +227,7 @@ class NodeSwitch {

return NodeSwitch.fallback(
currency,
(amount || 0) > this.clnAmountThreshold
(amount || 0) > this.clnAmountThreshold[swapType]
? currency.lndClient
: currency.clnClient,
);
Expand Down
128 changes: 86 additions & 42 deletions test/unit/swap/NodeSwitch.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { randomBytes } from 'crypto';
import Logger from '../../../lib/Logger';
import { getHexString } from '../../../lib/Utils';
import { SwapType } from '../../../lib/consts/Enums';
import LightningPayment from '../../../lib/db/models/LightningPayment';
import ReverseSwap, { NodeType } from '../../../lib/db/models/ReverseSwap';
import Swap from '../../../lib/db/models/Swap';
Expand Down Expand Up @@ -49,52 +50,87 @@ describe('NodeSwitch', () => {
} as unknown as Currency;
});

test.each`
config
${undefined}
${{}}
`('should handle empty config', ({ config }) => {
const ns = new NodeSwitch(Logger.disabledLogger, config);
expect(ns['clnAmountThreshold']).toEqual(
NodeSwitch['defaultClnAmountThreshold'],
);
expect(ns['referralIds'].size).toEqual(0);
});
describe('constructor', () => {
test.each`
config
${undefined}
${{}}
`('should handle empty config', ({ config }) => {
const ns = new NodeSwitch(Logger.disabledLogger, config);
expect(ns['clnAmountThreshold']).toEqual({
[SwapType.Submarine]: NodeSwitch['defaultClnAmountThreshold'],
[SwapType.ReverseSubmarine]: NodeSwitch['defaultClnAmountThreshold'],
});
expect(ns['referralIds'].size).toEqual(0);
});

test('should parse config', () => {
const nodeOne =
'026165850492521f4ac8abd9bd8088123446d126f648ca35e60f88177dc149ceb2';
const nodeTwo =
'02d96eadea3d780104449aca5c93461ce67c1564e2e1d73225fa67dd3b997a6018'.toUpperCase();

const config = {
clnAmountThreshold: 21,
swapNode: 'LND',
referralsIds: {
test: 'CLN',
breez: 'LND',
other: 'notFound',
},
preferredForNode: {
[nodeOne]: 'LND',
[nodeTwo]: 'CLN',
unparseable: 'notFound',
},
};
const ns = new NodeSwitch(Logger.disabledLogger, config);
test('should parse config with clnAmountThreshold as number', () => {
const nodeOne =
'026165850492521f4ac8abd9bd8088123446d126f648ca35e60f88177dc149ceb2';
const nodeTwo =
'02d96eadea3d780104449aca5c93461ce67c1564e2e1d73225fa67dd3b997a6018'.toUpperCase();

expect(ns['clnAmountThreshold']).toEqual(config.clnAmountThreshold);
expect(ns['swapNode']).toEqual(NodeType.LND);
const config = {
clnAmountThreshold: 21,
swapNode: 'LND',
referralsIds: {
test: 'CLN',
breez: 'LND',
other: 'notFound',
},
preferredForNode: {
[nodeOne]: 'LND',
[nodeTwo]: 'CLN',
unparseable: 'notFound',
},
};
const ns = new NodeSwitch(Logger.disabledLogger, config);

const referrals = ns['referralIds'];
expect(referrals.size).toEqual(2);
expect(referrals.get('test')).toEqual(NodeType.CLN);
expect(referrals.get('breez')).toEqual(NodeType.LND);
expect(ns['clnAmountThreshold']).toEqual({
[SwapType.Submarine]: config.clnAmountThreshold,
[SwapType.ReverseSubmarine]: config.clnAmountThreshold,
});
expect(ns['swapNode']).toEqual(NodeType.LND);

const preferredNodes = ns['preferredForNode'];
expect(preferredNodes.size).toEqual(2);
expect(preferredNodes.get(nodeOne)).toEqual(NodeType.LND);
expect(preferredNodes.get(nodeTwo.toLowerCase())).toEqual(NodeType.CLN);
const referrals = ns['referralIds'];
expect(referrals.size).toEqual(2);
expect(referrals.get('test')).toEqual(NodeType.CLN);
expect(referrals.get('breez')).toEqual(NodeType.LND);

const preferredNodes = ns['preferredForNode'];
expect(preferredNodes.size).toEqual(2);
expect(preferredNodes.get(nodeOne)).toEqual(NodeType.LND);
expect(preferredNodes.get(nodeTwo.toLowerCase())).toEqual(NodeType.CLN);
});

test('should parse config with clnAmountThreshold as object', () => {
const config = {
clnAmountThreshold: {
submarine: 2_000_000,
reverse: 1_000_000,
},
};
const ns = new NodeSwitch(Logger.disabledLogger, config);

expect(ns['clnAmountThreshold']).toEqual({
[SwapType.Submarine]: config.clnAmountThreshold.submarine,
[SwapType.ReverseSubmarine]: config.clnAmountThreshold.reverse,
});
});

test('should parse config with clnAmountThreshold as object and coalesce undefined', () => {
const config = {
clnAmountThreshold: {
reverse: 1_000_000,
},
};
const ns = new NodeSwitch(Logger.disabledLogger, config);

expect(ns['clnAmountThreshold']).toEqual({
[SwapType.Submarine]: NodeSwitch['defaultClnAmountThreshold'],
[SwapType.ReverseSubmarine]: config.clnAmountThreshold.reverse,
});
});
});

test.each`
Expand All @@ -118,6 +154,10 @@ describe('NodeSwitch', () => {
await expect(
new NodeSwitch(Logger.disabledLogger, {
referralsIds: { breez: 'LND' },
clnAmountThreshold: {
submarine: 1_000_000,
reverse: 2_000_000,
},
}).getSwapNode(
currency,
{
Expand Down Expand Up @@ -262,6 +302,10 @@ describe('NodeSwitch', () => {
expect(
new NodeSwitch(Logger.disabledLogger, {
referralsIds: { breez: 'LND' },
clnAmountThreshold: {
submarine: 2_000_000,
reverse: 1_000_000,
},
}).getNodeForReverseSwap('', currency, amount, referral),
).toEqual({ nodeType: type, lightningClient: client });
},
Expand Down

0 comments on commit ea4e60e

Please sign in to comment.