@totemsdk/omnia-router 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/execute.d.ts +37 -0
- package/dist/execute.js +249 -0
- package/dist/graph.d.ts +32 -0
- package/dist/graph.js +95 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/pathfind.d.ts +25 -0
- package/dist/pathfind.js +247 -0
- package/dist/request.d.ts +19 -0
- package/dist/request.js +34 -0
- package/dist/types.d.ts +184 -0
- package/dist/types.js +9 -0
- package/package.json +48 -0
- package/src/__tests__/router.test.ts +877 -0
- package/src/execute.ts +329 -0
- package/src/graph.ts +109 -0
- package/src/index.ts +46 -0
- package/src/pathfind.ts +314 -0
- package/src/request.ts +48 -0
- package/src/types.ts +221 -0
|
@@ -0,0 +1,877 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createChannelGraph,
|
|
3
|
+
addChannel,
|
|
4
|
+
removeChannel,
|
|
5
|
+
announceSwap,
|
|
6
|
+
findRoute,
|
|
7
|
+
findCrossTokenRoute,
|
|
8
|
+
applyRate,
|
|
9
|
+
parseRateToScaled,
|
|
10
|
+
executeMultiHopPayment,
|
|
11
|
+
executeCrossTokenPayment,
|
|
12
|
+
cancelPayment,
|
|
13
|
+
buildPaymentRequest,
|
|
14
|
+
} from '../index';
|
|
15
|
+
import type {
|
|
16
|
+
RouterChannel,
|
|
17
|
+
ChannelGraphEdge,
|
|
18
|
+
ChannelOps,
|
|
19
|
+
RoutingHop,
|
|
20
|
+
LeaseProvider,
|
|
21
|
+
PaymentRequest,
|
|
22
|
+
CrossTokenRoute,
|
|
23
|
+
} from '../index';
|
|
24
|
+
|
|
25
|
+
// ─── Test helpers ─────────────────────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
const SCALE = 100_000_000n;
|
|
28
|
+
const TOKEN_A = '0x00';
|
|
29
|
+
const TOKEN_B = '0xBBBB';
|
|
30
|
+
|
|
31
|
+
const ALICE = 'pk-alice';
|
|
32
|
+
const BOB = 'pk-bob';
|
|
33
|
+
const CAROL = 'pk-carol';
|
|
34
|
+
const BRIDGE = 'pk-bridge';
|
|
35
|
+
|
|
36
|
+
const MOCK_LP: LeaseProvider = {};
|
|
37
|
+
|
|
38
|
+
function mkEdge(
|
|
39
|
+
id: string, from: string, to: string, tokenId: string, balance: bigint, feeRate = 100_000n,
|
|
40
|
+
): ChannelGraphEdge {
|
|
41
|
+
return { channelId: id, from, to, tokenId, availableBalance: balance, htlcCapacity: balance, feeRate };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function mkChannel(
|
|
45
|
+
id: string, from: string, to: string, tokenId = TOKEN_A, balance = 1000n * SCALE,
|
|
46
|
+
): RouterChannel {
|
|
47
|
+
return {
|
|
48
|
+
channelId: id,
|
|
49
|
+
tokenId,
|
|
50
|
+
parties: [
|
|
51
|
+
{ partyId: 'A', publicKeyDigest: from, addressIndex: 0 },
|
|
52
|
+
{ partyId: 'B', publicKeyDigest: to, addressIndex: 0 },
|
|
53
|
+
],
|
|
54
|
+
balances: { A: balance, B: 0n },
|
|
55
|
+
pendingHTLCs: [],
|
|
56
|
+
totalValue: balance,
|
|
57
|
+
currentSequence: 0,
|
|
58
|
+
status: 'active',
|
|
59
|
+
localSigner: { publicKeyDigest: from },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ─── Mock ChannelOps ──────────────────────────────────────────────────────────
|
|
64
|
+
|
|
65
|
+
function makeMockOps(overrides: Partial<ChannelOps> = {}): ChannelOps {
|
|
66
|
+
const addHTLC: ChannelOps['addHTLC'] = async (channel, params, _lp) => {
|
|
67
|
+
const htlcId = `htlc-${channel.channelId}-${channel.currentSequence + 1}`;
|
|
68
|
+
const senderPkd = channel.localSigner?.publicKeyDigest ?? channel.parties[0].publicKeyDigest;
|
|
69
|
+
const senderPartyId = channel.parties.find(p => p.publicKeyDigest === senderPkd)?.partyId ?? 'A';
|
|
70
|
+
const newBalances = { ...channel.balances };
|
|
71
|
+
newBalances[senderPartyId] = (newBalances[senderPartyId] ?? 0n) - params.amount;
|
|
72
|
+
const updatedChannel: RouterChannel = {
|
|
73
|
+
...channel,
|
|
74
|
+
balances: newBalances,
|
|
75
|
+
pendingHTLCs: [
|
|
76
|
+
...channel.pendingHTLCs,
|
|
77
|
+
{
|
|
78
|
+
htlcId,
|
|
79
|
+
amount: params.amount,
|
|
80
|
+
hashlock: params.hashlock,
|
|
81
|
+
timeoutBlock: params.timeoutBlock,
|
|
82
|
+
direction: params.direction,
|
|
83
|
+
status: 'pending',
|
|
84
|
+
htlcAddress: '0xhtlc',
|
|
85
|
+
senderPublicKeyDigest: senderPkd,
|
|
86
|
+
recipientPublicKeyDigest: params.counterpartPublicKeyDigest,
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
currentSequence: channel.currentSequence + 1,
|
|
90
|
+
};
|
|
91
|
+
return { channel: updatedChannel, htlcId };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const fulfillHTLC: ChannelOps['fulfillHTLC'] = async (channel, htlcId, _preimage, _lp) => {
|
|
95
|
+
const htlc = channel.pendingHTLCs.find(h => h.htlcId === htlcId);
|
|
96
|
+
if (!htlc) return { channel, error: `HTLC ${htlcId} not found` };
|
|
97
|
+
const recipPartyId = channel.parties.find(
|
|
98
|
+
p => p.publicKeyDigest === htlc.recipientPublicKeyDigest,
|
|
99
|
+
)?.partyId ?? 'B';
|
|
100
|
+
const newBalances = { ...channel.balances };
|
|
101
|
+
newBalances[recipPartyId] = (newBalances[recipPartyId] ?? 0n) + htlc.amount;
|
|
102
|
+
const updatedChannel: RouterChannel = {
|
|
103
|
+
...channel,
|
|
104
|
+
balances: newBalances,
|
|
105
|
+
pendingHTLCs: channel.pendingHTLCs.map(
|
|
106
|
+
h => h.htlcId === htlcId ? { ...h, status: 'fulfilled' as const } : h,
|
|
107
|
+
),
|
|
108
|
+
currentSequence: channel.currentSequence + 1,
|
|
109
|
+
};
|
|
110
|
+
return { channel: updatedChannel };
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const timeoutHTLC: ChannelOps['timeoutHTLC'] = async (channel, htlcId, _lp) => {
|
|
114
|
+
const htlc = channel.pendingHTLCs.find(h => h.htlcId === htlcId);
|
|
115
|
+
if (!htlc) return { channel, error: `HTLC ${htlcId} not found` };
|
|
116
|
+
const senderPartyId = channel.parties.find(
|
|
117
|
+
p => p.publicKeyDigest === htlc.senderPublicKeyDigest,
|
|
118
|
+
)?.partyId ?? 'A';
|
|
119
|
+
const newBalances = { ...channel.balances };
|
|
120
|
+
newBalances[senderPartyId] = (newBalances[senderPartyId] ?? 0n) + htlc.amount;
|
|
121
|
+
const updatedChannel: RouterChannel = {
|
|
122
|
+
...channel,
|
|
123
|
+
balances: newBalances,
|
|
124
|
+
pendingHTLCs: channel.pendingHTLCs.map(
|
|
125
|
+
h => h.htlcId === htlcId ? { ...h, status: 'timed_out' as const } : h,
|
|
126
|
+
),
|
|
127
|
+
currentSequence: channel.currentSequence + 1,
|
|
128
|
+
};
|
|
129
|
+
return { channel: updatedChannel };
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
return { addHTLC, fulfillHTLC, timeoutHTLC, ...overrides };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ─── 1. Graph management ──────────────────────────────────────────────────────
|
|
136
|
+
|
|
137
|
+
describe('ChannelGraph management', () => {
|
|
138
|
+
test('addChannel inserts directed edge', () => {
|
|
139
|
+
const g = createChannelGraph();
|
|
140
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE));
|
|
141
|
+
expect(g.edgesByChannel.has('c1')).toBe(true);
|
|
142
|
+
expect(g.edgesByChannel.get('c1')!.length).toBe(1);
|
|
143
|
+
expect(g.nodeEdges.get(ALICE)!.length).toBe(1);
|
|
144
|
+
expect(g.nodeEdges.has(BOB)).toBe(false);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('addChannel replaces an edge with the same (channelId, from) direction', () => {
|
|
148
|
+
const g = createChannelGraph();
|
|
149
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 100n));
|
|
150
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 999n));
|
|
151
|
+
expect(g.nodeEdges.get(ALICE)!.length).toBe(1);
|
|
152
|
+
const edges = g.edgesByChannel.get('c1')!;
|
|
153
|
+
expect(edges.length).toBe(1);
|
|
154
|
+
expect(edges[0].availableBalance).toBe(999n);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test('addChannel keeps both directed edges for a bidirectional channel', () => {
|
|
158
|
+
const g = createChannelGraph();
|
|
159
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n)); // Alice → Bob
|
|
160
|
+
addChannel(g, mkEdge('c1', BOB, ALICE, TOKEN_A, 200n)); // Bob → Alice
|
|
161
|
+
const edges = g.edgesByChannel.get('c1')!;
|
|
162
|
+
expect(edges.length).toBe(2);
|
|
163
|
+
// Both sender directions are present in nodeEdges
|
|
164
|
+
expect(g.nodeEdges.get(ALICE)!.length).toBe(1);
|
|
165
|
+
expect(g.nodeEdges.get(BOB)!.length).toBe(1);
|
|
166
|
+
// Updating one direction does not affect the other
|
|
167
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 777n));
|
|
168
|
+
const updated = g.edgesByChannel.get('c1')!;
|
|
169
|
+
expect(updated.length).toBe(2);
|
|
170
|
+
expect(updated.find(e => e.from === ALICE)!.availableBalance).toBe(777n);
|
|
171
|
+
expect(updated.find(e => e.from === BOB)!.availableBalance).toBe(200n);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test('removeChannel cleans up both maps (all directions)', () => {
|
|
175
|
+
const g = createChannelGraph();
|
|
176
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n));
|
|
177
|
+
addChannel(g, mkEdge('c1', BOB, ALICE, TOKEN_A, 200n));
|
|
178
|
+
removeChannel(g, 'c1');
|
|
179
|
+
expect(g.edgesByChannel.has('c1')).toBe(false);
|
|
180
|
+
expect(g.nodeEdges.has(ALICE)).toBe(false);
|
|
181
|
+
expect(g.nodeEdges.has(BOB)).toBe(false);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('announceSwap registers under tokenIn:tokenOut key', () => {
|
|
185
|
+
const g = createChannelGraph();
|
|
186
|
+
announceSwap(g, {
|
|
187
|
+
intermediaryPubKey: BRIDGE, tokenIn: TOKEN_A, tokenOut: TOKEN_B,
|
|
188
|
+
rate: '1.5', inboundChannelId: 'c1', outboundChannelId: 'c2',
|
|
189
|
+
maxAmountIn: 1000n * SCALE,
|
|
190
|
+
});
|
|
191
|
+
const anns = g.swapIndex.get(`${TOKEN_A}:${TOKEN_B}`)!;
|
|
192
|
+
expect(anns.length).toBe(1);
|
|
193
|
+
expect(anns[0].rate).toBe('1.5');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('announceSwap replaces duplicate intermediary+channel pair', () => {
|
|
197
|
+
const g = createChannelGraph();
|
|
198
|
+
const base = { intermediaryPubKey: BRIDGE, tokenIn: TOKEN_A, tokenOut: TOKEN_B,
|
|
199
|
+
inboundChannelId: 'c1', outboundChannelId: 'c2', maxAmountIn: 1000n * SCALE };
|
|
200
|
+
announceSwap(g, { ...base, rate: '1.0' });
|
|
201
|
+
announceSwap(g, { ...base, rate: '1.2' });
|
|
202
|
+
const anns = g.swapIndex.get(`${TOKEN_A}:${TOKEN_B}`)!;
|
|
203
|
+
expect(anns.length).toBe(1);
|
|
204
|
+
expect(anns[0].rate).toBe('1.2');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test('announceSwap rejects negative rate', () => {
|
|
208
|
+
const g = createChannelGraph();
|
|
209
|
+
expect(() => announceSwap(g, {
|
|
210
|
+
intermediaryPubKey: BRIDGE, tokenIn: TOKEN_A, tokenOut: TOKEN_B,
|
|
211
|
+
rate: '-0.5', inboundChannelId: 'c1', outboundChannelId: 'c2',
|
|
212
|
+
maxAmountIn: 1000n * SCALE,
|
|
213
|
+
})).toThrow(/rate/);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('announceSwap rejects zero rate', () => {
|
|
217
|
+
const g = createChannelGraph();
|
|
218
|
+
expect(() => announceSwap(g, {
|
|
219
|
+
intermediaryPubKey: BRIDGE, tokenIn: TOKEN_A, tokenOut: TOKEN_B,
|
|
220
|
+
rate: '0', inboundChannelId: 'c1', outboundChannelId: 'c2',
|
|
221
|
+
maxAmountIn: 1000n * SCALE,
|
|
222
|
+
})).toThrow(/rate/);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test('findCrossTokenRoute skips swap announcement with negative amountOut via adversarial graph edit', () => {
|
|
226
|
+
// Simulate an announcement that somehow has a negative rate after bypassing
|
|
227
|
+
// announceSwap (e.g. direct graph manipulation). findCrossTokenRoute must
|
|
228
|
+
// skip it via the amountOut <= 0n guard.
|
|
229
|
+
const g = createChannelGraph();
|
|
230
|
+
addChannel(g, mkEdge('in-chan', ALICE, BRIDGE, TOKEN_A, 5000n * SCALE));
|
|
231
|
+
addChannel(g, mkEdge('out-chan', BRIDGE, ALICE, TOKEN_B, 5000n * SCALE));
|
|
232
|
+
// Bypass announceSwap validation by writing directly to the swapIndex
|
|
233
|
+
g.swapIndex.set(`${TOKEN_A}:${TOKEN_B}`, [{
|
|
234
|
+
intermediaryPubKey: BRIDGE, tokenIn: TOKEN_A, tokenOut: TOKEN_B,
|
|
235
|
+
rate: '-1.0', inboundChannelId: 'in-chan', outboundChannelId: 'out-chan',
|
|
236
|
+
maxAmountIn: 1000n * SCALE,
|
|
237
|
+
}]);
|
|
238
|
+
const route = findCrossTokenRoute(g, ALICE, ALICE, 100n * SCALE, TOKEN_A, TOKEN_B);
|
|
239
|
+
expect(route).toBeNull();
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// ─── 2. Pathfinding ───────────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
describe('findRoute — single-token Dijkstra', () => {
|
|
246
|
+
test('finds direct single-hop route', () => {
|
|
247
|
+
const g = createChannelGraph();
|
|
248
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE));
|
|
249
|
+
const route = findRoute(g, ALICE, BOB, 100n * SCALE, TOKEN_A);
|
|
250
|
+
expect(route).not.toBeNull();
|
|
251
|
+
expect(route!.hops.length).toBe(1);
|
|
252
|
+
expect(route!.hops[0].channelId).toBe('c1');
|
|
253
|
+
expect(route!.tokenIn).toBe(TOKEN_A);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test('finds 3-hop route', () => {
|
|
257
|
+
const g = createChannelGraph();
|
|
258
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE));
|
|
259
|
+
addChannel(g, mkEdge('c2', BOB, CAROL, TOKEN_A, 500n * SCALE));
|
|
260
|
+
const route = findRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A);
|
|
261
|
+
expect(route).not.toBeNull();
|
|
262
|
+
expect(route!.hops.length).toBe(2);
|
|
263
|
+
expect(route!.hops[0].channelId).toBe('c1');
|
|
264
|
+
expect(route!.hops[1].channelId).toBe('c2');
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
test('returns null when no path exists', () => {
|
|
268
|
+
const g = createChannelGraph();
|
|
269
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE));
|
|
270
|
+
expect(findRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A)).toBeNull();
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
test('filters edge with insufficient balance', () => {
|
|
274
|
+
const g = createChannelGraph();
|
|
275
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 50n * SCALE));
|
|
276
|
+
expect(findRoute(g, ALICE, BOB, 100n * SCALE, TOKEN_A)).toBeNull();
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
test('filters edge with wrong tokenId', () => {
|
|
280
|
+
const g = createChannelGraph();
|
|
281
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_B, 500n * SCALE));
|
|
282
|
+
expect(findRoute(g, ALICE, BOB, 100n * SCALE, TOKEN_A)).toBeNull();
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
test('prefers lower-fee path', () => {
|
|
286
|
+
const g = createChannelGraph();
|
|
287
|
+
// Direct path: high fee
|
|
288
|
+
addChannel(g, { ...mkEdge('direct', ALICE, BOB, TOKEN_A, 500n * SCALE), feeRate: 1_000_000n });
|
|
289
|
+
// 2-hop path: low fee
|
|
290
|
+
addChannel(g, { ...mkEdge('via1', ALICE, CAROL, TOKEN_A, 500n * SCALE), feeRate: 1_000n });
|
|
291
|
+
addChannel(g, { ...mkEdge('via2', CAROL, BOB, TOKEN_A, 500n * SCALE), feeRate: 1_000n });
|
|
292
|
+
const route = findRoute(g, ALICE, BOB, 100n * SCALE, TOKEN_A);
|
|
293
|
+
expect(route).not.toBeNull();
|
|
294
|
+
expect(route!.hops[0].channelId).toBe('via1');
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
test('computes totalFees correctly', () => {
|
|
298
|
+
const g = createChannelGraph();
|
|
299
|
+
// feeRate = 100_000n per SCALE = 0.1%
|
|
300
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE, 100_000n));
|
|
301
|
+
// amount = 1 scaled unit so fee = 1 * SCALE * 100_000 / SCALE = 100_000
|
|
302
|
+
const amount = 1n * SCALE;
|
|
303
|
+
const route = findRoute(g, ALICE, BOB, amount, TOKEN_A);
|
|
304
|
+
expect(route!.totalFees).toBe(100_000n);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
describe('findCrossTokenRoute', () => {
|
|
309
|
+
function crossGraph() {
|
|
310
|
+
const g = createChannelGraph();
|
|
311
|
+
// Alice → Bridge in TOKEN_A
|
|
312
|
+
addChannel(g, mkEdge('in-chan', ALICE, BRIDGE, TOKEN_A, 1000n * SCALE));
|
|
313
|
+
// Bridge → Carol in TOKEN_B
|
|
314
|
+
addChannel(g, mkEdge('out-chan', BRIDGE, CAROL, TOKEN_B, 2000n * SCALE));
|
|
315
|
+
announceSwap(g, {
|
|
316
|
+
intermediaryPubKey: BRIDGE,
|
|
317
|
+
tokenIn: TOKEN_A,
|
|
318
|
+
tokenOut: TOKEN_B,
|
|
319
|
+
rate: '1.5',
|
|
320
|
+
inboundChannelId: 'in-chan',
|
|
321
|
+
outboundChannelId: 'out-chan',
|
|
322
|
+
maxAmountIn: 1000n * SCALE,
|
|
323
|
+
});
|
|
324
|
+
return g;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
test('returns null when no swap announcement exists for the token pair', () => {
|
|
328
|
+
const g = createChannelGraph();
|
|
329
|
+
addChannel(g, mkEdge('c1', ALICE, BOB, TOKEN_A, 500n * SCALE));
|
|
330
|
+
expect(findCrossTokenRoute(g, ALICE, BOB, 100n * SCALE, TOKEN_A, TOKEN_B)).toBeNull();
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
test('returns null when intermediary balance insufficient', () => {
|
|
334
|
+
const g = crossGraph();
|
|
335
|
+
const route = findCrossTokenRoute(g, ALICE, BRIDGE, 2000n * SCALE, TOKEN_A, TOKEN_B);
|
|
336
|
+
expect(route).toBeNull();
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
test('finds Alice→Bridge→Carol cross-token route', () => {
|
|
340
|
+
const g = crossGraph();
|
|
341
|
+
const route = findCrossTokenRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A, TOKEN_B);
|
|
342
|
+
expect(route).not.toBeNull();
|
|
343
|
+
expect(route!.swapHops.length).toBe(1);
|
|
344
|
+
const swap = route!.swapHops[0];
|
|
345
|
+
expect(swap.tokenIn).toBe(TOKEN_A);
|
|
346
|
+
expect(swap.tokenOut).toBe(TOKEN_B);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
test('route.hops contains only the SwapHop for direct Alice→Bridge→Carol path', () => {
|
|
350
|
+
const g = crossGraph();
|
|
351
|
+
const route = findCrossTokenRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A, TOKEN_B);
|
|
352
|
+
expect(route).not.toBeNull();
|
|
353
|
+
// No pre-swap or post-swap hops — Alice IS the inbound channel sender,
|
|
354
|
+
// Carol IS the outbound channel receiver.
|
|
355
|
+
expect(route!.hops.length).toBe(1);
|
|
356
|
+
expect((route!.hops[0] as any).isSwap).toBe(true);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
test('fee is NOT double-counted for direct swap path', () => {
|
|
360
|
+
const g = crossGraph();
|
|
361
|
+
const amountIn = 100n * SCALE;
|
|
362
|
+
const route = findCrossTokenRoute(g, ALICE, CAROL, amountIn, TOKEN_A, TOKEN_B);
|
|
363
|
+
expect(route).not.toBeNull();
|
|
364
|
+
// Expected: inboundFee + outboundFee (no duplication)
|
|
365
|
+
// feeRate = 100_000n (default), SCALE = 10^8
|
|
366
|
+
// inboundFee = 100 * SCALE * 100_000 / SCALE = 100 * 100_000 = 10_000_000
|
|
367
|
+
// amountOut = 150 * SCALE, outboundFee = 150 * SCALE * 100_000 / SCALE = 15_000_000
|
|
368
|
+
const expectedFees = 10_000_000n + 15_000_000n;
|
|
369
|
+
expect(route!.totalFees).toBe(expectedFees);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
test('rate application: amountOut = amountIn × rate', () => {
|
|
373
|
+
const g = crossGraph();
|
|
374
|
+
const amountIn = 100n * SCALE;
|
|
375
|
+
const route = findCrossTokenRoute(g, ALICE, CAROL, amountIn, TOKEN_A, TOKEN_B);
|
|
376
|
+
expect(route).not.toBeNull();
|
|
377
|
+
const swap = route!.swapHops[0];
|
|
378
|
+
// amountOut = 100 * 1.5 = 150 (in scaled units)
|
|
379
|
+
expect(swap.amountOut).toBe(150n * SCALE);
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
// ─── 3. Rate helpers ──────────────────────────────────────────────────────────
|
|
384
|
+
|
|
385
|
+
describe('parseRateToScaled / applyRate', () => {
|
|
386
|
+
test('parses "1.0" → SCALE', () => {
|
|
387
|
+
expect(parseRateToScaled('1.0')).toBe(100_000_000n);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
test('parses "0.95" → 95_000_000n', () => {
|
|
391
|
+
expect(parseRateToScaled('0.95')).toBe(95_000_000n);
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
test('parses "2" → 200_000_000n', () => {
|
|
395
|
+
expect(parseRateToScaled('2')).toBe(200_000_000n);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
test('applyRate: 1000 scaled × 1.5 rate = 1500 scaled', () => {
|
|
399
|
+
const amountIn = 1000n * SCALE;
|
|
400
|
+
expect(applyRate(amountIn, '1.5')).toBe(1500n * SCALE);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
test('applyRate: 1000 scaled × 0.95 rate = 950 scaled', () => {
|
|
404
|
+
expect(applyRate(1000n * SCALE, '0.95')).toBe(950n * SCALE);
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// ─── 4. buildPaymentRequest ───────────────────────────────────────────────────
|
|
409
|
+
|
|
410
|
+
describe('buildPaymentRequest', () => {
|
|
411
|
+
test('returns hashlock and preimage', () => {
|
|
412
|
+
const req = buildPaymentRequest(100n * SCALE, TOKEN_A, 1000n);
|
|
413
|
+
expect(req.hashlock).toMatch(/^0x[0-9a-f]{64}$/);
|
|
414
|
+
expect(req.preimage).toMatch(/^0x[0-9a-f]{64}$/);
|
|
415
|
+
expect(req.amount).toBe(100n * SCALE);
|
|
416
|
+
expect(req.tokenId).toBe(TOKEN_A);
|
|
417
|
+
expect(req.expiryBlock).toBe(1000n);
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
test('each call produces a distinct preimage', () => {
|
|
421
|
+
const r1 = buildPaymentRequest(1n, TOKEN_A, 100n);
|
|
422
|
+
const r2 = buildPaymentRequest(1n, TOKEN_A, 100n);
|
|
423
|
+
expect(r1.preimage).not.toBe(r2.preimage);
|
|
424
|
+
expect(r1.hashlock).not.toBe(r2.hashlock);
|
|
425
|
+
});
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
// ─── 5. executeMultiHopPayment ────────────────────────────────────────────────
|
|
429
|
+
|
|
430
|
+
describe('executeMultiHopPayment — 3-hop single-token payment', () => {
|
|
431
|
+
function setup() {
|
|
432
|
+
// Alice ──c1──> Hop1 ──c2──> Hop2 ──c3──> Carol
|
|
433
|
+
const HOP1 = 'pk-hop1', HOP2 = 'pk-hop2';
|
|
434
|
+
const g = createChannelGraph();
|
|
435
|
+
addChannel(g, mkEdge('c1', ALICE, HOP1, TOKEN_A, 1000n * SCALE));
|
|
436
|
+
addChannel(g, mkEdge('c2', HOP1, HOP2, TOKEN_A, 1000n * SCALE));
|
|
437
|
+
addChannel(g, mkEdge('c3', HOP2, CAROL, TOKEN_A, 1000n * SCALE));
|
|
438
|
+
|
|
439
|
+
const route = findRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A)!;
|
|
440
|
+
expect(route).not.toBeNull();
|
|
441
|
+
|
|
442
|
+
const channels: Map<string, RouterChannel> = new Map([
|
|
443
|
+
['c1', mkChannel('c1', ALICE, HOP1)],
|
|
444
|
+
['c2', mkChannel('c2', HOP1, HOP2)],
|
|
445
|
+
['c3', mkChannel('c3', HOP2, CAROL)],
|
|
446
|
+
]);
|
|
447
|
+
|
|
448
|
+
const lps: Map<string, LeaseProvider> = new Map([
|
|
449
|
+
['c1', MOCK_LP], ['c2', MOCK_LP], ['c3', MOCK_LP],
|
|
450
|
+
]);
|
|
451
|
+
|
|
452
|
+
const paymentReq = buildPaymentRequest(100n * SCALE, TOKEN_A, 1000n);
|
|
453
|
+
const ops = makeMockOps();
|
|
454
|
+
return { channels, lps, route, paymentReq, ops };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
test('succeeds: all HTLCs locked and fulfilled', async () => {
|
|
458
|
+
const { channels, lps, route, paymentReq, ops } = setup();
|
|
459
|
+
const result = await executeMultiHopPayment(ops, channels, route, paymentReq, lps);
|
|
460
|
+
expect(result.success).toBe(true);
|
|
461
|
+
expect(result.settledHops.length).toBe(3);
|
|
462
|
+
expect(result.preimage).toBe(paymentReq.preimage);
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
test('balances update correctly after payment', async () => {
|
|
466
|
+
const { channels, lps, route, paymentReq, ops } = setup();
|
|
467
|
+
await executeMultiHopPayment(ops, channels, route, paymentReq, lps);
|
|
468
|
+
// c1: Alice's balance should decrease by amount, then increase (fulfill)
|
|
469
|
+
// net: settled means Carol (B) received the funds on c3
|
|
470
|
+
const c3 = channels.get('c3')!;
|
|
471
|
+
const carolPartyId = c3.parties.find(p => p.publicKeyDigest === 'pk-carol')?.partyId ?? 'B';
|
|
472
|
+
expect(c3.balances[carolPartyId]).toBe(100n * SCALE);
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
test('fails with clear error when preimage is missing', async () => {
|
|
476
|
+
const { channels, lps, route, paymentReq, ops } = setup();
|
|
477
|
+
const reqWithoutPreimage: PaymentRequest = { ...paymentReq, preimage: undefined };
|
|
478
|
+
const result = await executeMultiHopPayment(ops, channels, route, reqWithoutPreimage, lps);
|
|
479
|
+
expect(result.success).toBe(false);
|
|
480
|
+
expect(result.error).toMatch(/preimage/);
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
test('fulfill-phase failure: still-pending HTLCs are timed out', async () => {
|
|
484
|
+
const { channels, lps, route, paymentReq } = setup();
|
|
485
|
+
|
|
486
|
+
// fulfillHTLC fails on the first call (which is the last hop, c3, reversed)
|
|
487
|
+
let fulfillCount = 0;
|
|
488
|
+
const timeoutCalls: string[] = [];
|
|
489
|
+
|
|
490
|
+
const failOps = makeMockOps({
|
|
491
|
+
async fulfillHTLC(channel, htlcId, preimage, lp) {
|
|
492
|
+
fulfillCount++;
|
|
493
|
+
if (fulfillCount === 1) throw new Error('simulated fulfill failure');
|
|
494
|
+
return makeMockOps().fulfillHTLC(channel, htlcId, preimage, lp);
|
|
495
|
+
},
|
|
496
|
+
async timeoutHTLC(channel, htlcId, lp) {
|
|
497
|
+
timeoutCalls.push(htlcId);
|
|
498
|
+
return makeMockOps().timeoutHTLC(channel, htlcId, lp);
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
const result = await executeMultiHopPayment(failOps, channels, route, paymentReq, lps);
|
|
503
|
+
expect(result.success).toBe(false);
|
|
504
|
+
// All 3 locked HTLCs should be timed out (none were fulfilled before the error)
|
|
505
|
+
expect(timeoutCalls.length).toBe(3);
|
|
506
|
+
expect(result.settledHops.length).toBe(0);
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
test('partial fulfill failure: only still-pending HTLCs are timed out', async () => {
|
|
510
|
+
const { channels, lps, route, paymentReq } = setup();
|
|
511
|
+
|
|
512
|
+
// fulfillHTLC succeeds for hop 1 (last, c3), fails for hop 2 (middle, c2)
|
|
513
|
+
let fulfillCount = 0;
|
|
514
|
+
const timeoutCalls: string[] = [];
|
|
515
|
+
const baseOps = makeMockOps();
|
|
516
|
+
|
|
517
|
+
const partialOps = makeMockOps({
|
|
518
|
+
async fulfillHTLC(channel, htlcId, preimage, lp) {
|
|
519
|
+
fulfillCount++;
|
|
520
|
+
if (fulfillCount === 2) throw new Error('mid-reveal failure');
|
|
521
|
+
return baseOps.fulfillHTLC(channel, htlcId, preimage, lp);
|
|
522
|
+
},
|
|
523
|
+
async timeoutHTLC(channel, htlcId, lp) {
|
|
524
|
+
timeoutCalls.push(htlcId);
|
|
525
|
+
return baseOps.timeoutHTLC(channel, htlcId, lp);
|
|
526
|
+
},
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
const result = await executeMultiHopPayment(partialOps, channels, route, paymentReq, lps);
|
|
530
|
+
expect(result.success).toBe(false);
|
|
531
|
+
// 1 hop was fulfilled (c3), 2 remain pending (c2, c1) → 2 timeouts
|
|
532
|
+
expect(result.settledHops.length).toBe(1);
|
|
533
|
+
expect(timeoutCalls.length).toBe(2);
|
|
534
|
+
});
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
describe('executeMultiHopPayment — middle hop failure', () => {
|
|
538
|
+
test('all previously locked HTLCs are timed out when a forward hop fails', async () => {
|
|
539
|
+
const HOP1 = 'pk-hop1';
|
|
540
|
+
const g = createChannelGraph();
|
|
541
|
+
addChannel(g, mkEdge('c1', ALICE, HOP1, TOKEN_A, 1000n * SCALE));
|
|
542
|
+
addChannel(g, mkEdge('c2', HOP1, CAROL, TOKEN_A, 1000n * SCALE));
|
|
543
|
+
|
|
544
|
+
const route = findRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A)!;
|
|
545
|
+
const channels: Map<string, RouterChannel> = new Map([
|
|
546
|
+
['c1', mkChannel('c1', ALICE, HOP1)],
|
|
547
|
+
['c2', mkChannel('c2', HOP1, CAROL)],
|
|
548
|
+
]);
|
|
549
|
+
const lps: Map<string, LeaseProvider> = new Map([
|
|
550
|
+
['c1', MOCK_LP], ['c2', MOCK_LP],
|
|
551
|
+
]);
|
|
552
|
+
|
|
553
|
+
const paymentReq = buildPaymentRequest(100n * SCALE, TOKEN_A, 1000n);
|
|
554
|
+
|
|
555
|
+
let addCallCount = 0;
|
|
556
|
+
const failingOps = makeMockOps({
|
|
557
|
+
async addHTLC(channel, params, lp) {
|
|
558
|
+
addCallCount++;
|
|
559
|
+
if (addCallCount === 2) throw new Error('simulated hop failure');
|
|
560
|
+
const base = makeMockOps();
|
|
561
|
+
return base.addHTLC(channel, params, lp);
|
|
562
|
+
},
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
const timeoutCalls: string[] = [];
|
|
566
|
+
const trackingOps: ChannelOps = {
|
|
567
|
+
...failingOps,
|
|
568
|
+
timeoutHTLC: async (channel, htlcId, lp) => {
|
|
569
|
+
timeoutCalls.push(htlcId);
|
|
570
|
+
return makeMockOps().timeoutHTLC(channel, htlcId, lp);
|
|
571
|
+
},
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const result = await executeMultiHopPayment(trackingOps, channels, route, paymentReq, lps);
|
|
575
|
+
expect(result.success).toBe(false);
|
|
576
|
+
// c1 HTLC (locked in hop 1) should have been timed out
|
|
577
|
+
expect(timeoutCalls.length).toBe(1);
|
|
578
|
+
expect(timeoutCalls[0]).toMatch(/c1/);
|
|
579
|
+
});
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
// ─── 6. cancelPayment ────────────────────────────────────────────────────────
|
|
583
|
+
|
|
584
|
+
describe('cancelPayment', () => {
|
|
585
|
+
test('times out all hops that have htlcId set', async () => {
|
|
586
|
+
const HOP1 = 'pk-hop1';
|
|
587
|
+
const g = createChannelGraph();
|
|
588
|
+
addChannel(g, mkEdge('c1', ALICE, HOP1, TOKEN_A, 1000n * SCALE));
|
|
589
|
+
addChannel(g, mkEdge('c2', HOP1, CAROL, TOKEN_A, 1000n * SCALE));
|
|
590
|
+
|
|
591
|
+
const channels: Map<string, RouterChannel> = new Map([
|
|
592
|
+
['c1', mkChannel('c1', ALICE, HOP1)],
|
|
593
|
+
['c2', mkChannel('c2', HOP1, CAROL)],
|
|
594
|
+
]);
|
|
595
|
+
const lps: Map<string, LeaseProvider> = new Map([
|
|
596
|
+
['c1', MOCK_LP], ['c2', MOCK_LP],
|
|
597
|
+
]);
|
|
598
|
+
|
|
599
|
+
const ops = makeMockOps();
|
|
600
|
+
// Manually populate htlcId on the route hops (simulating a partial execution)
|
|
601
|
+
const route = findRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A)!;
|
|
602
|
+
|
|
603
|
+
// Lock c1 only
|
|
604
|
+
const addResult = await ops.addHTLC(channels.get('c1')!, {
|
|
605
|
+
amount: 100n * SCALE, hashlock: '0xdeadbeef', timeoutBlock: 1000n,
|
|
606
|
+
direction: 'offered', counterpartPublicKeyDigest: HOP1,
|
|
607
|
+
}, MOCK_LP);
|
|
608
|
+
channels.set('c1', addResult.channel);
|
|
609
|
+
(route.hops[0] as RoutingHop).htlcId = addResult.htlcId;
|
|
610
|
+
|
|
611
|
+
const timeoutCalls: string[] = [];
|
|
612
|
+
const tracking: ChannelOps = {
|
|
613
|
+
...ops,
|
|
614
|
+
timeoutHTLC: async (ch, id, lp) => {
|
|
615
|
+
timeoutCalls.push(id);
|
|
616
|
+
return ops.timeoutHTLC(ch, id, lp);
|
|
617
|
+
},
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
await cancelPayment(tracking, channels, route, lps);
|
|
621
|
+
expect(timeoutCalls.length).toBe(1);
|
|
622
|
+
});
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
// ─── 7. Cross-token payment execution ────────────────────────────────────────
|
|
626
|
+
|
|
627
|
+
describe('executeCrossTokenPayment', () => {
|
|
628
|
+
function crossSetup() {
|
|
629
|
+
const g = createChannelGraph();
|
|
630
|
+
addChannel(g, mkEdge('in-chan', ALICE, BRIDGE, TOKEN_A, 1000n * SCALE));
|
|
631
|
+
addChannel(g, mkEdge('out-chan', BRIDGE, CAROL, TOKEN_B, 2000n * SCALE));
|
|
632
|
+
announceSwap(g, {
|
|
633
|
+
intermediaryPubKey: BRIDGE,
|
|
634
|
+
tokenIn: TOKEN_A,
|
|
635
|
+
tokenOut: TOKEN_B,
|
|
636
|
+
rate: '1.5',
|
|
637
|
+
inboundChannelId: 'in-chan',
|
|
638
|
+
outboundChannelId: 'out-chan',
|
|
639
|
+
maxAmountIn: 1000n * SCALE,
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
const route = findCrossTokenRoute(g, ALICE, CAROL, 100n * SCALE, TOKEN_A, TOKEN_B) as CrossTokenRoute;
|
|
643
|
+
expect(route).not.toBeNull();
|
|
644
|
+
|
|
645
|
+
const channels: Map<string, RouterChannel> = new Map([
|
|
646
|
+
['in-chan', mkChannel('in-chan', ALICE, BRIDGE, TOKEN_A, 1000n * SCALE)],
|
|
647
|
+
['out-chan', mkChannel('out-chan', BRIDGE, CAROL, TOKEN_B, 2000n * SCALE)],
|
|
648
|
+
]);
|
|
649
|
+
const lps: Map<string, LeaseProvider> = new Map([
|
|
650
|
+
['in-chan', MOCK_LP], ['out-chan', MOCK_LP],
|
|
651
|
+
]);
|
|
652
|
+
|
|
653
|
+
const paymentReq = buildPaymentRequest(100n * SCALE, TOKEN_A, 1000n);
|
|
654
|
+
const ops = makeMockOps();
|
|
655
|
+
return { channels, lps, route, paymentReq, ops, g };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
test('succeeds: both sides settle atomically', async () => {
|
|
659
|
+
const { channels, lps, route, paymentReq, ops } = crossSetup();
|
|
660
|
+
const result = await executeCrossTokenPayment(ops, channels, route, paymentReq, lps);
|
|
661
|
+
expect(result.success).toBe(true);
|
|
662
|
+
expect(result.settledHops.length).toBe(2);
|
|
663
|
+
expect(result.preimage).toBe(paymentReq.preimage);
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
test('each channel is locked exactly once (no duplicate HTLC locking)', async () => {
|
|
667
|
+
const { channels, lps, route, paymentReq } = crossSetup();
|
|
668
|
+
const addCalls: string[] = [];
|
|
669
|
+
const trackingOps = makeMockOps({
|
|
670
|
+
async addHTLC(channel, params, lp) {
|
|
671
|
+
addCalls.push(channel.channelId);
|
|
672
|
+
return makeMockOps().addHTLC(channel, params, lp);
|
|
673
|
+
},
|
|
674
|
+
});
|
|
675
|
+
await executeCrossTokenPayment(trackingOps, channels, route, paymentReq, lps);
|
|
676
|
+
// Exactly 2 addHTLC calls — one for in-chan, one for out-chan
|
|
677
|
+
expect(addCalls).toHaveLength(2);
|
|
678
|
+
expect(addCalls.filter(id => id === 'in-chan').length).toBe(1);
|
|
679
|
+
expect(addCalls.filter(id => id === 'out-chan').length).toBe(1);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
test('both channels have exactly one fulfilled HTLC after success', async () => {
|
|
683
|
+
const { channels, lps, route, paymentReq, ops } = crossSetup();
|
|
684
|
+
await executeCrossTokenPayment(ops, channels, route, paymentReq, lps);
|
|
685
|
+
const inChan = channels.get('in-chan')!;
|
|
686
|
+
const outChan = channels.get('out-chan')!;
|
|
687
|
+
expect(inChan.pendingHTLCs.filter(h => h.status === 'fulfilled').length).toBe(1);
|
|
688
|
+
expect(outChan.pendingHTLCs.filter(h => h.status === 'fulfilled').length).toBe(1);
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
test('cross-token failure: inbound failure rolls back nothing yet', async () => {
|
|
692
|
+
const { channels, lps, route, paymentReq } = crossSetup();
|
|
693
|
+
|
|
694
|
+
const failOps = makeMockOps({
|
|
695
|
+
addHTLC: async () => ({ channel: channels.get('in-chan')!, htlcId: '', error: 'inbound fail' }),
|
|
696
|
+
});
|
|
697
|
+
|
|
698
|
+
const result = await executeCrossTokenPayment(failOps, channels, route, paymentReq, lps);
|
|
699
|
+
expect(result.success).toBe(false);
|
|
700
|
+
expect(result.error).toMatch(/inbound/);
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
test('cross-token fulfill-phase failure: all pending HTLCs are timed out', async () => {
|
|
704
|
+
const { channels, lps, route, paymentReq } = crossSetup();
|
|
705
|
+
|
|
706
|
+
const timeoutCalls: string[] = [];
|
|
707
|
+
const baseOps = makeMockOps();
|
|
708
|
+
|
|
709
|
+
const failFulfillOps: ChannelOps = {
|
|
710
|
+
addHTLC: baseOps.addHTLC,
|
|
711
|
+
async fulfillHTLC(channel, htlcId, _preimage, lp) {
|
|
712
|
+
throw new Error('fulfill failed');
|
|
713
|
+
},
|
|
714
|
+
async timeoutHTLC(channel, htlcId, lp) {
|
|
715
|
+
timeoutCalls.push(htlcId);
|
|
716
|
+
return baseOps.timeoutHTLC(channel, htlcId, lp);
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
const result = await executeCrossTokenPayment(failFulfillOps, channels, route, paymentReq, lps);
|
|
721
|
+
expect(result.success).toBe(false);
|
|
722
|
+
// Both inbound and outbound HTLCs should be timed out
|
|
723
|
+
expect(timeoutCalls.length).toBe(2);
|
|
724
|
+
expect(result.settledHops.length).toBe(0);
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
test('outbound failure after inbound lock → inbound HTLC is rolled back', async () => {
|
|
728
|
+
const { channels, lps, route, paymentReq } = crossSetup();
|
|
729
|
+
|
|
730
|
+
let addCount = 0;
|
|
731
|
+
const ops = makeMockOps();
|
|
732
|
+
const timeoutCalls: string[] = [];
|
|
733
|
+
|
|
734
|
+
const partialOps: ChannelOps = {
|
|
735
|
+
async addHTLC(channel, params, lp) {
|
|
736
|
+
addCount++;
|
|
737
|
+
if (addCount === 2) throw new Error('outbound fail');
|
|
738
|
+
return ops.addHTLC(channel, params, lp);
|
|
739
|
+
},
|
|
740
|
+
fulfillHTLC: ops.fulfillHTLC,
|
|
741
|
+
async timeoutHTLC(channel, htlcId, lp) {
|
|
742
|
+
timeoutCalls.push(htlcId);
|
|
743
|
+
return ops.timeoutHTLC(channel, htlcId, lp);
|
|
744
|
+
},
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
const result = await executeCrossTokenPayment(partialOps, channels, route, paymentReq, lps);
|
|
748
|
+
expect(result.success).toBe(false);
|
|
749
|
+
// The inbound HTLC locked in step 1 should be timed out
|
|
750
|
+
expect(timeoutCalls.length).toBeGreaterThanOrEqual(1);
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
// ── Pre/post-swap hop tests ──────────────────────────────────────────────
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Route: Alice → Relay → Bridge (swap) → Carol → Dave
|
|
757
|
+
* pre-swap: Alice --[TOKEN_A]--> Relay (pre-chan)
|
|
758
|
+
* inbound: Relay --[TOKEN_A]--> Bridge (in-chan)
|
|
759
|
+
* outbound: Bridge --[TOKEN_B]--> Carol (out-chan)
|
|
760
|
+
* post-swap: Carol --[TOKEN_B]--> Dave (post-chan)
|
|
761
|
+
*/
|
|
762
|
+
function crossSetupWithPrePost() {
|
|
763
|
+
const RELAY = 'pk-relay';
|
|
764
|
+
const DAVE = 'pk-dave';
|
|
765
|
+
const g = createChannelGraph();
|
|
766
|
+
|
|
767
|
+
// TOKEN_A edges (sender side)
|
|
768
|
+
addChannel(g, mkEdge('pre-chan', ALICE, RELAY, TOKEN_A, 1000n * SCALE));
|
|
769
|
+
addChannel(g, mkEdge('in-chan', RELAY, BRIDGE, TOKEN_A, 1000n * SCALE));
|
|
770
|
+
// TOKEN_B edges (recipient side)
|
|
771
|
+
addChannel(g, mkEdge('out-chan', BRIDGE, CAROL, TOKEN_B, 2000n * SCALE));
|
|
772
|
+
addChannel(g, mkEdge('post-chan', CAROL, DAVE, TOKEN_B, 2000n * SCALE));
|
|
773
|
+
|
|
774
|
+
announceSwap(g, {
|
|
775
|
+
intermediaryPubKey: BRIDGE,
|
|
776
|
+
tokenIn: TOKEN_A,
|
|
777
|
+
tokenOut: TOKEN_B,
|
|
778
|
+
rate: '1.5',
|
|
779
|
+
inboundChannelId: 'in-chan',
|
|
780
|
+
outboundChannelId: 'out-chan',
|
|
781
|
+
maxAmountIn: 1000n * SCALE,
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
const route = findCrossTokenRoute(g, ALICE, DAVE, 100n * SCALE, TOKEN_A, TOKEN_B) as CrossTokenRoute;
|
|
785
|
+
expect(route).not.toBeNull();
|
|
786
|
+
|
|
787
|
+
const channels: Map<string, RouterChannel> = new Map([
|
|
788
|
+
['pre-chan', mkChannel('pre-chan', ALICE, RELAY, TOKEN_A, 1000n * SCALE)],
|
|
789
|
+
['in-chan', mkChannel('in-chan', RELAY, BRIDGE, TOKEN_A, 1000n * SCALE)],
|
|
790
|
+
['out-chan', mkChannel('out-chan', BRIDGE, CAROL, TOKEN_B, 2000n * SCALE)],
|
|
791
|
+
['post-chan', mkChannel('post-chan', CAROL, DAVE, TOKEN_B, 2000n * SCALE)],
|
|
792
|
+
]);
|
|
793
|
+
const lps: Map<string, LeaseProvider> = new Map([
|
|
794
|
+
['pre-chan', MOCK_LP],
|
|
795
|
+
['in-chan', MOCK_LP],
|
|
796
|
+
['out-chan', MOCK_LP],
|
|
797
|
+
['post-chan', MOCK_LP],
|
|
798
|
+
]);
|
|
799
|
+
const paymentReq = buildPaymentRequest(100n * SCALE, TOKEN_A, 1000n);
|
|
800
|
+
const ops = makeMockOps();
|
|
801
|
+
return { channels, lps, route, paymentReq, ops, g, RELAY, DAVE };
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
test('pre/post-swap route: succeeds and settles all 4 HTLCs', async () => {
|
|
805
|
+
const { channels, lps, route, paymentReq, ops } = crossSetupWithPrePost();
|
|
806
|
+
const result = await executeCrossTokenPayment(ops, channels, route, paymentReq, lps);
|
|
807
|
+
expect(result.success).toBe(true);
|
|
808
|
+
expect(result.settledHops.length).toBe(4);
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
test('pre/post-swap route: HTLC timeouts are strictly monotonically decreasing', async () => {
|
|
812
|
+
const { channels, lps, route, paymentReq } = crossSetupWithPrePost();
|
|
813
|
+
|
|
814
|
+
const lockedTimeouts: Array<{ channelId: string; timeoutBlock: bigint }> = [];
|
|
815
|
+
const trackingOps = makeMockOps({
|
|
816
|
+
async addHTLC(channel, params, lp) {
|
|
817
|
+
lockedTimeouts.push({ channelId: channel.channelId, timeoutBlock: params.timeoutBlock });
|
|
818
|
+
return makeMockOps().addHTLC(channel, params, lp);
|
|
819
|
+
},
|
|
820
|
+
});
|
|
821
|
+
|
|
822
|
+
const result = await executeCrossTokenPayment(trackingOps, channels, route, paymentReq, lps);
|
|
823
|
+
expect(result.success).toBe(true);
|
|
824
|
+
// 4 locks: pre-chan, in-chan, out-chan, post-chan
|
|
825
|
+
expect(lockedTimeouts.length).toBe(4);
|
|
826
|
+
// Verify strictly decreasing timeouts (sender → recipient)
|
|
827
|
+
for (let i = 1; i < lockedTimeouts.length; i++) {
|
|
828
|
+
expect(lockedTimeouts[i].timeoutBlock).toBeLessThan(lockedTimeouts[i - 1].timeoutBlock);
|
|
829
|
+
}
|
|
830
|
+
// pre-chan has the highest timeout (closest to sender)
|
|
831
|
+
expect(lockedTimeouts[0].channelId).toBe('pre-chan');
|
|
832
|
+
// post-chan has the lowest timeout (closest to recipient)
|
|
833
|
+
expect(lockedTimeouts[3].channelId).toBe('post-chan');
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
test('pre/post-swap route: forward failure in pre-hop rolls back nothing extra', async () => {
|
|
837
|
+
const { channels, lps, route, paymentReq } = crossSetupWithPrePost();
|
|
838
|
+
const timeoutCalls: string[] = [];
|
|
839
|
+
|
|
840
|
+
const failOnFirst = makeMockOps({
|
|
841
|
+
addHTLC: async () => ({ channel: channels.get('pre-chan')!, htlcId: '', error: 'pre-hop fail' }),
|
|
842
|
+
timeoutHTLC: async (channel, htlcId, lp) => {
|
|
843
|
+
timeoutCalls.push(htlcId);
|
|
844
|
+
return makeMockOps().timeoutHTLC(channel, htlcId, lp);
|
|
845
|
+
},
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
const result = await executeCrossTokenPayment(failOnFirst, channels, route, paymentReq, lps);
|
|
849
|
+
expect(result.success).toBe(false);
|
|
850
|
+
// Nothing was locked before the first failure → no timeouts needed
|
|
851
|
+
expect(timeoutCalls.length).toBe(0);
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
test('pre/post-swap route: forward failure in post-hop rolls back all 3 prior locks', async () => {
|
|
855
|
+
const { channels, lps, route, paymentReq } = crossSetupWithPrePost();
|
|
856
|
+
const timeoutCalls: string[] = [];
|
|
857
|
+
let addCount = 0;
|
|
858
|
+
const baseOps = makeMockOps();
|
|
859
|
+
|
|
860
|
+
const failOnFourth = makeMockOps({
|
|
861
|
+
async addHTLC(channel, params, lp) {
|
|
862
|
+
addCount++;
|
|
863
|
+
if (addCount === 4) throw new Error('post-hop fail');
|
|
864
|
+
return baseOps.addHTLC(channel, params, lp);
|
|
865
|
+
},
|
|
866
|
+
timeoutHTLC: async (channel, htlcId, lp) => {
|
|
867
|
+
timeoutCalls.push(htlcId);
|
|
868
|
+
return baseOps.timeoutHTLC(channel, htlcId, lp);
|
|
869
|
+
},
|
|
870
|
+
});
|
|
871
|
+
|
|
872
|
+
const result = await executeCrossTokenPayment(failOnFourth, channels, route, paymentReq, lps);
|
|
873
|
+
expect(result.success).toBe(false);
|
|
874
|
+
// 3 HTLCs were locked (pre-chan, in-chan, out-chan) before the 4th failed
|
|
875
|
+
expect(timeoutCalls.length).toBe(3);
|
|
876
|
+
});
|
|
877
|
+
});
|