@totemsdk/omnia-router 0.3.0 → 0.4.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.
@@ -1,25 +1,24 @@
1
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;
2
+ import { applyRate, parseRateToScaled } from './rates.js';
3
+ export { parseRateToScaled, applyRate };
9
4
  /**
10
5
  * 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.
6
+ * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
7
+ * availableBalance. Returns null if no path exists within maxHops.
13
8
  *
14
- * Returns null if no path exists within maxHops.
9
+ * Delegates to the routing engine (zero-fee BFS / layered bounded search).
15
10
  */
16
11
  export declare function findRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, opts?: RouteOptions): Route | null;
17
12
  /**
18
13
  * 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
14
+ * recipient receives `tokenOut`. The path may include one or more swap hops
20
15
  * provided by bridging intermediaries registered via announceSwap.
21
16
  *
22
17
  * Selection criteria: lowest total fee (including swap fee), then fewest hops,
23
- * then fewest swap hops.
18
+ * then fewest swap hops, then a deterministic route key.
19
+ *
20
+ * `maxHops` is a **global** end-to-end budget: preHops + 1 (swap) + postHops
21
+ * must not exceed it (RFC-055 §2.5). The inbound leg is computed once for all
22
+ * announcements; the outbound leg is cached per `(postDst, amountOut, tokenOut)`.
24
23
  */
25
24
  export declare function findCrossTokenRoute(graph: ChannelGraph, from: string, to: string, amountIn: bigint, tokenIn: string, tokenOut: string, opts?: RouteOptions): CrossTokenRoute | null;
@@ -1,169 +1,91 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseRateToScaled = parseRateToScaled;
4
- exports.applyRate = applyRate;
3
+ exports.applyRate = exports.parseRateToScaled = void 0;
5
4
  exports.findRoute = findRoute;
6
5
  exports.findCrossTokenRoute = findCrossTokenRoute;
7
6
  const graph_js_1 = require("./graph.js");
8
- const SCALE = 100000000n;
9
- // ─── Numeric helpers ──────────────────────────────────────────────────────────
10
- /**
11
- * Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
12
- * "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
13
- */
14
- function parseRateToScaled(rate) {
15
- const neg = rate.startsWith('-');
16
- const abs = neg ? rate.slice(1) : rate;
17
- const dot = abs.indexOf('.');
18
- const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
19
- const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
20
- const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
21
- const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
22
- const result = BigInt(intPart) * SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
23
- return neg ? -result : result;
24
- }
25
- /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
26
- function applyRate(amountIn, rate) {
27
- const rateScaled = parseRateToScaled(rate);
28
- return (amountIn * rateScaled) / SCALE;
29
- }
7
+ const rates_js_1 = require("./rates.js");
8
+ Object.defineProperty(exports, "applyRate", { enumerable: true, get: function () { return rates_js_1.applyRate; } });
9
+ Object.defineProperty(exports, "parseRateToScaled", { enumerable: true, get: function () { return rates_js_1.parseRateToScaled; } });
10
+ const bounded_search_js_1 = require("./bounded-search.js");
11
+ const routing_engine_js_1 = require("./routing-engine.js");
12
+ // ─── Single-token ─────────────────────────────────────────────────────────────
30
13
  /**
31
14
  * Find the cheapest route (lowest total fee, then fewest hops) from `from` to
32
- * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
33
- * availableBalance.
15
+ * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
16
+ * availableBalance. Returns null if no path exists within maxHops.
34
17
  *
35
- * Returns null if no path exists within maxHops.
18
+ * Delegates to the routing engine (zero-fee BFS / layered bounded search).
36
19
  */
37
20
  function findRoute(graph, from, to, amount, tokenId, opts) {
38
- return _reconstruct(graph, from, to, amount, tokenId, opts?.maxHops ?? 8);
21
+ const snapshot = (0, routing_engine_js_1.createRoutingGraphSnapshot)(graph);
22
+ const engine = (0, routing_engine_js_1.selectRoutingEngine)(snapshot);
23
+ return engine.findRoute(snapshot, {
24
+ source: from,
25
+ destination: to,
26
+ amount,
27
+ tokenId,
28
+ ...(opts?.maxHops === undefined ? {} : { maxHops: opts.maxHops }),
29
+ }, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
39
30
  }
40
- /** Full path reconstruction (used once Dijkstra confirms a route exists). */
41
- function _reconstruct(graph, from, to, amount, tokenId, maxHops) {
42
- const dist = new Map();
43
- const queue = [{ node: from, totalFees: 0n, hops: 0, path: [] }];
44
- dist.set(from, { totalFees: 0n, hops: 0, path: [] });
45
- while (queue.length > 0) {
46
- const { node, totalFees, hops, path } = _dequeue(queue);
47
- if (node === to) {
48
- return {
49
- hops: path,
50
- totalFees,
51
- tokenIn: tokenId,
52
- tokenOut: tokenId,
53
- estimatedBlocks: path.length * 2,
54
- };
55
- }
56
- if (hops >= maxHops)
57
- continue;
58
- for (const edge of (graph.nodeEdges.get(node) ?? [])) {
59
- if (edge.tokenId !== tokenId)
60
- continue;
61
- if (edge.availableBalance < amount)
62
- continue;
63
- const fee = _edgeFee(amount, edge);
64
- const newFees = totalFees + fee;
65
- const newHops = hops + 1;
66
- const best = dist.get(edge.to);
67
- if (best && _notBetter(newFees, newHops, best.totalFees, best.hops))
68
- continue;
69
- const hop = {
70
- channelId: edge.channelId,
71
- from: edge.from,
72
- to: edge.to,
73
- amount,
74
- tokenId,
75
- };
76
- const newPath = [...path, hop];
77
- dist.set(edge.to, { totalFees: newFees, hops: newHops, path: newPath });
78
- _enqueue(queue, { node: edge.to, totalFees: newFees, hops: newHops, path: newPath });
79
- }
80
- }
81
- const best = dist.get(to);
82
- if (!best)
83
- return null;
84
- return {
85
- hops: best.path,
86
- totalFees: best.totalFees,
87
- tokenIn: tokenId,
88
- tokenOut: tokenId,
89
- estimatedBlocks: best.path.length * 2,
90
- };
91
- }
92
- // ─── Cross-token Dijkstra ─────────────────────────────────────────────────────
31
+ // ─── Cross-token ──────────────────────────────────────────────────────────────
93
32
  /**
94
33
  * Find a cross-token route where the sender spends `tokenIn` and the
95
- * recipient receives `tokenOut`. The path may include one or more swap hops
34
+ * recipient receives `tokenOut`. The path may include one or more swap hops
96
35
  * provided by bridging intermediaries registered via announceSwap.
97
36
  *
98
37
  * Selection criteria: lowest total fee (including swap fee), then fewest hops,
99
- * then fewest swap hops.
38
+ * then fewest swap hops, then a deterministic route key.
39
+ *
40
+ * `maxHops` is a **global** end-to-end budget: preHops + 1 (swap) + postHops
41
+ * must not exceed it (RFC-055 §2.5). The inbound leg is computed once for all
42
+ * announcements; the outbound leg is cached per `(postDst, amountOut, tokenOut)`.
100
43
  */
101
44
  function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
102
45
  const announcements = (0, graph_js_1.getSwapAnnouncements)(graph, tokenIn, tokenOut);
103
46
  if (announcements.length === 0)
104
47
  return null;
48
+ const maxHops = opts?.maxHops ?? routing_engine_js_1.DEFAULT_MAX_HOPS;
49
+ if (!Number.isInteger(maxHops) || maxHops < 0) {
50
+ throw new Error(`maxHops must be a non-negative integer (got ${String(opts?.maxHops)})`);
51
+ }
52
+ // A swap consumes one hop; pre + swap + post must fit the global budget.
53
+ if (amountIn <= 0n || maxHops < 1)
54
+ return null;
55
+ const snapshot = (0, routing_engine_js_1.createRoutingGraphSnapshot)(graph);
56
+ const engine = (0, routing_engine_js_1.selectRoutingEngine)(snapshot);
57
+ // One bounded inbound tree serves every announcement.
58
+ const preTree = engine.computeTree(snapshot, { source: from, amount: amountIn, tokenId: tokenIn, maxHops: maxHops - 1 }, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
59
+ const postCache = new Map();
105
60
  let best = null;
106
61
  for (const ann of announcements) {
107
- // Validate maxAmountIn
108
62
  if (amountIn > ann.maxAmountIn)
109
63
  continue;
110
- // Inbound segment: from → intermediary via tokenIn.
111
- // Look up the directed edge whose `to` is the intermediary (the edge ends
112
- // at the intermediary so they can claim the inbound HTLC).
113
64
  const inboundEdges = graph.edgesByChannel.get(ann.inboundChannelId) ?? [];
114
65
  const inboundEdge = inboundEdges.find(e => e.to === ann.intermediaryPubKey && e.tokenId === tokenIn);
115
66
  if (!inboundEdge)
116
67
  continue;
117
- // Check the inbound edge has sufficient balance
118
68
  if (inboundEdge.availableBalance < amountIn)
119
69
  continue;
120
- // amountOut from rate — must be positive (validated at announceSwap, but
121
- // guard here defensively in case of adversarial state or direct graph edits)
122
- const amountOut = applyRate(amountIn, ann.rate);
70
+ const amountOut = (0, rates_js_1.applyRate)(amountIn, ann.rate);
123
71
  if (amountOut <= 0n)
124
72
  continue;
125
- // Outbound segment: intermediary → recipient via tokenOut.
126
- // Look up the directed edge whose `from` is the intermediary.
127
73
  const outboundEdges = graph.edgesByChannel.get(ann.outboundChannelId) ?? [];
128
74
  const outboundEdge = outboundEdges.find(e => e.from === ann.intermediaryPubKey && e.tokenId === tokenOut);
129
75
  if (!outboundEdge)
130
76
  continue;
131
77
  if (outboundEdge.availableBalance < amountOut)
132
78
  continue;
133
- // SwapHop represents the ENTIRE atomic bridge crossing — both the inbound
134
- // and outbound channels are locked together with the same hashlock inside
135
- // executeCrossTokenPayment. We must NOT also include those channels as
136
- // ordinary RoutingHops, or execution would try to lock them twice.
137
- //
138
- // Therefore:
139
- // pre-swap = route from `from` → inboundEdge.from
140
- // post-swap = route from outboundEdge.to → `to`
141
- //
142
- // Fees for the swap channels themselves (inboundFee + outboundFee) are
143
- // accounted for separately and NOT included in pre/post route totals.
144
- const preSrc = inboundEdge.from; // sender side of the inbound channel
145
- const postDst = outboundEdge.to; // receiver side of the outbound channel
146
- // Pre-swap route: from → preSrc (empty when from IS the inbound channel sender)
147
- let preRoute;
148
- if (from === preSrc) {
149
- preRoute = { hops: [], totalFees: 0n, tokenIn, tokenOut: tokenIn, estimatedBlocks: 0 };
150
- }
151
- else {
152
- preRoute = findRoute(graph, from, preSrc, amountIn, tokenIn, opts);
79
+ const preSrc = inboundEdge.from;
80
+ const postDst = outboundEdge.to;
81
+ const postKey = `${postDst}|${amountOut.toString()}|${tokenOut}|${maxHops - 1}`;
82
+ let postTree = postCache.get(postKey);
83
+ if (!postTree) {
84
+ postTree = engine.computeTree(snapshot, { source: postDst, amount: amountOut, tokenId: tokenOut, maxHops: maxHops - 1 }, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
85
+ postCache.set(postKey, postTree);
153
86
  }
154
- if (!preRoute)
155
- continue;
156
- // Post-swap route: postDst → to (empty when postDst IS the final recipient)
157
- let postRoute;
158
- if (postDst === to) {
159
- postRoute = { hops: [], totalFees: 0n, tokenIn: tokenOut, tokenOut, estimatedBlocks: 0 };
160
- }
161
- else {
162
- postRoute = findRoute(graph, postDst, to, amountOut, tokenOut, opts);
163
- }
164
- if (!postRoute)
165
- continue;
166
- // Build the swap hop (encompasses both swap channels)
87
+ const inboundFee = (0, bounded_search_js_1.defaultEdgeFee)(amountIn, inboundEdge);
88
+ const outboundFee = (0, bounded_search_js_1.defaultEdgeFee)(amountOut, outboundEdge);
167
89
  const swapHop = {
168
90
  isSwap: true,
169
91
  channelId: ann.inboundChannelId,
@@ -179,75 +101,51 @@ function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts)
179
101
  inboundChannelId: ann.inboundChannelId,
180
102
  outboundChannelId: ann.outboundChannelId,
181
103
  };
182
- // Fees: pre + inbound swap channel + outbound swap channel + post
183
- // (no double-counting — swap channels are NOT in preRoute/postRoute hops)
184
- const inboundFee = _edgeFee(amountIn, inboundEdge);
185
- const outboundFee = _edgeFee(amountOut, outboundEdge);
186
- const totalFees = preRoute.totalFees + inboundFee + outboundFee + postRoute.totalFees;
187
- const allHops = [
188
- ...preRoute.hops,
189
- swapHop,
190
- ...postRoute.hops,
191
- ];
192
- const candidate = {
193
- hops: allHops,
194
- totalFees,
195
- tokenIn,
196
- tokenOut,
197
- estimatedBlocks: allHops.length * 2,
198
- swapHops: [swapHop],
199
- };
200
- if (!best || _crossTokenBetter(candidate, best)) {
201
- best = candidate;
104
+ for (let preH = 0; preH <= maxHops - 1; preH++) {
105
+ const preLabel = preTree.labelAt(preSrc, preH);
106
+ if (!preLabel)
107
+ continue;
108
+ for (let postH = 0; postH <= maxHops - 1 - preH; postH++) {
109
+ const postLabel = postTree.labelAt(to, postH);
110
+ if (!postLabel)
111
+ continue;
112
+ const allHops = [
113
+ ...preLabel.route.hops,
114
+ swapHop,
115
+ ...postLabel.route.hops,
116
+ ];
117
+ const candidate = {
118
+ hops: allHops,
119
+ totalFees: preLabel.totalFees + inboundFee + outboundFee + postLabel.totalFees,
120
+ tokenIn,
121
+ tokenOut,
122
+ estimatedBlocks: allHops.length * 2,
123
+ swapHops: [swapHop],
124
+ };
125
+ if (!best || _crossTokenBetter(candidate, best)) {
126
+ best = candidate;
127
+ }
128
+ }
202
129
  }
203
130
  }
204
131
  return best;
205
132
  }
206
133
  // ─── Helpers ──────────────────────────────────────────────────────────────────
207
- function _edgeFee(amount, edge) {
208
- return (amount * edge.feeRate) / SCALE;
209
- }
210
- /** Returns true if (newFees, newHops) is NOT better than (bestFees, bestHops). */
211
- function _notBetter(newFees, newHops, bestFees, bestHops) {
212
- if (newFees > bestFees)
213
- return true;
214
- if (newFees < bestFees)
215
- return false;
216
- return newHops >= bestHops;
217
- }
218
134
  function _crossTokenBetter(a, b) {
219
- if (a.totalFees < b.totalFees)
220
- return true;
221
- if (a.totalFees > b.totalFees)
222
- return false;
223
- if (a.hops.length < b.hops.length)
224
- return true;
225
- if (a.hops.length > b.hops.length)
226
- return false;
227
- return a.swapHops.length < b.swapHops.length;
228
- }
229
- /** Extract a single-edge route when `from` → `to` via `edge` is a direct hop. */
230
- function _singleEdgeRoute(edge, from, to, amount, tokenId) {
231
- if (edge.from !== from || edge.to !== to)
232
- return null;
233
- if (edge.tokenId !== tokenId)
234
- return null;
235
- if (edge.availableBalance < amount)
236
- return null;
237
- const hop = { channelId: edge.channelId, from, to, amount, tokenId };
238
- return { hops: [hop], totalFees: _edgeFee(amount, edge), tokenIn: tokenId, tokenOut: tokenId, estimatedBlocks: 2 };
135
+ if (a.totalFees !== b.totalFees)
136
+ return a.totalFees < b.totalFees;
137
+ if (a.hops.length !== b.hops.length)
138
+ return a.hops.length < b.hops.length;
139
+ if (a.swapHops.length !== b.swapHops.length)
140
+ return a.swapHops.length < b.swapHops.length;
141
+ return _routeKey(a.hops) < _routeKey(b.hops);
239
142
  }
240
- /** Dequeue the minimum-cost state from the priority queue. */
241
- function _dequeue(queue) {
242
- let minIdx = 0;
243
- for (let i = 1; i < queue.length; i++) {
244
- const a = queue[i], b = queue[minIdx];
245
- if (a.totalFees < b.totalFees || (a.totalFees === b.totalFees && a.hops < b.hops)) {
246
- minIdx = i;
143
+ function _routeKey(hops) {
144
+ return hops.map((hop) => {
145
+ if (hop.isSwap) {
146
+ const swap = hop;
147
+ return `swap:${swap.channelId}:${swap.outboundChannelId}`;
247
148
  }
248
- }
249
- return queue.splice(minIdx, 1)[0];
250
- }
251
- function _enqueue(queue, state) {
252
- queue.push(state);
149
+ return (0, bounded_search_js_1.edgeKey)(hop);
150
+ }).join('>');
253
151
  }
@@ -0,0 +1,9 @@
1
+ /** Fixed-point scale shared by routing fees and swap rates. */
2
+ export declare const SCALE = 100000000n;
3
+ /**
4
+ * Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
5
+ * "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
6
+ */
7
+ export declare function parseRateToScaled(rate: string): bigint;
8
+ /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
9
+ export declare function applyRate(amountIn: bigint, rate: string): bigint;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SCALE = void 0;
4
+ exports.parseRateToScaled = parseRateToScaled;
5
+ exports.applyRate = applyRate;
6
+ /** Fixed-point scale shared by routing fees and swap rates. */
7
+ exports.SCALE = 100000000n;
8
+ /**
9
+ * Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
10
+ * "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
11
+ */
12
+ function parseRateToScaled(rate) {
13
+ const neg = rate.startsWith('-');
14
+ const abs = neg ? rate.slice(1) : rate;
15
+ const dot = abs.indexOf('.');
16
+ const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
17
+ const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
18
+ const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
19
+ const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
20
+ const result = BigInt(intPart) * exports.SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
21
+ return neg ? -result : result;
22
+ }
23
+ /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
24
+ function applyRate(amountIn, rate) {
25
+ const rateScaled = parseRateToScaled(rate);
26
+ return (amountIn * rateScaled) / exports.SCALE;
27
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Route revalidation against live channel state (RFC-054 §4 / RFC-055).
3
+ *
4
+ * A route from the router is a *candidate*. Before locking HTLCs the executor
5
+ * must confirm the channels still exist, are active, carry the expected token,
6
+ * have the expected direction and have enough sender balance.
7
+ */
8
+ import type { RouterChannel, RoutingHop, Route, SwapHop } from './types.js';
9
+ export type RouteValidationResult = {
10
+ ok: true;
11
+ } | {
12
+ ok: false;
13
+ error: string;
14
+ };
15
+ /** Validate a single channel spend (status, token, sender, balance). */
16
+ export declare function validateChannelSpend(channel: RouterChannel, sender: string, amount: bigint, tokenId: string): RouteValidationResult;
17
+ /** Validate a single-token hop. */
18
+ export declare function validateRoutingHop(channels: Map<string, RouterChannel>, hop: RoutingHop): RouteValidationResult;
19
+ /** The intermediary that connects a swap's inbound and outbound channels. */
20
+ export declare function swapIntermediary(channels: Map<string, RouterChannel>, hop: SwapHop): string | undefined;
21
+ /** Validate both legs of a swap hop. */
22
+ export declare function validateSwapHop(channels: Map<string, RouterChannel>, hop: SwapHop): RouteValidationResult;
23
+ /** Validate every hop of a route against live channel state. */
24
+ export declare function validateRoute(channels: Map<string, RouterChannel>, route: Route): RouteValidationResult;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateChannelSpend = validateChannelSpend;
4
+ exports.validateRoutingHop = validateRoutingHop;
5
+ exports.swapIntermediary = swapIntermediary;
6
+ exports.validateSwapHop = validateSwapHop;
7
+ exports.validateRoute = validateRoute;
8
+ function fail(error) {
9
+ return { ok: false, error };
10
+ }
11
+ function partyFor(channel, pkd) {
12
+ return channel.parties.find((party) => party.publicKeyDigest === pkd);
13
+ }
14
+ function otherParty(channel, pkd) {
15
+ return channel.parties.find((party) => party.publicKeyDigest !== pkd);
16
+ }
17
+ /** Validate a single channel spend (status, token, sender, balance). */
18
+ function validateChannelSpend(channel, sender, amount, tokenId) {
19
+ if (channel.status !== 'active') {
20
+ return fail(`channel ${channel.channelId} is ${channel.status}`);
21
+ }
22
+ if (channel.tokenId !== tokenId) {
23
+ return fail(`channel ${channel.channelId} token ${channel.tokenId} != ${tokenId}`);
24
+ }
25
+ if (amount <= 0n) {
26
+ return fail(`channel ${channel.channelId} spend amount must be positive`);
27
+ }
28
+ const party = partyFor(channel, sender);
29
+ if (!party) {
30
+ return fail(`sender ${sender} is not a party on channel ${channel.channelId}`);
31
+ }
32
+ const balance = channel.balances[party.partyId] ?? 0n;
33
+ if (balance < amount) {
34
+ return fail(`insufficient balance on channel ${channel.channelId}: ${balance.toString()} < ${amount.toString()}`);
35
+ }
36
+ return { ok: true };
37
+ }
38
+ /** Validate a single-token hop. */
39
+ function validateRoutingHop(channels, hop) {
40
+ const channel = channels.get(hop.channelId);
41
+ if (!channel)
42
+ return fail(`channel ${hop.channelId} not found`);
43
+ if (hop.from === hop.to)
44
+ return fail(`hop ${hop.channelId} has identical from/to`);
45
+ if (!partyFor(channel, hop.to)) {
46
+ return fail(`recipient ${hop.to} is not a party on channel ${hop.channelId}`);
47
+ }
48
+ return validateChannelSpend(channel, hop.from, hop.amount, hop.tokenId);
49
+ }
50
+ /** The intermediary that connects a swap's inbound and outbound channels. */
51
+ function swapIntermediary(channels, hop) {
52
+ const inbound = channels.get(hop.inboundChannelId);
53
+ if (!inbound)
54
+ return undefined;
55
+ return otherParty(inbound, hop.from)?.publicKeyDigest;
56
+ }
57
+ /** Validate both legs of a swap hop. */
58
+ function validateSwapHop(channels, hop) {
59
+ const inbound = channels.get(hop.inboundChannelId);
60
+ if (!inbound)
61
+ return fail(`inbound channel ${hop.inboundChannelId} not found`);
62
+ const outbound = channels.get(hop.outboundChannelId);
63
+ if (!outbound)
64
+ return fail(`outbound channel ${hop.outboundChannelId} not found`);
65
+ const inResult = validateChannelSpend(inbound, hop.from, hop.amountIn, hop.tokenIn);
66
+ if (!inResult.ok)
67
+ return inResult;
68
+ const intermediary = otherParty(inbound, hop.from)?.publicKeyDigest;
69
+ if (!intermediary) {
70
+ return fail(`inbound channel ${hop.inboundChannelId} has no intermediary`);
71
+ }
72
+ if (!partyFor(outbound, hop.to)) {
73
+ return fail(`recipient ${hop.to} is not a party on outbound channel ${hop.outboundChannelId}`);
74
+ }
75
+ const outIntermediary = otherParty(outbound, hop.to)?.publicKeyDigest;
76
+ if (outIntermediary !== intermediary) {
77
+ return fail(`swap intermediary mismatch: ${intermediary} != ${outIntermediary ?? 'none'}`);
78
+ }
79
+ return validateChannelSpend(outbound, intermediary, hop.amountOut, hop.tokenOut);
80
+ }
81
+ /** Validate every hop of a route against live channel state. */
82
+ function validateRoute(channels, route) {
83
+ for (const hop of route.hops) {
84
+ const result = hop.isSwap
85
+ ? validateSwapHop(channels, hop)
86
+ : validateRoutingHop(channels, hop);
87
+ if (!result.ok)
88
+ return result;
89
+ }
90
+ return { ok: true };
91
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Routing engine contracts (RFC-055 Phase 1).
3
+ *
4
+ * Internal module: not exported from the package barrel until the semantics are
5
+ * sufficiently tested. `findRoute` and `findCrossTokenRoute` consume it.
6
+ */
7
+ import type { ChannelGraph, Route } from './types.js';
8
+ import { type FeeFunction } from './bounded-search.js';
9
+ export declare const DEFAULT_MAX_HOPS = 8;
10
+ export interface RoutingGraphRevision {
11
+ topology: number;
12
+ economics: number;
13
+ live: number;
14
+ }
15
+ export interface RoutingGraphSnapshot {
16
+ readonly graph: ChannelGraph;
17
+ readonly revision: RoutingGraphRevision;
18
+ }
19
+ export declare function createRoutingGraphSnapshot(graph: ChannelGraph): RoutingGraphSnapshot;
20
+ export interface RoutingQuery {
21
+ source: string;
22
+ destination?: string;
23
+ amount: bigint;
24
+ tokenId: string;
25
+ targetToken?: string;
26
+ /** `undefined` ⇒ default 8; `null` ⇒ unbounded (rejected until implemented). */
27
+ maxHops?: number | null;
28
+ objective?: 'fees-then-hops';
29
+ costModelId?: string;
30
+ }
31
+ /**
32
+ * Versioned cost-model contract. The current model is additive, fixed-amount
33
+ * and non-negative; future models declare amount dependence explicitly.
34
+ */
35
+ export interface RoutingCostModel {
36
+ readonly id: string;
37
+ readonly nonNegative: boolean;
38
+ readonly additive: boolean;
39
+ readonly amountDependent: boolean;
40
+ edgeFee: FeeFunction;
41
+ compare(a: {
42
+ fees: bigint;
43
+ hops: number;
44
+ }, b: {
45
+ fees: bigint;
46
+ hops: number;
47
+ }): number;
48
+ }
49
+ export declare const FIXED_AMOUNT_COST_MODEL: RoutingCostModel;
50
+ export declare class UnsupportedRoutingModeError extends Error {
51
+ readonly mode: string;
52
+ constructor(mode: string);
53
+ }
54
+ export interface RoutingTreeLabel {
55
+ readonly hops: number;
56
+ readonly totalFees: bigint;
57
+ readonly route: Route;
58
+ }
59
+ /** Reusable one-to-many search result. Routes are reconstructed on demand. */
60
+ export interface RoutingTree {
61
+ readonly source: string;
62
+ readonly amount: bigint;
63
+ readonly tokenId: string;
64
+ readonly maxHops: number;
65
+ readonly revision: RoutingGraphRevision;
66
+ readonly costModelId: string;
67
+ readonly destinations: readonly string[];
68
+ labelAt(destination: string, hops: number): RoutingTreeLabel | null;
69
+ routeTo(destination: string): Route | null;
70
+ }
71
+ export interface RoutingEngineCapabilities {
72
+ readonly bounded: boolean;
73
+ readonly unbounded: boolean;
74
+ readonly oneToMany: boolean;
75
+ readonly incremental: boolean;
76
+ readonly crossToken: boolean;
77
+ }
78
+ export interface RoutingEngine {
79
+ readonly id: string;
80
+ readonly capabilities: RoutingEngineCapabilities;
81
+ findRoute(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): Route | null;
82
+ computeTree(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): RoutingTree;
83
+ }
84
+ export declare function selectRoutingEngine(_snapshot: RoutingGraphSnapshot): RoutingEngine;
85
+ /** Cache key includes every input that materially affects correctness. */
86
+ export declare function routeCacheKey(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): string;