@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.
@@ -0,0 +1,37 @@
1
+ import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, LeaseProvider } from './types.js';
2
+ /**
3
+ * Execute a single-token multi-hop payment atomically:
4
+ *
5
+ * 1. Forward phase — lock HTLCs across each hop in route.hops.
6
+ * 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
7
+ *
8
+ * Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
9
+ * failure, including failures that occur during the reveal phase — so stranded
10
+ * HTLCs are never left behind silently.
11
+ *
12
+ * `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
13
+ *
14
+ * The `channels` map is updated in-place after each HTLC operation.
15
+ */
16
+ export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
17
+ /**
18
+ * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
19
+ * Call this explicitly to roll back before or without attempting execution.
20
+ */
21
+ export declare function cancelPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, leaseProviders: Map<string, LeaseProvider>): Promise<void>;
22
+ /**
23
+ * Execute a cross-token payment atomically.
24
+ *
25
+ * For each SwapHop:
26
+ * 1. Lock the inbound HTLC (tokenIn side).
27
+ * 2. Lock the outbound HTLC (tokenOut side).
28
+ * Both use the same hashlock — the intermediary can only claim by revealing
29
+ * the preimage on both sides simultaneously.
30
+ *
31
+ * Then forward-locks all remaining non-swap hops, and reveals the preimage
32
+ * backwards across all locked channels.
33
+ *
34
+ * Rollback fires on ANY failure (forward OR backward phase) by timing out
35
+ * all still-pending locked HTLCs.
36
+ */
37
+ export declare function executeCrossTokenPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: CrossTokenRoute, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
@@ -0,0 +1,249 @@
1
+ // ─── Type guard ───────────────────────────────────────────────────────────────
2
+ function isSwapHop(hop) {
3
+ return hop.isSwap === true;
4
+ }
5
+ // ─── Internal helpers ─────────────────────────────────────────────────────────
6
+ /** Determine the counterparty public key digest relative to the local signer. */
7
+ function counterpartPkd(channel) {
8
+ const localPkd = channel.localSigner?.publicKeyDigest;
9
+ const other = channel.parties.find(p => p.publicKeyDigest !== localPkd);
10
+ if (!other)
11
+ throw new Error(`Channel ${channel.channelId}: cannot determine counterpart`);
12
+ return other.publicKeyDigest;
13
+ }
14
+ /**
15
+ * Best-effort timeout of a set of locked HTLCs.
16
+ * Errors from individual timeoutHTLC calls are silently ignored so rollback
17
+ * always completes as many cancellations as possible.
18
+ */
19
+ async function cancelHtlcs(ops, channels, locked, leaseProviders) {
20
+ for (const { channelId, htlcId } of [...locked].reverse()) {
21
+ const ch = channels.get(channelId);
22
+ const lp = leaseProviders.get(channelId);
23
+ if (!ch || !lp)
24
+ continue;
25
+ try {
26
+ const res = await ops.timeoutHTLC(ch, htlcId, lp);
27
+ channels.set(channelId, res.channel);
28
+ }
29
+ catch { /* best-effort: continue rolling back other hops */ }
30
+ }
31
+ }
32
+ // ─── Single-token multi-hop payment ──────────────────────────────────────────
33
+ /**
34
+ * Execute a single-token multi-hop payment atomically:
35
+ *
36
+ * 1. Forward phase — lock HTLCs across each hop in route.hops.
37
+ * 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
38
+ *
39
+ * Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
40
+ * failure, including failures that occur during the reveal phase — so stranded
41
+ * HTLCs are never left behind silently.
42
+ *
43
+ * `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
44
+ *
45
+ * The `channels` map is updated in-place after each HTLC operation.
46
+ */
47
+ export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
48
+ const preimage = paymentRequest.preimage;
49
+ if (!preimage) {
50
+ return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
51
+ }
52
+ const plainHops = route.hops.filter(h => !isSwapHop(h));
53
+ const locked = [];
54
+ // ── Forward: lock HTLCs ───────────────────────────────────────────────────
55
+ for (let i = 0; i < plainHops.length; i++) {
56
+ const hop = plainHops[i];
57
+ const channel = channels.get(hop.channelId);
58
+ if (!channel) {
59
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
60
+ return { success: false, error: `Channel ${hop.channelId} not found`, settledHops: [] };
61
+ }
62
+ const lp = leaseProviders.get(hop.channelId);
63
+ if (!lp) {
64
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
65
+ return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
66
+ }
67
+ // Timeouts decrease toward the recipient so each hop has time to claim.
68
+ const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
69
+ let addResult;
70
+ try {
71
+ addResult = await ops.addHTLC(channel, {
72
+ amount: hop.amount,
73
+ hashlock: paymentRequest.hashlock,
74
+ timeoutBlock,
75
+ direction: 'offered',
76
+ counterpartPublicKeyDigest: counterpartPkd(channel),
77
+ }, lp);
78
+ }
79
+ catch (err) {
80
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
81
+ return { success: false, error: String(err), settledHops: [] };
82
+ }
83
+ if (addResult.error) {
84
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
85
+ return { success: false, error: addResult.error, settledHops: [] };
86
+ }
87
+ channels.set(hop.channelId, addResult.channel);
88
+ hop.htlcId = addResult.htlcId;
89
+ locked.push({ channelId: hop.channelId, htlcId: addResult.htlcId });
90
+ }
91
+ // ── Backward: reveal preimage ─────────────────────────────────────────────
92
+ // Track fulfilled IDs so that on failure we can timeout only the still-pending
93
+ // ones (already-fulfilled HTLCs are irreversible and must not be retouched).
94
+ const settled = [];
95
+ const fulfilledSet = new Set();
96
+ for (const { channelId, htlcId } of [...locked].reverse()) {
97
+ const channel = channels.get(channelId);
98
+ const lp = leaseProviders.get(channelId);
99
+ let fulfillResult;
100
+ try {
101
+ fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
102
+ }
103
+ catch (err) {
104
+ // Timeout every still-pending lock (not yet fulfilled)
105
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
106
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
107
+ return { success: false, error: String(err), settledHops: settled };
108
+ }
109
+ if (fulfillResult.error) {
110
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
111
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
112
+ return { success: false, error: fulfillResult.error, settledHops: settled };
113
+ }
114
+ channels.set(channelId, fulfillResult.channel);
115
+ settled.push(htlcId);
116
+ fulfilledSet.add(htlcId);
117
+ }
118
+ return { success: true, preimage, settledHops: settled };
119
+ }
120
+ /**
121
+ * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
122
+ * Call this explicitly to roll back before or without attempting execution.
123
+ */
124
+ export async function cancelPayment(ops, channels, route, leaseProviders) {
125
+ const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
126
+ await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
127
+ }
128
+ // ─── Cross-token multi-hop payment ───────────────────────────────────────────
129
+ /**
130
+ * Execute a cross-token payment atomically.
131
+ *
132
+ * For each SwapHop:
133
+ * 1. Lock the inbound HTLC (tokenIn side).
134
+ * 2. Lock the outbound HTLC (tokenOut side).
135
+ * Both use the same hashlock — the intermediary can only claim by revealing
136
+ * the preimage on both sides simultaneously.
137
+ *
138
+ * Then forward-locks all remaining non-swap hops, and reveals the preimage
139
+ * backwards across all locked channels.
140
+ *
141
+ * Rollback fires on ANY failure (forward OR backward phase) by timing out
142
+ * all still-pending locked HTLCs.
143
+ */
144
+ export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
145
+ const preimage = paymentRequest.preimage;
146
+ if (!preimage) {
147
+ return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
148
+ }
149
+ const locked = [];
150
+ /**
151
+ * Lock a single HTLC, add it to `locked`, and return the htlcId.
152
+ * Throws on any error so callers can handle rollback uniformly.
153
+ */
154
+ async function lockHTLC(channelId, amount, hashlock, timeoutBlock) {
155
+ const channel = channels.get(channelId);
156
+ const lp = leaseProviders.get(channelId);
157
+ if (!channel)
158
+ throw new Error(`Channel ${channelId} not found`);
159
+ if (!lp)
160
+ throw new Error(`No lease provider for channel ${channelId}`);
161
+ // Let addHTLC exceptions propagate — they carry the original error message.
162
+ const result = await ops.addHTLC(channel, {
163
+ amount,
164
+ hashlock,
165
+ timeoutBlock,
166
+ direction: 'offered',
167
+ counterpartPublicKeyDigest: counterpartPkd(channel),
168
+ }, lp);
169
+ if (result.error)
170
+ throw new Error(result.error);
171
+ channels.set(channelId, result.channel);
172
+ locked.push({ channelId, htlcId: result.htlcId });
173
+ return result.htlcId;
174
+ }
175
+ // ── Lock HTLCs in full route order with monotonically decreasing timeouts ──
176
+ //
177
+ // Correct HTLC safety requires timeouts to DECREASE toward the recipient:
178
+ // sender (highest timeout) → ... → recipient (lowest timeout)
179
+ //
180
+ // We iterate route.hops in their declared order. For each RoutingHop we
181
+ // consume one position. For each SwapHop we consume two consecutive
182
+ // positions: inbound channel first (higher timeout), outbound second (lower).
183
+ //
184
+ // position 0: preHops[0] ← highest timeout
185
+ // position 1: preHops[1]
186
+ // ...
187
+ // position k: swapInbound
188
+ // position k+1: swapOutbound
189
+ // ...
190
+ // position n: postHops[last] ← lowest timeout
191
+ let pos = 0;
192
+ for (const hop of route.hops) {
193
+ if (isSwapHop(hop)) {
194
+ // Inbound channel (sender → intermediary, tokenIn side)
195
+ const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
196
+ try {
197
+ hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout);
198
+ }
199
+ catch (err) {
200
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
201
+ return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, settledHops: [] };
202
+ }
203
+ // Outbound channel (intermediary → recipient, tokenOut side)
204
+ const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
205
+ try {
206
+ await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout);
207
+ }
208
+ catch (err) {
209
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
210
+ return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, settledHops: [] };
211
+ }
212
+ }
213
+ else {
214
+ const timeout = paymentRequest.expiryBlock - BigInt(pos++);
215
+ try {
216
+ hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout);
217
+ }
218
+ catch (err) {
219
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
220
+ return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, settledHops: [] };
221
+ }
222
+ }
223
+ }
224
+ // ── Reveal preimage backward ──────────────────────────────────────────────
225
+ const settled = [];
226
+ const fulfilledSet = new Set();
227
+ for (const { channelId, htlcId } of [...locked].reverse()) {
228
+ const channel = channels.get(channelId);
229
+ const lp = leaseProviders.get(channelId);
230
+ let fulfillResult;
231
+ try {
232
+ fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
233
+ }
234
+ catch (err) {
235
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
236
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
237
+ return { success: false, error: String(err), settledHops: settled };
238
+ }
239
+ if (fulfillResult.error) {
240
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
241
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
242
+ return { success: false, error: fulfillResult.error, settledHops: settled };
243
+ }
244
+ channels.set(channelId, fulfillResult.channel);
245
+ settled.push(htlcId);
246
+ fulfilledSet.add(htlcId);
247
+ }
248
+ return { success: true, preimage, settledHops: settled };
249
+ }
@@ -0,0 +1,32 @@
1
+ import type { ChannelGraph, ChannelGraphEdge, SwapAnnouncement } from './types.js';
2
+ /** Create an empty ChannelGraph. */
3
+ export declare function createChannelGraph(): ChannelGraph;
4
+ /**
5
+ * Add a directed channel edge to the graph.
6
+ *
7
+ * A single logical channel between two parties has two directed edges — one
8
+ * per direction of flow. Both may be added independently using the same
9
+ * `channelId` because they are keyed by `(channelId, from)`. Calling
10
+ * `addChannel` twice with the same `(channelId, from)` replaces the first
11
+ * entry (balance update semantics).
12
+ */
13
+ export declare function addChannel(graph: ChannelGraph, edge: ChannelGraphEdge): void;
14
+ /**
15
+ * Remove ALL directed edges for `channelId` (i.e. both directions).
16
+ * No-op if the channelId is not present.
17
+ */
18
+ export declare function removeChannel(graph: ChannelGraph, channelId: string): void;
19
+ /**
20
+ * Register a swap announcement from a bridging intermediary.
21
+ *
22
+ * Validates that the rate is a positive finite decimal before storing.
23
+ * Throws `Error` if the rate is zero or negative.
24
+ *
25
+ * Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
26
+ * are replaced to prevent stale rate data.
27
+ */
28
+ export declare function announceSwap(graph: ChannelGraph, announcement: SwapAnnouncement): void;
29
+ /**
30
+ * Return all swap announcements for a given token pair, or an empty array.
31
+ */
32
+ export declare function getSwapAnnouncements(graph: ChannelGraph, tokenIn: string, tokenOut: string): SwapAnnouncement[];
package/dist/graph.js ADDED
@@ -0,0 +1,95 @@
1
+ import { parseRateToScaled } from './pathfind.js';
2
+ /** Create an empty ChannelGraph. */
3
+ export function createChannelGraph() {
4
+ return {
5
+ nodeEdges: new Map(),
6
+ edgesByChannel: new Map(),
7
+ swapIndex: new Map(),
8
+ };
9
+ }
10
+ /**
11
+ * Add a directed channel edge to the graph.
12
+ *
13
+ * A single logical channel between two parties has two directed edges — one
14
+ * per direction of flow. Both may be added independently using the same
15
+ * `channelId` because they are keyed by `(channelId, from)`. Calling
16
+ * `addChannel` twice with the same `(channelId, from)` replaces the first
17
+ * entry (balance update semantics).
18
+ */
19
+ export function addChannel(graph, edge) {
20
+ const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
21
+ // Replace any edge for the same (channelId, from) direction.
22
+ const idx = existing.findIndex(e => e.from === edge.from);
23
+ if (idx >= 0) {
24
+ _removeFromNodeEdges(graph, existing[idx]);
25
+ existing.splice(idx, 1, edge);
26
+ }
27
+ else {
28
+ existing.push(edge);
29
+ }
30
+ graph.edgesByChannel.set(edge.channelId, existing);
31
+ // Register in nodeEdges for O(1) Dijkstra lookup.
32
+ const nodeList = graph.nodeEdges.get(edge.from) ?? [];
33
+ nodeList.push(edge);
34
+ graph.nodeEdges.set(edge.from, nodeList);
35
+ }
36
+ /**
37
+ * Remove ALL directed edges for `channelId` (i.e. both directions).
38
+ * No-op if the channelId is not present.
39
+ */
40
+ export function removeChannel(graph, channelId) {
41
+ const edges = graph.edgesByChannel.get(channelId);
42
+ if (!edges)
43
+ return;
44
+ for (const edge of edges) {
45
+ _removeFromNodeEdges(graph, edge);
46
+ }
47
+ graph.edgesByChannel.delete(channelId);
48
+ }
49
+ function _removeFromNodeEdges(graph, edge) {
50
+ const nodeList = graph.nodeEdges.get(edge.from);
51
+ if (!nodeList)
52
+ return;
53
+ const filtered = nodeList.filter(e => !(e.channelId === edge.channelId && e.from === edge.from));
54
+ if (filtered.length === 0) {
55
+ graph.nodeEdges.delete(edge.from);
56
+ }
57
+ else {
58
+ graph.nodeEdges.set(edge.from, filtered);
59
+ }
60
+ }
61
+ /**
62
+ * Register a swap announcement from a bridging intermediary.
63
+ *
64
+ * Validates that the rate is a positive finite decimal before storing.
65
+ * Throws `Error` if the rate is zero or negative.
66
+ *
67
+ * Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
68
+ * are replaced to prevent stale rate data.
69
+ */
70
+ export function announceSwap(graph, announcement) {
71
+ const rateScaled = parseRateToScaled(announcement.rate);
72
+ if (rateScaled <= 0n) {
73
+ throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
74
+ }
75
+ const key = _swapKey(announcement.tokenIn, announcement.tokenOut);
76
+ const list = graph.swapIndex.get(key) ?? [];
77
+ const idx = list.findIndex(a => a.intermediaryPubKey === announcement.intermediaryPubKey &&
78
+ a.inboundChannelId === announcement.inboundChannelId);
79
+ if (idx >= 0) {
80
+ list[idx] = announcement;
81
+ }
82
+ else {
83
+ list.push(announcement);
84
+ }
85
+ graph.swapIndex.set(key, list);
86
+ }
87
+ /**
88
+ * Return all swap announcements for a given token pair, or an empty array.
89
+ */
90
+ export function getSwapAnnouncements(graph, tokenIn, tokenOut) {
91
+ return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
92
+ }
93
+ function _swapKey(tokenIn, tokenOut) {
94
+ return `${tokenIn}:${tokenOut}`;
95
+ }
@@ -0,0 +1,5 @@
1
+ export type { RouterChannel, ChannelParty, ChannelHTLC, HTLCStatus, ChannelSigner, ChannelOps, HTLCParams, LeaseProvider, ChannelGraphEdge, ChannelGraph, RoutingHop, SwapHop, Route, CrossTokenRoute, SwapAnnouncement, PaymentRequest, PaymentResult, RouteOptions, } from './types.js';
2
+ export { createChannelGraph, addChannel, removeChannel, announceSwap, getSwapAnnouncements, } from './graph.js';
3
+ export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from './pathfind.js';
4
+ export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
5
+ export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, } from './execute.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createChannelGraph, addChannel, removeChannel, announceSwap, getSwapAnnouncements, } from './graph.js';
2
+ export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from './pathfind.js';
3
+ export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
4
+ export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, } from './execute.js';
@@ -0,0 +1,25 @@
1
+ import type { ChannelGraph, Route, CrossTokenRoute, RouteOptions } from './types.js';
2
+ /**
3
+ * Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
4
+ * "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
5
+ */
6
+ export declare function parseRateToScaled(rate: string): bigint;
7
+ /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
8
+ export declare function applyRate(amountIn: bigint, rate: string): bigint;
9
+ /**
10
+ * Find the cheapest route (lowest total fee, then fewest hops) from `from` to
11
+ * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
12
+ * availableBalance.
13
+ *
14
+ * Returns null if no path exists within maxHops.
15
+ */
16
+ export declare function findRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, opts?: RouteOptions): Route | null;
17
+ /**
18
+ * Find a cross-token route where the sender spends `tokenIn` and the
19
+ * recipient receives `tokenOut`. The path may include one or more swap hops
20
+ * provided by bridging intermediaries registered via announceSwap.
21
+ *
22
+ * Selection criteria: lowest total fee (including swap fee), then fewest hops,
23
+ * then fewest swap hops.
24
+ */
25
+ export declare function findCrossTokenRoute(graph: ChannelGraph, from: string, to: string, amountIn: bigint, tokenIn: string, tokenOut: string, opts?: RouteOptions): CrossTokenRoute | null;