@totemsdk/omnia-router 0.2.1 → 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.
Files changed (47) hide show
  1. package/dist/bounded-search.d.ts +36 -0
  2. package/dist/bounded-search.js +164 -0
  3. package/dist/cjs/bounded-search.d.ts +36 -0
  4. package/dist/cjs/bounded-search.js +174 -0
  5. package/dist/cjs/durable-router-ledger.d.ts +60 -0
  6. package/dist/cjs/durable-router-ledger.js +88 -0
  7. package/dist/cjs/execute.d.ts +45 -0
  8. package/dist/cjs/execute.js +359 -0
  9. package/dist/cjs/forward.d.ts +50 -0
  10. package/dist/cjs/forward.js +56 -0
  11. package/dist/cjs/graph.d.ts +40 -0
  12. package/dist/cjs/graph.js +141 -0
  13. package/dist/cjs/index.d.ts +10 -0
  14. package/dist/cjs/index.js +29 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/pathfind.d.ts +24 -0
  17. package/dist/cjs/pathfind.js +151 -0
  18. package/dist/cjs/rates.d.ts +9 -0
  19. package/dist/cjs/rates.js +27 -0
  20. package/dist/cjs/request.d.ts +19 -0
  21. package/dist/cjs/request.js +38 -0
  22. package/dist/cjs/route-validation.d.ts +24 -0
  23. package/dist/cjs/route-validation.js +91 -0
  24. package/dist/cjs/routing-engine.d.ts +86 -0
  25. package/dist/cjs/routing-engine.js +154 -0
  26. package/dist/cjs/types.d.ts +207 -0
  27. package/dist/cjs/types.js +10 -0
  28. package/dist/durable-router-ledger.js +6 -9
  29. package/dist/execute.js +72 -24
  30. package/dist/forward.d.ts +50 -0
  31. package/dist/forward.js +53 -0
  32. package/dist/graph.d.ts +8 -0
  33. package/dist/graph.js +46 -15
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +7 -26
  36. package/dist/pathfind.d.ts +11 -12
  37. package/dist/pathfind.js +88 -196
  38. package/dist/rates.d.ts +9 -0
  39. package/dist/rates.js +22 -0
  40. package/dist/request.js +5 -9
  41. package/dist/route-validation.d.ts +24 -0
  42. package/dist/route-validation.js +84 -0
  43. package/dist/routing-engine.d.ts +86 -0
  44. package/dist/routing-engine.js +147 -0
  45. package/dist/types.d.ts +8 -1
  46. package/dist/types.js +1 -2
  47. package/package.json +17 -10
package/dist/graph.js CHANGED
@@ -1,18 +1,34 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createChannelGraph = createChannelGraph;
4
- exports.addChannel = addChannel;
5
- exports.removeChannel = removeChannel;
6
- exports.announceSwap = announceSwap;
7
- exports.getSwapAnnouncements = getSwapAnnouncements;
8
- const pathfind_js_1 = require("./pathfind.js");
1
+ import { parseRateToScaled } from './rates.js';
2
+ const graphRevisions = new WeakMap();
3
+ function ensureRevisions(graph) {
4
+ let revisions = graphRevisions.get(graph);
5
+ if (!revisions) {
6
+ revisions = { topology: 0, economics: 0, live: 0 };
7
+ graphRevisions.set(graph, revisions);
8
+ }
9
+ return revisions;
10
+ }
11
+ /** Snapshot-consistent revision marker for routing caches and trees. */
12
+ export function getGraphRevisions(graph) {
13
+ return { ...ensureRevisions(graph) };
14
+ }
15
+ function bumpTopology(graph) {
16
+ const revisions = ensureRevisions(graph);
17
+ revisions.topology += 1;
18
+ revisions.live += 1;
19
+ }
20
+ function bumpEconomics(graph) {
21
+ ensureRevisions(graph).economics += 1;
22
+ }
9
23
  /** Create an empty ChannelGraph. */
10
- function createChannelGraph() {
11
- return {
24
+ export function createChannelGraph() {
25
+ const graph = {
12
26
  nodeEdges: new Map(),
13
27
  edgesByChannel: new Map(),
14
28
  swapIndex: new Map(),
15
29
  };
30
+ graphRevisions.set(graph, { topology: 0, economics: 0, live: 0 });
31
+ return graph;
16
32
  }
17
33
  /**
18
34
  * Add a directed channel edge to the graph.
@@ -23,7 +39,19 @@ function createChannelGraph() {
23
39
  * `addChannel` twice with the same `(channelId, from)` replaces the first
24
40
  * entry (balance update semantics).
25
41
  */
26
- function addChannel(graph, edge) {
42
+ export function addChannel(graph, edge) {
43
+ if (!edge.channelId || !edge.from || !edge.to || !edge.tokenId) {
44
+ throw new Error('addChannel requires non-empty channelId, from, to and tokenId');
45
+ }
46
+ if (edge.feeRate < 0n) {
47
+ throw new Error(`Invalid feeRate ${edge.feeRate.toString()} for channel ${edge.channelId}: must be non-negative`);
48
+ }
49
+ if (edge.availableBalance < 0n) {
50
+ throw new Error(`Invalid availableBalance ${edge.availableBalance.toString()} for channel ${edge.channelId}: must be non-negative`);
51
+ }
52
+ if (edge.htlcCapacity < 0n) {
53
+ throw new Error(`Invalid htlcCapacity ${edge.htlcCapacity.toString()} for channel ${edge.channelId}: must be non-negative`);
54
+ }
27
55
  const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
28
56
  // Replace any edge for the same (channelId, from) direction.
29
57
  const idx = existing.findIndex(e => e.from === edge.from);
@@ -39,12 +67,13 @@ function addChannel(graph, edge) {
39
67
  const nodeList = graph.nodeEdges.get(edge.from) ?? [];
40
68
  nodeList.push(edge);
41
69
  graph.nodeEdges.set(edge.from, nodeList);
70
+ bumpTopology(graph);
42
71
  }
43
72
  /**
44
73
  * Remove ALL directed edges for `channelId` (i.e. both directions).
45
74
  * No-op if the channelId is not present.
46
75
  */
47
- function removeChannel(graph, channelId) {
76
+ export function removeChannel(graph, channelId) {
48
77
  const edges = graph.edgesByChannel.get(channelId);
49
78
  if (!edges)
50
79
  return;
@@ -52,6 +81,7 @@ function removeChannel(graph, channelId) {
52
81
  _removeFromNodeEdges(graph, edge);
53
82
  }
54
83
  graph.edgesByChannel.delete(channelId);
84
+ bumpTopology(graph);
55
85
  }
56
86
  function _removeFromNodeEdges(graph, edge) {
57
87
  const nodeList = graph.nodeEdges.get(edge.from);
@@ -74,8 +104,8 @@ function _removeFromNodeEdges(graph, edge) {
74
104
  * Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
75
105
  * are replaced to prevent stale rate data.
76
106
  */
77
- function announceSwap(graph, announcement) {
78
- const rateScaled = (0, pathfind_js_1.parseRateToScaled)(announcement.rate);
107
+ export function announceSwap(graph, announcement) {
108
+ const rateScaled = parseRateToScaled(announcement.rate);
79
109
  if (rateScaled <= 0n) {
80
110
  throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
81
111
  }
@@ -90,11 +120,12 @@ function announceSwap(graph, announcement) {
90
120
  list.push(announcement);
91
121
  }
92
122
  graph.swapIndex.set(key, list);
123
+ bumpEconomics(graph);
93
124
  }
94
125
  /**
95
126
  * Return all swap announcements for a given token pair, or an empty array.
96
127
  */
97
- function getSwapAnnouncements(graph, tokenIn, tokenOut) {
128
+ export function getSwapAnnouncements(graph, tokenIn, tokenOut) {
98
129
  return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
99
130
  }
100
131
  function _swapKey(tokenIn, tokenOut) {
package/dist/index.d.ts CHANGED
@@ -4,5 +4,7 @@ export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from '.
4
4
  export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
5
5
  export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
6
6
  export type { RouterFeeProof } from './types.js';
7
+ export { createCleartextRoutingCodec } from './forward.js';
8
+ export type { RoutingEnvelopeCodec, ForwardHop, PeelResult } from './forward.js';
7
9
  export { createDurableRouterLedger, } from './durable-router-ledger.js';
8
10
  export type { SettledSegment, RouterLedgerState, DurableRouterLedger, DurableRouterLedgerOptions, } from './durable-router-ledger.js';
package/dist/index.js CHANGED
@@ -1,26 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDurableRouterLedger = exports.ROUTER_FEE_PROOF_DOMAIN = exports.computeRouterFeeProofHash = exports.buildRouterFeeProof = exports.cancelPayment = exports.executeCrossTokenPayment = exports.executeMultiHopPayment = exports.buildCrossTokenRequest = exports.buildPaymentRequest = exports.parseRateToScaled = exports.applyRate = exports.findCrossTokenRoute = exports.findRoute = exports.getSwapAnnouncements = exports.announceSwap = exports.removeChannel = exports.addChannel = exports.createChannelGraph = void 0;
4
- var graph_js_1 = require("./graph.js");
5
- Object.defineProperty(exports, "createChannelGraph", { enumerable: true, get: function () { return graph_js_1.createChannelGraph; } });
6
- Object.defineProperty(exports, "addChannel", { enumerable: true, get: function () { return graph_js_1.addChannel; } });
7
- Object.defineProperty(exports, "removeChannel", { enumerable: true, get: function () { return graph_js_1.removeChannel; } });
8
- Object.defineProperty(exports, "announceSwap", { enumerable: true, get: function () { return graph_js_1.announceSwap; } });
9
- Object.defineProperty(exports, "getSwapAnnouncements", { enumerable: true, get: function () { return graph_js_1.getSwapAnnouncements; } });
10
- var pathfind_js_1 = require("./pathfind.js");
11
- Object.defineProperty(exports, "findRoute", { enumerable: true, get: function () { return pathfind_js_1.findRoute; } });
12
- Object.defineProperty(exports, "findCrossTokenRoute", { enumerable: true, get: function () { return pathfind_js_1.findCrossTokenRoute; } });
13
- Object.defineProperty(exports, "applyRate", { enumerable: true, get: function () { return pathfind_js_1.applyRate; } });
14
- Object.defineProperty(exports, "parseRateToScaled", { enumerable: true, get: function () { return pathfind_js_1.parseRateToScaled; } });
15
- var request_js_1 = require("./request.js");
16
- Object.defineProperty(exports, "buildPaymentRequest", { enumerable: true, get: function () { return request_js_1.buildPaymentRequest; } });
17
- Object.defineProperty(exports, "buildCrossTokenRequest", { enumerable: true, get: function () { return request_js_1.buildCrossTokenRequest; } });
18
- var execute_js_1 = require("./execute.js");
19
- Object.defineProperty(exports, "executeMultiHopPayment", { enumerable: true, get: function () { return execute_js_1.executeMultiHopPayment; } });
20
- Object.defineProperty(exports, "executeCrossTokenPayment", { enumerable: true, get: function () { return execute_js_1.executeCrossTokenPayment; } });
21
- Object.defineProperty(exports, "cancelPayment", { enumerable: true, get: function () { return execute_js_1.cancelPayment; } });
22
- Object.defineProperty(exports, "buildRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.buildRouterFeeProof; } });
23
- Object.defineProperty(exports, "computeRouterFeeProofHash", { enumerable: true, get: function () { return execute_js_1.computeRouterFeeProofHash; } });
24
- Object.defineProperty(exports, "ROUTER_FEE_PROOF_DOMAIN", { enumerable: true, get: function () { return execute_js_1.ROUTER_FEE_PROOF_DOMAIN; } });
25
- var durable_router_ledger_js_1 = require("./durable-router-ledger.js");
26
- Object.defineProperty(exports, "createDurableRouterLedger", { enumerable: true, get: function () { return durable_router_ledger_js_1.createDurableRouterLedger; } });
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, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
5
+ // RFC-035 B4 — pluggable forwarding envelopes (cleartext now; onion behind the same seam).
6
+ export { createCleartextRoutingCodec } from './forward.js';
7
+ export { createDurableRouterLedger, } from './durable-router-ledger.js';
@@ -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;
package/dist/pathfind.js CHANGED
@@ -1,169 +1,85 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseRateToScaled = parseRateToScaled;
4
- exports.applyRate = applyRate;
5
- exports.findRoute = findRoute;
6
- exports.findCrossTokenRoute = findCrossTokenRoute;
7
- 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
- }
1
+ import { getSwapAnnouncements } from './graph.js';
2
+ import { applyRate, parseRateToScaled } from './rates.js';
3
+ import { defaultEdgeFee as edgeFee, edgeKey } from './bounded-search.js';
4
+ import { createRoutingGraphSnapshot, selectRoutingEngine, FIXED_AMOUNT_COST_MODEL, DEFAULT_MAX_HOPS, } from './routing-engine.js';
5
+ export { parseRateToScaled, applyRate };
6
+ // ─── Single-token ─────────────────────────────────────────────────────────────
30
7
  /**
31
8
  * 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.
9
+ * `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
10
+ * availableBalance. Returns null if no path exists within maxHops.
34
11
  *
35
- * Returns null if no path exists within maxHops.
12
+ * Delegates to the routing engine (zero-fee BFS / layered bounded search).
36
13
  */
37
- function findRoute(graph, from, to, amount, tokenId, opts) {
38
- return _reconstruct(graph, from, to, amount, tokenId, opts?.maxHops ?? 8);
14
+ export function findRoute(graph, from, to, amount, tokenId, opts) {
15
+ const snapshot = createRoutingGraphSnapshot(graph);
16
+ const engine = selectRoutingEngine(snapshot);
17
+ return engine.findRoute(snapshot, {
18
+ source: from,
19
+ destination: to,
20
+ amount,
21
+ tokenId,
22
+ ...(opts?.maxHops === undefined ? {} : { maxHops: opts.maxHops }),
23
+ }, FIXED_AMOUNT_COST_MODEL);
39
24
  }
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 ─────────────────────────────────────────────────────
25
+ // ─── Cross-token ──────────────────────────────────────────────────────────────
93
26
  /**
94
27
  * 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
28
+ * recipient receives `tokenOut`. The path may include one or more swap hops
96
29
  * provided by bridging intermediaries registered via announceSwap.
97
30
  *
98
31
  * Selection criteria: lowest total fee (including swap fee), then fewest hops,
99
- * then fewest swap hops.
32
+ * then fewest swap hops, then a deterministic route key.
33
+ *
34
+ * `maxHops` is a **global** end-to-end budget: preHops + 1 (swap) + postHops
35
+ * must not exceed it (RFC-055 §2.5). The inbound leg is computed once for all
36
+ * announcements; the outbound leg is cached per `(postDst, amountOut, tokenOut)`.
100
37
  */
101
- function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
102
- const announcements = (0, graph_js_1.getSwapAnnouncements)(graph, tokenIn, tokenOut);
38
+ export function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
39
+ const announcements = getSwapAnnouncements(graph, tokenIn, tokenOut);
103
40
  if (announcements.length === 0)
104
41
  return null;
42
+ const maxHops = opts?.maxHops ?? DEFAULT_MAX_HOPS;
43
+ if (!Number.isInteger(maxHops) || maxHops < 0) {
44
+ throw new Error(`maxHops must be a non-negative integer (got ${String(opts?.maxHops)})`);
45
+ }
46
+ // A swap consumes one hop; pre + swap + post must fit the global budget.
47
+ if (amountIn <= 0n || maxHops < 1)
48
+ return null;
49
+ const snapshot = createRoutingGraphSnapshot(graph);
50
+ const engine = selectRoutingEngine(snapshot);
51
+ // One bounded inbound tree serves every announcement.
52
+ const preTree = engine.computeTree(snapshot, { source: from, amount: amountIn, tokenId: tokenIn, maxHops: maxHops - 1 }, FIXED_AMOUNT_COST_MODEL);
53
+ const postCache = new Map();
105
54
  let best = null;
106
55
  for (const ann of announcements) {
107
- // Validate maxAmountIn
108
56
  if (amountIn > ann.maxAmountIn)
109
57
  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
58
  const inboundEdges = graph.edgesByChannel.get(ann.inboundChannelId) ?? [];
114
59
  const inboundEdge = inboundEdges.find(e => e.to === ann.intermediaryPubKey && e.tokenId === tokenIn);
115
60
  if (!inboundEdge)
116
61
  continue;
117
- // Check the inbound edge has sufficient balance
118
62
  if (inboundEdge.availableBalance < amountIn)
119
63
  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
64
  const amountOut = applyRate(amountIn, ann.rate);
123
65
  if (amountOut <= 0n)
124
66
  continue;
125
- // Outbound segment: intermediary → recipient via tokenOut.
126
- // Look up the directed edge whose `from` is the intermediary.
127
67
  const outboundEdges = graph.edgesByChannel.get(ann.outboundChannelId) ?? [];
128
68
  const outboundEdge = outboundEdges.find(e => e.from === ann.intermediaryPubKey && e.tokenId === tokenOut);
129
69
  if (!outboundEdge)
130
70
  continue;
131
71
  if (outboundEdge.availableBalance < amountOut)
132
72
  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);
73
+ const preSrc = inboundEdge.from;
74
+ const postDst = outboundEdge.to;
75
+ const postKey = `${postDst}|${amountOut.toString()}|${tokenOut}|${maxHops - 1}`;
76
+ let postTree = postCache.get(postKey);
77
+ if (!postTree) {
78
+ postTree = engine.computeTree(snapshot, { source: postDst, amount: amountOut, tokenId: tokenOut, maxHops: maxHops - 1 }, FIXED_AMOUNT_COST_MODEL);
79
+ postCache.set(postKey, postTree);
153
80
  }
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)
81
+ const inboundFee = edgeFee(amountIn, inboundEdge);
82
+ const outboundFee = edgeFee(amountOut, outboundEdge);
167
83
  const swapHop = {
168
84
  isSwap: true,
169
85
  channelId: ann.inboundChannelId,
@@ -179,75 +95,51 @@ function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts)
179
95
  inboundChannelId: ann.inboundChannelId,
180
96
  outboundChannelId: ann.outboundChannelId,
181
97
  };
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;
98
+ for (let preH = 0; preH <= maxHops - 1; preH++) {
99
+ const preLabel = preTree.labelAt(preSrc, preH);
100
+ if (!preLabel)
101
+ continue;
102
+ for (let postH = 0; postH <= maxHops - 1 - preH; postH++) {
103
+ const postLabel = postTree.labelAt(to, postH);
104
+ if (!postLabel)
105
+ continue;
106
+ const allHops = [
107
+ ...preLabel.route.hops,
108
+ swapHop,
109
+ ...postLabel.route.hops,
110
+ ];
111
+ const candidate = {
112
+ hops: allHops,
113
+ totalFees: preLabel.totalFees + inboundFee + outboundFee + postLabel.totalFees,
114
+ tokenIn,
115
+ tokenOut,
116
+ estimatedBlocks: allHops.length * 2,
117
+ swapHops: [swapHop],
118
+ };
119
+ if (!best || _crossTokenBetter(candidate, best)) {
120
+ best = candidate;
121
+ }
122
+ }
202
123
  }
203
124
  }
204
125
  return best;
205
126
  }
206
127
  // ─── 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
128
  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 };
129
+ if (a.totalFees !== b.totalFees)
130
+ return a.totalFees < b.totalFees;
131
+ if (a.hops.length !== b.hops.length)
132
+ return a.hops.length < b.hops.length;
133
+ if (a.swapHops.length !== b.swapHops.length)
134
+ return a.swapHops.length < b.swapHops.length;
135
+ return _routeKey(a.hops) < _routeKey(b.hops);
239
136
  }
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;
137
+ function _routeKey(hops) {
138
+ return hops.map((hop) => {
139
+ if (hop.isSwap) {
140
+ const swap = hop;
141
+ return `swap:${swap.channelId}:${swap.outboundChannelId}`;
247
142
  }
248
- }
249
- return queue.splice(minIdx, 1)[0];
250
- }
251
- function _enqueue(queue, state) {
252
- queue.push(state);
143
+ return edgeKey(hop);
144
+ }).join('>');
253
145
  }
@@ -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;
package/dist/rates.js ADDED
@@ -0,0 +1,22 @@
1
+ /** Fixed-point scale shared by routing fees and swap rates. */
2
+ export 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 function parseRateToScaled(rate) {
8
+ const neg = rate.startsWith('-');
9
+ const abs = neg ? rate.slice(1) : rate;
10
+ const dot = abs.indexOf('.');
11
+ const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
12
+ const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
13
+ const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
14
+ const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
15
+ const result = BigInt(intPart) * SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
16
+ return neg ? -result : result;
17
+ }
18
+ /** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
19
+ export function applyRate(amountIn, rate) {
20
+ const rateScaled = parseRateToScaled(rate);
21
+ return (amountIn * rateScaled) / SCALE;
22
+ }
package/dist/request.js CHANGED
@@ -1,8 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildPaymentRequest = buildPaymentRequest;
4
- exports.buildCrossTokenRequest = buildCrossTokenRequest;
5
- const core_1 = require("@totemsdk/core");
1
+ import { F, hex } from '@totemsdk/core';
6
2
  /**
7
3
  * Generate a random 32-byte preimage, compute SHA3-256(preimage) as the
8
4
  * hashlock, and return a PaymentRequest that is ready to share.
@@ -14,11 +10,11 @@ const core_1 = require("@totemsdk/core");
14
10
  * Compatible with Bare/Pear environments: uses globalThis.crypto.getRandomValues
15
11
  * (Web Crypto API, available in Node ≥18, browsers, and Pear/Bare runtimes).
16
12
  */
17
- function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
13
+ export function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
18
14
  const preimageBytes = new Uint8Array(32);
19
15
  globalThis.crypto.getRandomValues(preimageBytes);
20
- const preimage = '0x' + (0, core_1.hex)(preimageBytes);
21
- const hashlock = '0x' + (0, core_1.hex)((0, core_1.F)(preimageBytes));
16
+ const preimage = '0x' + hex(preimageBytes);
17
+ const hashlock = '0x' + hex(F(preimageBytes));
22
18
  return {
23
19
  hashlock,
24
20
  preimage,
@@ -33,6 +29,6 @@ function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
33
29
  * to receive. The API is identical to buildPaymentRequest — the distinction
34
30
  * is conceptual (recipient generates hashlock; sender sources liquidity).
35
31
  */
36
- function buildCrossTokenRequest(amountOut, tokenOut, expiryBlock, description) {
32
+ export function buildCrossTokenRequest(amountOut, tokenOut, expiryBlock, description) {
37
33
  return buildPaymentRequest(amountOut, tokenOut, expiryBlock, description);
38
34
  }
@@ -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;