@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.
- package/dist/bounded-search.d.ts +36 -0
- package/dist/bounded-search.js +164 -0
- package/dist/cjs/bounded-search.d.ts +36 -0
- package/dist/cjs/bounded-search.js +174 -0
- package/dist/cjs/execute.js +63 -7
- package/dist/cjs/graph.d.ts +8 -0
- package/dist/cjs/graph.js +42 -3
- package/dist/cjs/pathfind.d.ts +11 -12
- package/dist/cjs/pathfind.js +87 -189
- package/dist/cjs/rates.d.ts +9 -0
- package/dist/cjs/rates.js +27 -0
- package/dist/cjs/route-validation.d.ts +24 -0
- package/dist/cjs/route-validation.js +91 -0
- package/dist/cjs/routing-engine.d.ts +86 -0
- package/dist/cjs/routing-engine.js +154 -0
- package/dist/cjs/types.d.ts +8 -1
- package/dist/execute.js +63 -7
- package/dist/graph.d.ts +8 -0
- package/dist/graph.js +40 -2
- package/dist/pathfind.d.ts +11 -12
- package/dist/pathfind.js +84 -186
- package/dist/rates.d.ts +9 -0
- package/dist/rates.js +22 -0
- package/dist/route-validation.d.ts +24 -0
- package/dist/route-validation.js +84 -0
- package/dist/routing-engine.d.ts +86 -0
- package/dist/routing-engine.js +147 -0
- package/dist/types.d.ts +8 -1
- package/package.json +5 -4
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded routing core (RFC-055 Phase 1).
|
|
3
|
+
*
|
|
4
|
+
* Internal module shared by the point-to-point engine, the one-to-many tree and
|
|
5
|
+
* cross-token routing. Not exported from the package barrel yet.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChannelGraph, ChannelGraphEdge, Route, RoutingHop } from './types.js';
|
|
8
|
+
export type FeeFunction = (amount: bigint, edge: ChannelGraphEdge) => bigint;
|
|
9
|
+
/** Default cost model: amount × feeRate / SCALE, fixed amount per hop. */
|
|
10
|
+
export declare function defaultEdgeFee(amount: bigint, edge: ChannelGraphEdge): bigint;
|
|
11
|
+
export interface SearchParent {
|
|
12
|
+
prevNode: string;
|
|
13
|
+
edge: ChannelGraphEdge;
|
|
14
|
+
}
|
|
15
|
+
export interface SearchLabel {
|
|
16
|
+
totalFees: bigint;
|
|
17
|
+
parent?: SearchParent;
|
|
18
|
+
}
|
|
19
|
+
/** Deterministic edge key used for tie-breaking and BFS ordering. */
|
|
20
|
+
export declare function edgeKey(edge: {
|
|
21
|
+
channelId: string;
|
|
22
|
+
from: string;
|
|
23
|
+
to: string;
|
|
24
|
+
}): string;
|
|
25
|
+
/** Layered (hops, node) search. layers[h][v] is the cheapest path using exactly h edges. */
|
|
26
|
+
export declare function computeLayers(graph: ChannelGraph, from: string, amount: bigint, tokenId: string, maxHops: number, feeFor?: FeeFunction): Array<Map<string, SearchLabel>>;
|
|
27
|
+
/** Select the cheapest (fees, hops) label for `to` and reconstruct its path. */
|
|
28
|
+
export declare function routeFromLayers(layers: Array<Map<string, SearchLabel>>, to: string, amount: bigint, tokenId: string, maxHops: number): Route | null;
|
|
29
|
+
export declare function reconstructFromLayers(layers: Array<Map<string, SearchLabel>>, h: number, to: string, amount: bigint, tokenId: string): RoutingHop[];
|
|
30
|
+
/** True when every edge for `tokenId` costs zero under `feeFor` (BFS is optimal). */
|
|
31
|
+
export declare function isZeroFeeToken(graph: ChannelGraph, tokenId: string, amount: bigint, feeFor?: FeeFunction): boolean;
|
|
32
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
33
|
+
/** BFS layer tree for zero-fee single-token graphs (shortest-hop labels). */
|
|
34
|
+
export declare function bfsLayers(graph: ChannelGraph, from: string, amount: bigint, tokenId: string, maxHops: number, stopAt?: string): Array<Map<string, SearchLabel>>;
|
|
35
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
36
|
+
export declare function bfsRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, maxHops: number): Route | null;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { SCALE } from './rates.js';
|
|
2
|
+
/** Default cost model: amount × feeRate / SCALE, fixed amount per hop. */
|
|
3
|
+
export function defaultEdgeFee(amount, edge) {
|
|
4
|
+
return (amount * edge.feeRate) / SCALE;
|
|
5
|
+
}
|
|
6
|
+
/** Deterministic edge key used for tie-breaking and BFS ordering. */
|
|
7
|
+
export function edgeKey(edge) {
|
|
8
|
+
return `${edge.channelId}|${edge.from}|${edge.to}`;
|
|
9
|
+
}
|
|
10
|
+
/** Layered (hops, node) search. layers[h][v] is the cheapest path using exactly h edges. */
|
|
11
|
+
export function computeLayers(graph, from, amount, tokenId, maxHops, feeFor = defaultEdgeFee) {
|
|
12
|
+
const layers = Array.from({ length: maxHops + 1 }, () => new Map());
|
|
13
|
+
layers[0].set(from, { totalFees: 0n });
|
|
14
|
+
for (let h = 1; h <= maxHops; h++) {
|
|
15
|
+
const prev = layers[h - 1];
|
|
16
|
+
if (prev.size === 0)
|
|
17
|
+
break;
|
|
18
|
+
const curr = layers[h];
|
|
19
|
+
for (const [u, label] of prev) {
|
|
20
|
+
const edges = graph.nodeEdges.get(u);
|
|
21
|
+
if (!edges)
|
|
22
|
+
continue;
|
|
23
|
+
for (const edge of edges) {
|
|
24
|
+
if (edge.tokenId !== tokenId)
|
|
25
|
+
continue;
|
|
26
|
+
if (edge.feeRate < 0n)
|
|
27
|
+
continue;
|
|
28
|
+
if (edge.availableBalance < amount)
|
|
29
|
+
continue;
|
|
30
|
+
const newFees = label.totalFees + feeFor(amount, edge);
|
|
31
|
+
const parent = { prevNode: u, edge };
|
|
32
|
+
const existing = curr.get(edge.to);
|
|
33
|
+
if (!existing || _betterSameLayer(newFees, parent, existing, h, edge.to, layers)) {
|
|
34
|
+
curr.set(edge.to, { totalFees: newFees, parent });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return layers;
|
|
40
|
+
}
|
|
41
|
+
/** Select the cheapest (fees, hops) label for `to` and reconstruct its path. */
|
|
42
|
+
export function routeFromLayers(layers, to, amount, tokenId, maxHops) {
|
|
43
|
+
let bestH = -1;
|
|
44
|
+
let bestFees = 0n;
|
|
45
|
+
for (let h = 0; h <= maxHops; h++) {
|
|
46
|
+
const label = layers[h]?.get(to);
|
|
47
|
+
if (!label)
|
|
48
|
+
continue;
|
|
49
|
+
if (bestH === -1 ||
|
|
50
|
+
label.totalFees < bestFees ||
|
|
51
|
+
(label.totalFees === bestFees && h < bestH)) {
|
|
52
|
+
bestH = h;
|
|
53
|
+
bestFees = label.totalFees;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (bestH === -1)
|
|
57
|
+
return null;
|
|
58
|
+
const hops = reconstructFromLayers(layers, bestH, to, amount, tokenId);
|
|
59
|
+
return {
|
|
60
|
+
hops,
|
|
61
|
+
totalFees: bestFees,
|
|
62
|
+
tokenIn: tokenId,
|
|
63
|
+
tokenOut: tokenId,
|
|
64
|
+
estimatedBlocks: hops.length * 2,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export function reconstructFromLayers(layers, h, to, amount, tokenId) {
|
|
68
|
+
const hops = [];
|
|
69
|
+
let current = to;
|
|
70
|
+
for (let layer = h; layer > 0; layer--) {
|
|
71
|
+
const label = layers[layer]?.get(current);
|
|
72
|
+
if (!label?.parent)
|
|
73
|
+
break;
|
|
74
|
+
const { edge } = label.parent;
|
|
75
|
+
hops.push({
|
|
76
|
+
channelId: edge.channelId,
|
|
77
|
+
from: edge.from,
|
|
78
|
+
to: edge.to,
|
|
79
|
+
amount,
|
|
80
|
+
tokenId,
|
|
81
|
+
feeRate: edge.feeRate,
|
|
82
|
+
});
|
|
83
|
+
current = label.parent.prevNode;
|
|
84
|
+
}
|
|
85
|
+
return hops.reverse();
|
|
86
|
+
}
|
|
87
|
+
/** True when every edge for `tokenId` costs zero under `feeFor` (BFS is optimal). */
|
|
88
|
+
export function isZeroFeeToken(graph, tokenId, amount, feeFor = defaultEdgeFee) {
|
|
89
|
+
// Fast path for the fixed-amount model: avoid per-edge bigint math.
|
|
90
|
+
const fast = feeFor === defaultEdgeFee;
|
|
91
|
+
for (const edges of graph.nodeEdges.values()) {
|
|
92
|
+
for (const edge of edges) {
|
|
93
|
+
if (edge.tokenId !== tokenId)
|
|
94
|
+
continue;
|
|
95
|
+
const zero = fast ? edge.feeRate === 0n : feeFor(amount, edge) === 0n;
|
|
96
|
+
if (!zero)
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
103
|
+
/** BFS layer tree for zero-fee single-token graphs (shortest-hop labels). */
|
|
104
|
+
export function bfsLayers(graph, from, amount, tokenId, maxHops, stopAt) {
|
|
105
|
+
const layers = Array.from({ length: maxHops + 1 }, () => new Map());
|
|
106
|
+
layers[0].set(from, { totalFees: 0n });
|
|
107
|
+
const visited = new Set([from]);
|
|
108
|
+
let frontier = [from];
|
|
109
|
+
for (let depth = 1; depth <= maxHops && frontier.length > 0; depth++) {
|
|
110
|
+
const next = [];
|
|
111
|
+
const layer = layers[depth];
|
|
112
|
+
for (const u of frontier) {
|
|
113
|
+
const edges = [...(graph.nodeEdges.get(u) ?? [])].sort(_compareEdges);
|
|
114
|
+
for (const edge of edges) {
|
|
115
|
+
if (edge.tokenId !== tokenId)
|
|
116
|
+
continue;
|
|
117
|
+
if (edge.feeRate < 0n)
|
|
118
|
+
continue;
|
|
119
|
+
if (edge.availableBalance < amount)
|
|
120
|
+
continue;
|
|
121
|
+
if (visited.has(edge.to))
|
|
122
|
+
continue;
|
|
123
|
+
visited.add(edge.to);
|
|
124
|
+
layer.set(edge.to, { totalFees: 0n, parent: { prevNode: u, edge } });
|
|
125
|
+
if (stopAt !== undefined && edge.to === stopAt)
|
|
126
|
+
return layers;
|
|
127
|
+
next.push(edge.to);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
frontier = next;
|
|
131
|
+
}
|
|
132
|
+
return layers;
|
|
133
|
+
}
|
|
134
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
135
|
+
export function bfsRoute(graph, from, to, amount, tokenId, maxHops) {
|
|
136
|
+
return routeFromLayers(bfsLayers(graph, from, amount, tokenId, maxHops, to), to, amount, tokenId, maxHops);
|
|
137
|
+
}
|
|
138
|
+
function _betterSameLayer(newFees, parent, existing, h, node, layers) {
|
|
139
|
+
if (newFees !== existing.totalFees)
|
|
140
|
+
return newFees < existing.totalFees;
|
|
141
|
+
return _parentKey(parent, h - 1, layers) < _pathKey(h, node, layers);
|
|
142
|
+
}
|
|
143
|
+
function _pathKey(h, node, layers) {
|
|
144
|
+
const parts = [];
|
|
145
|
+
let current = node;
|
|
146
|
+
for (let layer = h; layer > 0; layer--) {
|
|
147
|
+
const label = layers[layer]?.get(current);
|
|
148
|
+
if (!label?.parent)
|
|
149
|
+
break;
|
|
150
|
+
parts.push(edgeKey(label.parent.edge));
|
|
151
|
+
current = label.parent.prevNode;
|
|
152
|
+
}
|
|
153
|
+
return parts.reverse().join('>');
|
|
154
|
+
}
|
|
155
|
+
function _parentKey(parent, hPrev, layers) {
|
|
156
|
+
const prefix = edgeKey(parent.edge);
|
|
157
|
+
const rest = hPrev === 0 ? '' : _pathKey(hPrev, parent.prevNode, layers);
|
|
158
|
+
return rest ? `${prefix}>${rest}` : prefix;
|
|
159
|
+
}
|
|
160
|
+
function _compareEdges(a, b) {
|
|
161
|
+
const ka = edgeKey(a);
|
|
162
|
+
const kb = edgeKey(b);
|
|
163
|
+
return ka < kb ? -1 : ka > kb ? 1 : 0;
|
|
164
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded routing core (RFC-055 Phase 1).
|
|
3
|
+
*
|
|
4
|
+
* Internal module shared by the point-to-point engine, the one-to-many tree and
|
|
5
|
+
* cross-token routing. Not exported from the package barrel yet.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChannelGraph, ChannelGraphEdge, Route, RoutingHop } from './types.js';
|
|
8
|
+
export type FeeFunction = (amount: bigint, edge: ChannelGraphEdge) => bigint;
|
|
9
|
+
/** Default cost model: amount × feeRate / SCALE, fixed amount per hop. */
|
|
10
|
+
export declare function defaultEdgeFee(amount: bigint, edge: ChannelGraphEdge): bigint;
|
|
11
|
+
export interface SearchParent {
|
|
12
|
+
prevNode: string;
|
|
13
|
+
edge: ChannelGraphEdge;
|
|
14
|
+
}
|
|
15
|
+
export interface SearchLabel {
|
|
16
|
+
totalFees: bigint;
|
|
17
|
+
parent?: SearchParent;
|
|
18
|
+
}
|
|
19
|
+
/** Deterministic edge key used for tie-breaking and BFS ordering. */
|
|
20
|
+
export declare function edgeKey(edge: {
|
|
21
|
+
channelId: string;
|
|
22
|
+
from: string;
|
|
23
|
+
to: string;
|
|
24
|
+
}): string;
|
|
25
|
+
/** Layered (hops, node) search. layers[h][v] is the cheapest path using exactly h edges. */
|
|
26
|
+
export declare function computeLayers(graph: ChannelGraph, from: string, amount: bigint, tokenId: string, maxHops: number, feeFor?: FeeFunction): Array<Map<string, SearchLabel>>;
|
|
27
|
+
/** Select the cheapest (fees, hops) label for `to` and reconstruct its path. */
|
|
28
|
+
export declare function routeFromLayers(layers: Array<Map<string, SearchLabel>>, to: string, amount: bigint, tokenId: string, maxHops: number): Route | null;
|
|
29
|
+
export declare function reconstructFromLayers(layers: Array<Map<string, SearchLabel>>, h: number, to: string, amount: bigint, tokenId: string): RoutingHop[];
|
|
30
|
+
/** True when every edge for `tokenId` costs zero under `feeFor` (BFS is optimal). */
|
|
31
|
+
export declare function isZeroFeeToken(graph: ChannelGraph, tokenId: string, amount: bigint, feeFor?: FeeFunction): boolean;
|
|
32
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
33
|
+
/** BFS layer tree for zero-fee single-token graphs (shortest-hop labels). */
|
|
34
|
+
export declare function bfsLayers(graph: ChannelGraph, from: string, amount: bigint, tokenId: string, maxHops: number, stopAt?: string): Array<Map<string, SearchLabel>>;
|
|
35
|
+
/** Bounded BFS for zero-fee single-token graphs (fewest hops, deterministic). */
|
|
36
|
+
export declare function bfsRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, maxHops: number): Route | null;
|
|
@@ -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
|
+
}
|
package/dist/cjs/execute.js
CHANGED
|
@@ -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
|
}
|
package/dist/cjs/graph.d.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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,
|
|
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.
|