@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,314 @@
1
+ import type {
2
+ ChannelGraph,
3
+ ChannelGraphEdge,
4
+ Route,
5
+ CrossTokenRoute,
6
+ RoutingHop,
7
+ SwapHop,
8
+ RouteOptions,
9
+ } from './types.js';
10
+ import { getSwapAnnouncements } from './graph.js';
11
+
12
+ const SCALE = 100_000_000n;
13
+
14
+ // ─── Numeric helpers ──────────────────────────────────────────────────────────
15
+
16
+ /**
17
+ * Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
18
+ * "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
19
+ */
20
+ export function parseRateToScaled(rate: string): bigint {
21
+ const neg = rate.startsWith('-');
22
+ const abs = neg ? rate.slice(1) : rate;
23
+ const dot = abs.indexOf('.');
24
+ const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
25
+ const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
26
+ const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
27
+ const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
28
+ const result = BigInt(intPart) * SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
29
+ return neg ? -result : result;
30
+ }
31
+
32
+ /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
33
+ export function applyRate(amountIn: bigint, rate: string): bigint {
34
+ const rateScaled = parseRateToScaled(rate);
35
+ return (amountIn * rateScaled) / SCALE;
36
+ }
37
+
38
+ // ─── Single-token Dijkstra ────────────────────────────────────────────────────
39
+
40
+ type DijkstraState = {
41
+ node: string;
42
+ totalFees: bigint;
43
+ hops: number;
44
+ path: RoutingHop[];
45
+ };
46
+
47
+ /**
48
+ * Find the cheapest route (lowest total fee, then fewest hops) from `from` to
49
+ * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
50
+ * availableBalance.
51
+ *
52
+ * Returns null if no path exists within maxHops.
53
+ */
54
+ export function findRoute(
55
+ graph: ChannelGraph,
56
+ from: string,
57
+ to: string,
58
+ amount: bigint,
59
+ tokenId: string,
60
+ opts?: RouteOptions,
61
+ ): Route | null {
62
+ return _reconstruct(graph, from, to, amount, tokenId, opts?.maxHops ?? 8);
63
+ }
64
+
65
+ /** Full path reconstruction (used once Dijkstra confirms a route exists). */
66
+ function _reconstruct(
67
+ graph: ChannelGraph,
68
+ from: string,
69
+ to: string,
70
+ amount: bigint,
71
+ tokenId: string,
72
+ maxHops: number,
73
+ ): Route | null {
74
+ const dist = new Map<string, { totalFees: bigint; hops: number; path: RoutingHop[] }>();
75
+ const queue: DijkstraState[] = [{ node: from, totalFees: 0n, hops: 0, path: [] }];
76
+ dist.set(from, { totalFees: 0n, hops: 0, path: [] });
77
+
78
+ while (queue.length > 0) {
79
+ const { node, totalFees, hops, path } = _dequeue(queue);
80
+
81
+ if (node === to) {
82
+ return {
83
+ hops: path,
84
+ totalFees,
85
+ tokenIn: tokenId,
86
+ tokenOut: tokenId,
87
+ estimatedBlocks: path.length * 2,
88
+ };
89
+ }
90
+
91
+ if (hops >= maxHops) continue;
92
+
93
+ for (const edge of (graph.nodeEdges.get(node) ?? [])) {
94
+ if (edge.tokenId !== tokenId) continue;
95
+ if (edge.availableBalance < amount) continue;
96
+
97
+ const fee = _edgeFee(amount, edge);
98
+ const newFees = totalFees + fee;
99
+ const newHops = hops + 1;
100
+
101
+ const best = dist.get(edge.to);
102
+ if (best && _notBetter(newFees, newHops, best.totalFees, best.hops)) continue;
103
+
104
+ const hop: RoutingHop = {
105
+ channelId: edge.channelId,
106
+ from: edge.from,
107
+ to: edge.to,
108
+ amount,
109
+ tokenId,
110
+ };
111
+ const newPath = [...path, hop];
112
+ dist.set(edge.to, { totalFees: newFees, hops: newHops, path: newPath });
113
+ _enqueue(queue, { node: edge.to, totalFees: newFees, hops: newHops, path: newPath });
114
+ }
115
+ }
116
+
117
+ const best = dist.get(to);
118
+ if (!best) return null;
119
+ return {
120
+ hops: best.path,
121
+ totalFees: best.totalFees,
122
+ tokenIn: tokenId,
123
+ tokenOut: tokenId,
124
+ estimatedBlocks: best.path.length * 2,
125
+ };
126
+ }
127
+
128
+ // ─── Cross-token Dijkstra ─────────────────────────────────────────────────────
129
+
130
+ /**
131
+ * Find a cross-token route where the sender spends `tokenIn` and the
132
+ * recipient receives `tokenOut`. The path may include one or more swap hops
133
+ * provided by bridging intermediaries registered via announceSwap.
134
+ *
135
+ * Selection criteria: lowest total fee (including swap fee), then fewest hops,
136
+ * then fewest swap hops.
137
+ */
138
+ export function findCrossTokenRoute(
139
+ graph: ChannelGraph,
140
+ from: string,
141
+ to: string,
142
+ amountIn: bigint,
143
+ tokenIn: string,
144
+ tokenOut: string,
145
+ opts?: RouteOptions,
146
+ ): CrossTokenRoute | null {
147
+ const announcements = getSwapAnnouncements(graph, tokenIn, tokenOut);
148
+ if (announcements.length === 0) return null;
149
+
150
+ let best: CrossTokenRoute | null = null;
151
+
152
+ for (const ann of announcements) {
153
+ // Validate maxAmountIn
154
+ if (amountIn > ann.maxAmountIn) continue;
155
+
156
+ // Inbound segment: from → intermediary via tokenIn.
157
+ // Look up the directed edge whose `to` is the intermediary (the edge ends
158
+ // at the intermediary so they can claim the inbound HTLC).
159
+ const inboundEdges = graph.edgesByChannel.get(ann.inboundChannelId) ?? [];
160
+ const inboundEdge = inboundEdges.find(
161
+ e => e.to === ann.intermediaryPubKey && e.tokenId === tokenIn,
162
+ );
163
+ if (!inboundEdge) continue;
164
+
165
+ // Check the inbound edge has sufficient balance
166
+ if (inboundEdge.availableBalance < amountIn) continue;
167
+
168
+ // amountOut from rate — must be positive (validated at announceSwap, but
169
+ // guard here defensively in case of adversarial state or direct graph edits)
170
+ const amountOut = applyRate(amountIn, ann.rate);
171
+ if (amountOut <= 0n) continue;
172
+
173
+ // Outbound segment: intermediary → recipient via tokenOut.
174
+ // Look up the directed edge whose `from` is the intermediary.
175
+ const outboundEdges = graph.edgesByChannel.get(ann.outboundChannelId) ?? [];
176
+ const outboundEdge = outboundEdges.find(
177
+ e => e.from === ann.intermediaryPubKey && e.tokenId === tokenOut,
178
+ );
179
+ if (!outboundEdge) continue;
180
+ if (outboundEdge.availableBalance < amountOut) continue;
181
+
182
+ // SwapHop represents the ENTIRE atomic bridge crossing — both the inbound
183
+ // and outbound channels are locked together with the same hashlock inside
184
+ // executeCrossTokenPayment. We must NOT also include those channels as
185
+ // ordinary RoutingHops, or execution would try to lock them twice.
186
+ //
187
+ // Therefore:
188
+ // pre-swap = route from `from` → inboundEdge.from
189
+ // post-swap = route from outboundEdge.to → `to`
190
+ //
191
+ // Fees for the swap channels themselves (inboundFee + outboundFee) are
192
+ // accounted for separately and NOT included in pre/post route totals.
193
+
194
+ const preSrc = inboundEdge.from; // sender side of the inbound channel
195
+ const postDst = outboundEdge.to; // receiver side of the outbound channel
196
+
197
+ // Pre-swap route: from → preSrc (empty when from IS the inbound channel sender)
198
+ let preRoute: Route | null;
199
+ if (from === preSrc) {
200
+ preRoute = { hops: [], totalFees: 0n, tokenIn, tokenOut: tokenIn, estimatedBlocks: 0 };
201
+ } else {
202
+ preRoute = findRoute(graph, from, preSrc, amountIn, tokenIn, opts);
203
+ }
204
+ if (!preRoute) continue;
205
+
206
+ // Post-swap route: postDst → to (empty when postDst IS the final recipient)
207
+ let postRoute: Route | null;
208
+ if (postDst === to) {
209
+ postRoute = { hops: [], totalFees: 0n, tokenIn: tokenOut, tokenOut, estimatedBlocks: 0 };
210
+ } else {
211
+ postRoute = findRoute(graph, postDst, to, amountOut, tokenOut, opts);
212
+ }
213
+ if (!postRoute) continue;
214
+
215
+ // Build the swap hop (encompasses both swap channels)
216
+ const swapHop: SwapHop = {
217
+ isSwap: true,
218
+ channelId: ann.inboundChannelId,
219
+ from: preSrc,
220
+ to: postDst,
221
+ amount: amountIn,
222
+ tokenId: tokenIn,
223
+ tokenIn,
224
+ tokenOut,
225
+ amountIn,
226
+ amountOut,
227
+ rate: ann.rate,
228
+ inboundChannelId: ann.inboundChannelId,
229
+ outboundChannelId: ann.outboundChannelId,
230
+ };
231
+
232
+ // Fees: pre + inbound swap channel + outbound swap channel + post
233
+ // (no double-counting — swap channels are NOT in preRoute/postRoute hops)
234
+ const inboundFee = _edgeFee(amountIn, inboundEdge);
235
+ const outboundFee = _edgeFee(amountOut, outboundEdge);
236
+ const totalFees = preRoute.totalFees + inboundFee + outboundFee + postRoute.totalFees;
237
+
238
+ const allHops: (RoutingHop | SwapHop)[] = [
239
+ ...preRoute.hops,
240
+ swapHop,
241
+ ...postRoute.hops,
242
+ ];
243
+
244
+ const candidate: CrossTokenRoute = {
245
+ hops: allHops,
246
+ totalFees,
247
+ tokenIn,
248
+ tokenOut,
249
+ estimatedBlocks: allHops.length * 2,
250
+ swapHops: [swapHop],
251
+ };
252
+
253
+ if (!best || _crossTokenBetter(candidate, best)) {
254
+ best = candidate;
255
+ }
256
+ }
257
+
258
+ return best;
259
+ }
260
+
261
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
262
+
263
+ function _edgeFee(amount: bigint, edge: ChannelGraphEdge): bigint {
264
+ return (amount * edge.feeRate) / SCALE;
265
+ }
266
+
267
+ /** Returns true if (newFees, newHops) is NOT better than (bestFees, bestHops). */
268
+ function _notBetter(
269
+ newFees: bigint, newHops: number,
270
+ bestFees: bigint, bestHops: number,
271
+ ): boolean {
272
+ if (newFees > bestFees) return true;
273
+ if (newFees < bestFees) return false;
274
+ return newHops >= bestHops;
275
+ }
276
+
277
+ function _crossTokenBetter(a: CrossTokenRoute, b: CrossTokenRoute): boolean {
278
+ if (a.totalFees < b.totalFees) return true;
279
+ if (a.totalFees > b.totalFees) return false;
280
+ if (a.hops.length < b.hops.length) return true;
281
+ if (a.hops.length > b.hops.length) return false;
282
+ return a.swapHops.length < b.swapHops.length;
283
+ }
284
+
285
+ /** Extract a single-edge route when `from` → `to` via `edge` is a direct hop. */
286
+ function _singleEdgeRoute(
287
+ edge: ChannelGraphEdge,
288
+ from: string,
289
+ to: string,
290
+ amount: bigint,
291
+ tokenId: string,
292
+ ): Route | null {
293
+ if (edge.from !== from || edge.to !== to) return null;
294
+ if (edge.tokenId !== tokenId) return null;
295
+ if (edge.availableBalance < amount) return null;
296
+ const hop: RoutingHop = { channelId: edge.channelId, from, to, amount, tokenId };
297
+ return { hops: [hop], totalFees: _edgeFee(amount, edge), tokenIn: tokenId, tokenOut: tokenId, estimatedBlocks: 2 };
298
+ }
299
+
300
+ /** Dequeue the minimum-cost state from the priority queue. */
301
+ function _dequeue(queue: DijkstraState[]): DijkstraState {
302
+ let minIdx = 0;
303
+ for (let i = 1; i < queue.length; i++) {
304
+ const a = queue[i], b = queue[minIdx];
305
+ if (a.totalFees < b.totalFees || (a.totalFees === b.totalFees && a.hops < b.hops)) {
306
+ minIdx = i;
307
+ }
308
+ }
309
+ return queue.splice(minIdx, 1)[0];
310
+ }
311
+
312
+ function _enqueue(queue: DijkstraState[], state: DijkstraState): void {
313
+ queue.push(state);
314
+ }
package/src/request.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { F, hex } from '@totemsdk/core';
2
+ import type { PaymentRequest } from './types.js';
3
+
4
+ /**
5
+ * Generate a random 32-byte preimage, compute SHA3-256(preimage) as the
6
+ * hashlock, and return a PaymentRequest that is ready to share.
7
+ *
8
+ * The returned PaymentRequest includes the `preimage` field so the payer
9
+ * can call executeMultiHopPayment. Strip `preimage` before forwarding the
10
+ * request to intermediaries.
11
+ *
12
+ * Compatible with Bare/Pear environments: uses globalThis.crypto.getRandomValues
13
+ * (Web Crypto API, available in Node ≥18, browsers, and Pear/Bare runtimes).
14
+ */
15
+ export function buildPaymentRequest(
16
+ amount: bigint,
17
+ tokenId: string,
18
+ expiryBlock: bigint,
19
+ description?: string,
20
+ ): PaymentRequest {
21
+ const preimageBytes = new Uint8Array(32);
22
+ globalThis.crypto.getRandomValues(preimageBytes);
23
+ const preimage = '0x' + hex(preimageBytes);
24
+ const hashlock = '0x' + hex(F(preimageBytes));
25
+
26
+ return {
27
+ hashlock,
28
+ preimage,
29
+ amount,
30
+ tokenId,
31
+ expiryBlock,
32
+ description,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Recipient-side variant: generates a payment request for the token they want
38
+ * to receive. The API is identical to buildPaymentRequest — the distinction
39
+ * is conceptual (recipient generates hashlock; sender sources liquidity).
40
+ */
41
+ export function buildCrossTokenRequest(
42
+ amountOut: bigint,
43
+ tokenOut: string,
44
+ expiryBlock: bigint,
45
+ description?: string,
46
+ ): PaymentRequest {
47
+ return buildPaymentRequest(amountOut, tokenOut, expiryBlock, description);
48
+ }
package/src/types.ts ADDED
@@ -0,0 +1,221 @@
1
+ /**
2
+ * @totemsdk/omnia-router — public types
3
+ *
4
+ * All monetary values are scaled bigints (SCALE = 10^8).
5
+ * The router uses local mirrors of OmniaChannel/HTLCRecord so the package
6
+ * has no hard runtime dependency on @totemsdk/omnia — callers pass the
7
+ * real objects (structural typing ensures compatibility).
8
+ */
9
+
10
+ // ─── Internal channel mirrors (structural superset of OmniaChannel fields used) ──
11
+
12
+ export interface ChannelParty {
13
+ partyId: string;
14
+ publicKeyDigest: string;
15
+ addressIndex: number;
16
+ }
17
+
18
+ export type HTLCStatus = 'pending' | 'fulfilled' | 'timed_out';
19
+
20
+ export interface ChannelHTLC {
21
+ htlcId: string;
22
+ amount: bigint;
23
+ hashlock: string;
24
+ timeoutBlock: bigint;
25
+ direction: 'offered' | 'received';
26
+ status: HTLCStatus;
27
+ htlcAddress: string;
28
+ senderPublicKeyDigest: string;
29
+ recipientPublicKeyDigest: string;
30
+ }
31
+
32
+ export interface ChannelSigner {
33
+ publicKeyDigest: string;
34
+ }
35
+
36
+ /**
37
+ * Minimal mirror of OmniaChannel — the fields the router actually reads.
38
+ * Structurally compatible with @totemsdk/omnia's OmniaChannel so callers
39
+ * can pass real channel objects without an adapter.
40
+ */
41
+ export interface RouterChannel {
42
+ channelId: string;
43
+ tokenId: string;
44
+ parties: ChannelParty[];
45
+ balances: Record<string, bigint>;
46
+ pendingHTLCs: ChannelHTLC[];
47
+ totalValue: bigint;
48
+ currentSequence: number;
49
+ status: string;
50
+ localSigner?: ChannelSigner;
51
+ }
52
+
53
+ /**
54
+ * Parameters for adding an HTLC — mirrors @totemsdk/omnia's AddHTLCParams.
55
+ */
56
+ export interface HTLCParams {
57
+ amount: bigint;
58
+ hashlock: string;
59
+ timeoutBlock: bigint;
60
+ direction: 'offered' | 'received';
61
+ counterpartPublicKeyDigest: string;
62
+ }
63
+
64
+ /**
65
+ * Opaque lease-provider handle — the router passes it through to the
66
+ * underlying HTLC operations but never inspects it.
67
+ */
68
+ export type LeaseProvider = unknown;
69
+
70
+ /**
71
+ * Dependency-injected HTLC operations.
72
+ *
73
+ * In production, wire in the real functions from @totemsdk/omnia:
74
+ * import { addHTLC, fulfillHTLC, timeoutHTLC } from '@totemsdk/omnia';
75
+ * const ops: ChannelOps = { addHTLC, fulfillHTLC, timeoutHTLC };
76
+ *
77
+ * In tests, pass mocks directly — no jest.mock() needed.
78
+ */
79
+ export interface ChannelOps {
80
+ addHTLC(
81
+ channel: RouterChannel,
82
+ params: HTLCParams,
83
+ leaseProvider: LeaseProvider,
84
+ ): Promise<{ channel: RouterChannel; htlcId: string; error?: string }>;
85
+
86
+ fulfillHTLC(
87
+ channel: RouterChannel,
88
+ htlcId: string,
89
+ preimage: string,
90
+ leaseProvider: LeaseProvider,
91
+ ): Promise<{ channel: RouterChannel; error?: string }>;
92
+
93
+ timeoutHTLC(
94
+ channel: RouterChannel,
95
+ htlcId: string,
96
+ leaseProvider: LeaseProvider,
97
+ ): Promise<{ channel: RouterChannel; error?: string }>;
98
+ }
99
+
100
+ // ─── Graph ────────────────────────────────────────────────────────────────────
101
+
102
+ /**
103
+ * A directed edge in the channel graph.
104
+ * For a bidirectional channel, add two edges (one per direction).
105
+ */
106
+ export interface ChannelGraphEdge {
107
+ channelId: string;
108
+ /** Sender's public key digest */
109
+ from: string;
110
+ /** Recipient's public key digest */
111
+ to: string;
112
+ tokenId: string;
113
+ /** Sender's available balance in scaled units */
114
+ availableBalance: bigint;
115
+ /** Maximum additional HTLC capacity in scaled units */
116
+ htlcCapacity: bigint;
117
+ /** Fee per SCALE units of amount (e.g. 100_000n = 0.1%) */
118
+ feeRate: bigint;
119
+ }
120
+
121
+ /**
122
+ * In-memory channel graph with a swap announcement index.
123
+ *
124
+ * A single logical channel may have up to two directed edges (one per
125
+ * direction of flow, e.g. Alice→Bob and Bob→Alice). Both edges share the
126
+ * same `channelId` and are stored together in `edgesByChannel`.
127
+ */
128
+ export interface ChannelGraph {
129
+ /** Directed edges keyed by sender pubkey */
130
+ nodeEdges: Map<string, ChannelGraphEdge[]>;
131
+ /**
132
+ * All directed edges for a channel, keyed by channelId.
133
+ * Value is an array because a bidirectional channel has two directed edges.
134
+ */
135
+ edgesByChannel: Map<string, ChannelGraphEdge[]>;
136
+ /** Swap announcements keyed by `${tokenIn}:${tokenOut}` */
137
+ swapIndex: Map<string, SwapAnnouncement[]>;
138
+ }
139
+
140
+ // ─── Routing ──────────────────────────────────────────────────────────────────
141
+
142
+ export interface RoutingHop {
143
+ channelId: string;
144
+ from: string;
145
+ to: string;
146
+ amount: bigint;
147
+ tokenId: string;
148
+ /** Populated during payment execution */
149
+ htlcId?: string;
150
+ }
151
+
152
+ export interface SwapHop extends RoutingHop {
153
+ isSwap: true;
154
+ tokenIn: string;
155
+ tokenOut: string;
156
+ amountIn: bigint;
157
+ amountOut: bigint;
158
+ /** "amountOut per amountIn" expressed as decimal string, e.g. "0.95" */
159
+ rate: string;
160
+ inboundChannelId: string;
161
+ outboundChannelId: string;
162
+ }
163
+
164
+ export interface Route {
165
+ hops: (RoutingHop | SwapHop)[];
166
+ totalFees: bigint;
167
+ tokenIn: string;
168
+ tokenOut: string;
169
+ estimatedBlocks: number;
170
+ }
171
+
172
+ export interface CrossTokenRoute extends Route {
173
+ swapHops: SwapHop[];
174
+ }
175
+
176
+ // ─── Swap announcements ───────────────────────────────────────────────────────
177
+
178
+ export interface SwapAnnouncement {
179
+ intermediaryPubKey: string;
180
+ tokenIn: string;
181
+ tokenOut: string;
182
+ /** How many tokenOut scaled units per tokenIn scaled unit */
183
+ rate: string;
184
+ inboundChannelId: string;
185
+ outboundChannelId: string;
186
+ maxAmountIn: bigint;
187
+ }
188
+
189
+ // ─── Payment requests ─────────────────────────────────────────────────────────
190
+
191
+ export interface PaymentRequest {
192
+ /** SHA3-256 hex of preimage */
193
+ hashlock: string;
194
+ /**
195
+ * Known to the payer (returned by buildPaymentRequest).
196
+ * Strip this before sharing the request with intermediaries.
197
+ */
198
+ preimage?: string;
199
+ amount: bigint;
200
+ tokenId: string;
201
+ expiryBlock: bigint;
202
+ description?: string;
203
+ }
204
+
205
+ // ─── Payment results ──────────────────────────────────────────────────────────
206
+
207
+ export interface PaymentResult {
208
+ success: boolean;
209
+ /** Hex preimage revealed during settlement (present on success) */
210
+ preimage?: string;
211
+ error?: string;
212
+ /** htlcIds that were successfully settled */
213
+ settledHops: string[];
214
+ }
215
+
216
+ // ─── Pathfinding options ──────────────────────────────────────────────────────
217
+
218
+ export interface RouteOptions {
219
+ /** Maximum number of hops (default: 8) */
220
+ maxHops?: number;
221
+ }