@totemsdk/omnia-router 0.3.0 → 0.4.1

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,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultEdgeFee = defaultEdgeFee;
4
+ exports.edgeKey = edgeKey;
5
+ exports.computeLayers = computeLayers;
6
+ exports.routeFromLayers = routeFromLayers;
7
+ exports.reconstructFromLayers = reconstructFromLayers;
8
+ exports.isZeroFeeToken = isZeroFeeToken;
9
+ exports.bfsLayers = bfsLayers;
10
+ exports.bfsRoute = bfsRoute;
11
+ const rates_js_1 = require("./rates.js");
12
+ /** Default cost model: amount × feeRate / SCALE, fixed amount per hop. */
13
+ function defaultEdgeFee(amount, edge) {
14
+ return (amount * edge.feeRate) / rates_js_1.SCALE;
15
+ }
16
+ /** Deterministic edge key used for tie-breaking and BFS ordering. */
17
+ function edgeKey(edge) {
18
+ return `${edge.channelId}|${edge.from}|${edge.to}`;
19
+ }
20
+ /** Layered (hops, node) search. layers[h][v] is the cheapest path using exactly h edges. */
21
+ function computeLayers(graph, from, amount, tokenId, maxHops, feeFor = defaultEdgeFee) {
22
+ const layers = Array.from({ length: maxHops + 1 }, () => new Map());
23
+ layers[0].set(from, { totalFees: 0n });
24
+ for (let h = 1; h <= maxHops; h++) {
25
+ const prev = layers[h - 1];
26
+ if (prev.size === 0)
27
+ break;
28
+ const curr = layers[h];
29
+ for (const [u, label] of prev) {
30
+ const edges = graph.nodeEdges.get(u);
31
+ if (!edges)
32
+ continue;
33
+ for (const edge of edges) {
34
+ if (edge.tokenId !== tokenId)
35
+ continue;
36
+ if (edge.feeRate < 0n)
37
+ continue;
38
+ if (edge.availableBalance < amount)
39
+ continue;
40
+ const newFees = label.totalFees + feeFor(amount, edge);
41
+ const parent = { prevNode: u, edge };
42
+ const existing = curr.get(edge.to);
43
+ if (!existing || _betterSameLayer(newFees, parent, existing, h, edge.to, layers)) {
44
+ curr.set(edge.to, { totalFees: newFees, parent });
45
+ }
46
+ }
47
+ }
48
+ }
49
+ return layers;
50
+ }
51
+ /** Select the cheapest (fees, hops) label for `to` and reconstruct its path. */
52
+ function routeFromLayers(layers, to, amount, tokenId, maxHops) {
53
+ let bestH = -1;
54
+ let bestFees = 0n;
55
+ for (let h = 0; h <= maxHops; h++) {
56
+ const label = layers[h]?.get(to);
57
+ if (!label)
58
+ continue;
59
+ if (bestH === -1 ||
60
+ label.totalFees < bestFees ||
61
+ (label.totalFees === bestFees && h < bestH)) {
62
+ bestH = h;
63
+ bestFees = label.totalFees;
64
+ }
65
+ }
66
+ if (bestH === -1)
67
+ return null;
68
+ const hops = reconstructFromLayers(layers, bestH, to, amount, tokenId);
69
+ return {
70
+ hops,
71
+ totalFees: bestFees,
72
+ tokenIn: tokenId,
73
+ tokenOut: tokenId,
74
+ estimatedBlocks: hops.length * 2,
75
+ };
76
+ }
77
+ function reconstructFromLayers(layers, h, to, amount, tokenId) {
78
+ const hops = [];
79
+ let current = to;
80
+ for (let layer = h; layer > 0; layer--) {
81
+ const label = layers[layer]?.get(current);
82
+ if (!label?.parent)
83
+ break;
84
+ const { edge } = label.parent;
85
+ hops.push({
86
+ channelId: edge.channelId,
87
+ from: edge.from,
88
+ to: edge.to,
89
+ amount,
90
+ tokenId,
91
+ feeRate: edge.feeRate,
92
+ });
93
+ current = label.parent.prevNode;
94
+ }
95
+ return hops.reverse();
96
+ }
97
+ /** True when every edge for `tokenId` costs zero under `feeFor` (BFS is optimal). */
98
+ function isZeroFeeToken(graph, tokenId, amount, feeFor = defaultEdgeFee) {
99
+ // Fast path for the fixed-amount model: avoid per-edge bigint math.
100
+ const fast = feeFor === defaultEdgeFee;
101
+ for (const edges of graph.nodeEdges.values()) {
102
+ for (const edge of edges) {
103
+ if (edge.tokenId !== tokenId)
104
+ continue;
105
+ const zero = fast ? edge.feeRate === 0n : feeFor(amount, edge) === 0n;
106
+ if (!zero)
107
+ return false;
108
+ }
109
+ }
110
+ return true;
111
+ }
112
+ /** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
113
+ /** BFS layer tree for zero-fee single-token graphs (shortest-hop labels). */
114
+ function bfsLayers(graph, from, amount, tokenId, maxHops, stopAt) {
115
+ const layers = Array.from({ length: maxHops + 1 }, () => new Map());
116
+ layers[0].set(from, { totalFees: 0n });
117
+ const visited = new Set([from]);
118
+ let frontier = [from];
119
+ for (let depth = 1; depth <= maxHops && frontier.length > 0; depth++) {
120
+ const next = [];
121
+ const layer = layers[depth];
122
+ for (const u of frontier) {
123
+ const edges = [...(graph.nodeEdges.get(u) ?? [])].sort(_compareEdges);
124
+ for (const edge of edges) {
125
+ if (edge.tokenId !== tokenId)
126
+ continue;
127
+ if (edge.feeRate < 0n)
128
+ continue;
129
+ if (edge.availableBalance < amount)
130
+ continue;
131
+ if (visited.has(edge.to))
132
+ continue;
133
+ visited.add(edge.to);
134
+ layer.set(edge.to, { totalFees: 0n, parent: { prevNode: u, edge } });
135
+ if (stopAt !== undefined && edge.to === stopAt)
136
+ return layers;
137
+ next.push(edge.to);
138
+ }
139
+ }
140
+ frontier = next;
141
+ }
142
+ return layers;
143
+ }
144
+ /** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
145
+ function bfsRoute(graph, from, to, amount, tokenId, maxHops) {
146
+ return routeFromLayers(bfsLayers(graph, from, amount, tokenId, maxHops, to), to, amount, tokenId, maxHops);
147
+ }
148
+ function _betterSameLayer(newFees, parent, existing, h, node, layers) {
149
+ if (newFees !== existing.totalFees)
150
+ return newFees < existing.totalFees;
151
+ return _parentKey(parent, h - 1, layers) < _pathKey(h, node, layers);
152
+ }
153
+ function _pathKey(h, node, layers) {
154
+ const parts = [];
155
+ let current = node;
156
+ for (let layer = h; layer > 0; layer--) {
157
+ const label = layers[layer]?.get(current);
158
+ if (!label?.parent)
159
+ break;
160
+ parts.push(edgeKey(label.parent.edge));
161
+ current = label.parent.prevNode;
162
+ }
163
+ return parts.reverse().join('>');
164
+ }
165
+ function _parentKey(parent, hPrev, layers) {
166
+ const prefix = edgeKey(parent.edge);
167
+ const rest = hPrev === 0 ? '' : _pathKey(hPrev, parent.prevNode, layers);
168
+ return rest ? `${prefix}>${rest}` : prefix;
169
+ }
170
+ function _compareEdges(a, b) {
171
+ const ka = edgeKey(a);
172
+ const kb = edgeKey(b);
173
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
174
+ }
@@ -7,10 +7,15 @@ exports.computeRouterFeeProofHash = computeRouterFeeProofHash;
7
7
  exports.cancelPayment = cancelPayment;
8
8
  exports.executeCrossTokenPayment = executeCrossTokenPayment;
9
9
  const core_1 = require("@totemsdk/core");
10
+ const route_validation_js_1 = require("./route-validation.js");
11
+ const rates_js_1 = require("./rates.js");
10
12
  // ─── Type guard ───────────────────────────────────────────────────────────────
11
13
  function isSwapHop(hop) {
12
14
  return hop.isSwap === true;
13
15
  }
16
+ function revalidationErrorCode(message) {
17
+ return message.includes('ROUTE_REVALIDATION_FAILED') ? 'ROUTE_REVALIDATION_FAILED' : undefined;
18
+ }
14
19
  // ─── Internal helpers ─────────────────────────────────────────────────────────
15
20
  /** Determine the counterparty public key digest relative to the local signer. */
16
21
  function counterpartPkd(channel) {
@@ -59,6 +64,25 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
59
64
  return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
60
65
  }
61
66
  const plainHops = route.hops.filter(h => !isSwapHop(h));
67
+ // Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
68
+ // downstream intermediaries; the fee for the final edge belongs to the
69
+ // recipient and is not charged. Intermediary i retains
70
+ // hopAmount[i] - hopAmount[i+1]. With no fee rates this is the legacy
71
+ // same-amount behaviour.
72
+ const fees = plainHops.map((hop) => hop.feeRate && hop.feeRate > 0n ? (paymentRequest.amount * hop.feeRate) / rates_js_1.SCALE : 0n);
73
+ for (let i = 0; i < plainHops.length; i++) {
74
+ const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
75
+ plainHops[i].amount = paymentRequest.amount + downstream;
76
+ }
77
+ const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route);
78
+ if (!routeValidation.ok) {
79
+ return {
80
+ success: false,
81
+ error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
82
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
83
+ settledHops: [],
84
+ };
85
+ }
62
86
  const locked = [];
63
87
  // ── Forward: lock HTLCs ───────────────────────────────────────────────────
64
88
  for (let i = 0; i < plainHops.length; i++) {
@@ -73,6 +97,16 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
73
97
  await cancelHtlcs(ops, channels, locked, leaseProviders);
74
98
  return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
75
99
  }
100
+ const hopValidation = (0, route_validation_js_1.validateRoutingHop)(channels, hop);
101
+ if (!hopValidation.ok) {
102
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
103
+ return {
104
+ success: false,
105
+ error: `ROUTE_REVALIDATION_FAILED: ${hopValidation.error}`,
106
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
107
+ settledHops: [],
108
+ };
109
+ }
76
110
  // Timeouts decrease toward the recipient so each hop has time to claim.
77
111
  const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
78
112
  let addResult;
@@ -200,18 +234,30 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
200
234
  if (!preimage) {
201
235
  return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
202
236
  }
237
+ const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route);
238
+ if (!routeValidation.ok) {
239
+ return {
240
+ success: false,
241
+ error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
242
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
243
+ settledHops: [],
244
+ };
245
+ }
203
246
  const locked = [];
204
247
  /**
205
248
  * Lock a single HTLC, add it to `locked`, and return the htlcId.
206
249
  * Throws on any error so callers can handle rollback uniformly.
207
250
  */
208
- async function lockHTLC(channelId, amount, hashlock, timeoutBlock) {
251
+ async function lockHTLC(channelId, amount, hashlock, timeoutBlock, tokenId, sender) {
209
252
  const channel = channels.get(channelId);
210
253
  const lp = leaseProviders.get(channelId);
211
254
  if (!channel)
212
255
  throw new Error(`Channel ${channelId} not found`);
213
256
  if (!lp)
214
257
  throw new Error(`No lease provider for channel ${channelId}`);
258
+ const spend = (0, route_validation_js_1.validateChannelSpend)(channel, sender, amount, tokenId);
259
+ if (!spend.ok)
260
+ throw new Error(`ROUTE_REVALIDATION_FAILED: ${spend.error}`);
215
261
  // Let addHTLC exceptions propagate — they carry the original error message.
216
262
  const result = await ops.addHTLC(channel, {
217
263
  amount,
@@ -248,30 +294,40 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
248
294
  // Inbound channel (sender → intermediary, tokenIn side)
249
295
  const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
250
296
  try {
251
- hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout);
297
+ hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
252
298
  }
253
299
  catch (err) {
254
300
  await cancelHtlcs(ops, channels, locked, leaseProviders);
255
- return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, settledHops: [] };
301
+ return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
256
302
  }
257
303
  // Outbound channel (intermediary → recipient, tokenOut side)
258
304
  const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
305
+ const intermediary = (0, route_validation_js_1.swapIntermediary)(channels, hop);
306
+ if (!intermediary) {
307
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
308
+ return {
309
+ success: false,
310
+ error: `ROUTE_REVALIDATION_FAILED: no intermediary for ${hop.inboundChannelId}`,
311
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
312
+ settledHops: [],
313
+ };
314
+ }
259
315
  try {
260
- await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout);
316
+ await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout, hop.tokenOut, intermediary);
261
317
  }
262
318
  catch (err) {
263
319
  await cancelHtlcs(ops, channels, locked, leaseProviders);
264
- return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, settledHops: [] };
320
+ return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
265
321
  }
266
322
  }
267
323
  else {
268
324
  const timeout = paymentRequest.expiryBlock - BigInt(pos++);
269
325
  try {
270
- hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout);
326
+ hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
271
327
  }
272
328
  catch (err) {
273
329
  await cancelHtlcs(ops, channels, locked, leaseProviders);
274
- return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, settledHops: [] };
330
+ return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
275
331
  }
276
332
  }
277
333
  }
@@ -1,4 +1,12 @@
1
1
  import type { ChannelGraph, ChannelGraphEdge, SwapAnnouncement } from './types.js';
2
+ /** Internal graph revisions (topology / economics / live state). */
3
+ export interface GraphRevisions {
4
+ topology: number;
5
+ economics: number;
6
+ live: number;
7
+ }
8
+ /** Snapshot-consistent revision marker for routing caches and trees. */
9
+ export declare function getGraphRevisions(graph: ChannelGraph): GraphRevisions;
2
10
  /** Create an empty ChannelGraph. */
3
11
  export declare function createChannelGraph(): ChannelGraph;
4
12
  /**
package/dist/cjs/graph.js CHANGED
@@ -1,18 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGraphRevisions = getGraphRevisions;
3
4
  exports.createChannelGraph = createChannelGraph;
4
5
  exports.addChannel = addChannel;
5
6
  exports.removeChannel = removeChannel;
6
7
  exports.announceSwap = announceSwap;
7
8
  exports.getSwapAnnouncements = getSwapAnnouncements;
8
- const pathfind_js_1 = require("./pathfind.js");
9
+ const rates_js_1 = require("./rates.js");
10
+ const graphRevisions = new WeakMap();
11
+ function ensureRevisions(graph) {
12
+ let revisions = graphRevisions.get(graph);
13
+ if (!revisions) {
14
+ revisions = { topology: 0, economics: 0, live: 0 };
15
+ graphRevisions.set(graph, revisions);
16
+ }
17
+ return revisions;
18
+ }
19
+ /** Snapshot-consistent revision marker for routing caches and trees. */
20
+ function getGraphRevisions(graph) {
21
+ return { ...ensureRevisions(graph) };
22
+ }
23
+ function bumpTopology(graph) {
24
+ const revisions = ensureRevisions(graph);
25
+ revisions.topology += 1;
26
+ revisions.live += 1;
27
+ }
28
+ function bumpEconomics(graph) {
29
+ ensureRevisions(graph).economics += 1;
30
+ }
9
31
  /** Create an empty ChannelGraph. */
10
32
  function createChannelGraph() {
11
- return {
33
+ const graph = {
12
34
  nodeEdges: new Map(),
13
35
  edgesByChannel: new Map(),
14
36
  swapIndex: new Map(),
15
37
  };
38
+ graphRevisions.set(graph, { topology: 0, economics: 0, live: 0 });
39
+ return graph;
16
40
  }
17
41
  /**
18
42
  * Add a directed channel edge to the graph.
@@ -24,6 +48,18 @@ function createChannelGraph() {
24
48
  * entry (balance update semantics).
25
49
  */
26
50
  function addChannel(graph, edge) {
51
+ if (!edge.channelId || !edge.from || !edge.to || !edge.tokenId) {
52
+ throw new Error('addChannel requires non-empty channelId, from, to and tokenId');
53
+ }
54
+ if (edge.feeRate < 0n) {
55
+ throw new Error(`Invalid feeRate ${edge.feeRate.toString()} for channel ${edge.channelId}: must be non-negative`);
56
+ }
57
+ if (edge.availableBalance < 0n) {
58
+ throw new Error(`Invalid availableBalance ${edge.availableBalance.toString()} for channel ${edge.channelId}: must be non-negative`);
59
+ }
60
+ if (edge.htlcCapacity < 0n) {
61
+ throw new Error(`Invalid htlcCapacity ${edge.htlcCapacity.toString()} for channel ${edge.channelId}: must be non-negative`);
62
+ }
27
63
  const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
28
64
  // Replace any edge for the same (channelId, from) direction.
29
65
  const idx = existing.findIndex(e => e.from === edge.from);
@@ -39,6 +75,7 @@ function addChannel(graph, edge) {
39
75
  const nodeList = graph.nodeEdges.get(edge.from) ?? [];
40
76
  nodeList.push(edge);
41
77
  graph.nodeEdges.set(edge.from, nodeList);
78
+ bumpTopology(graph);
42
79
  }
43
80
  /**
44
81
  * Remove ALL directed edges for `channelId` (i.e. both directions).
@@ -52,6 +89,7 @@ function removeChannel(graph, channelId) {
52
89
  _removeFromNodeEdges(graph, edge);
53
90
  }
54
91
  graph.edgesByChannel.delete(channelId);
92
+ bumpTopology(graph);
55
93
  }
56
94
  function _removeFromNodeEdges(graph, edge) {
57
95
  const nodeList = graph.nodeEdges.get(edge.from);
@@ -75,7 +113,7 @@ function _removeFromNodeEdges(graph, edge) {
75
113
  * are replaced to prevent stale rate data.
76
114
  */
77
115
  function announceSwap(graph, announcement) {
78
- const rateScaled = (0, pathfind_js_1.parseRateToScaled)(announcement.rate);
116
+ const rateScaled = (0, rates_js_1.parseRateToScaled)(announcement.rate);
79
117
  if (rateScaled <= 0n) {
80
118
  throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
81
119
  }
@@ -90,6 +128,7 @@ function announceSwap(graph, announcement) {
90
128
  list.push(announcement);
91
129
  }
92
130
  graph.swapIndex.set(key, list);
131
+ bumpEconomics(graph);
93
132
  }
94
133
  /**
95
134
  * Return all swap announcements for a given token pair, or an empty array.
@@ -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;