@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.
- 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/durable-router-ledger.d.ts +60 -0
- package/dist/cjs/durable-router-ledger.js +88 -0
- package/dist/cjs/execute.d.ts +45 -0
- package/dist/cjs/execute.js +359 -0
- package/dist/cjs/forward.d.ts +50 -0
- package/dist/cjs/forward.js +56 -0
- package/dist/cjs/graph.d.ts +40 -0
- package/dist/cjs/graph.js +141 -0
- package/dist/cjs/index.d.ts +10 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pathfind.d.ts +24 -0
- package/dist/cjs/pathfind.js +151 -0
- package/dist/cjs/rates.d.ts +9 -0
- package/dist/cjs/rates.js +27 -0
- package/dist/cjs/request.d.ts +19 -0
- package/dist/cjs/request.js +38 -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 +207 -0
- package/dist/cjs/types.js +10 -0
- package/dist/durable-router-ledger.js +6 -9
- package/dist/execute.js +72 -24
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +53 -0
- package/dist/graph.d.ts +8 -0
- package/dist/graph.js +46 -15
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -26
- package/dist/pathfind.d.ts +11 -12
- package/dist/pathfind.js +88 -196
- package/dist/rates.d.ts +9 -0
- package/dist/rates.js +22 -0
- package/dist/request.js +5 -9
- 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/dist/types.js +1 -2
- package/package.json +17 -10
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable settled-segment ledger (RFC-007 G9).
|
|
3
|
+
*
|
|
4
|
+
* Payment execution is multi-channel: a route spans several HTLC hops, each
|
|
5
|
+
* fulfilled in reverse order by revealing the preimage. If the host dies
|
|
6
|
+
* mid-route (after some hops settled, before others), the already-settled
|
|
7
|
+
* segments — channel + HTLC + revealed preimage + settled-at — must survive a
|
|
8
|
+
* restart so the node can (a) never re-lock or re-settle an already-committed
|
|
9
|
+
* segment, and (b) reconcile still-pending locks. This ledger records exactly
|
|
10
|
+
* those settled segments, keyed `channelId:htlcId`, idempotently.
|
|
11
|
+
*
|
|
12
|
+
* Backed by the shared revision-CAS snapshot store: corruption is surfaced
|
|
13
|
+
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
14
|
+
* settlement is never lost.
|
|
15
|
+
*/
|
|
16
|
+
import type { StorageAdapterWithCapabilities, CasStore, WriteAckMode } from '@totemsdk/storage/types';
|
|
17
|
+
/** A payment segment that has been irrevocably settled by preimage reveal. */
|
|
18
|
+
export interface SettledSegment {
|
|
19
|
+
channelId: string;
|
|
20
|
+
htlcId: string;
|
|
21
|
+
/** Preimage revealed during settlement — must survive a mid-route restart. */
|
|
22
|
+
preimage: string;
|
|
23
|
+
/** Monotonic settlement timestamp. */
|
|
24
|
+
settledAt: number;
|
|
25
|
+
/** Optional hop-level detail for reconciliation (amount, counterpart, digest). */
|
|
26
|
+
tokenId?: string;
|
|
27
|
+
senderPublicKeyDigest?: string;
|
|
28
|
+
recipientPublicKeyDigest?: string;
|
|
29
|
+
/** Set once a segment is fully reconciled against the node's route state. */
|
|
30
|
+
reconciled?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface RouterLedgerState {
|
|
33
|
+
/** `channelId:htlcId` → settled segment. */
|
|
34
|
+
segments: Record<string, SettledSegment>;
|
|
35
|
+
}
|
|
36
|
+
export interface DurableRouterLedgerOptions {
|
|
37
|
+
/** Key namespace prefix; default `totem_omnia_router:v1:`. */
|
|
38
|
+
readonly namespace?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Required write acknowledgment; default `durably-acknowledged`. Pass
|
|
41
|
+
* `volatile` only for tests/scratch adapters (e.g. `MemoryStore`).
|
|
42
|
+
*/
|
|
43
|
+
readonly requireAckMode?: WriteAckMode;
|
|
44
|
+
}
|
|
45
|
+
export interface DurableRouterLedger {
|
|
46
|
+
/** Idempotently record a settled segment. Re-recording the same segment is a no-op. */
|
|
47
|
+
recordSettled(segment: SettledSegment): Promise<void>;
|
|
48
|
+
/** True when the given channel+HTLC already settled. */
|
|
49
|
+
isSettled(channelId: string, htlcId: string): Promise<boolean>;
|
|
50
|
+
/** Retrieve a previously settled segment. */
|
|
51
|
+
getSettled(channelId: string, htlcId: string): Promise<SettledSegment | undefined>;
|
|
52
|
+
/** All settled segments, optionally filtered by channel. */
|
|
53
|
+
listSettled(channelId?: string): Promise<SettledSegment[]>;
|
|
54
|
+
/** Mark a settled segment as reconciled with the route state. */
|
|
55
|
+
markReconciled(channelId: string, htlcId: string): Promise<void>;
|
|
56
|
+
getRevision(): Promise<number>;
|
|
57
|
+
hasState(): Promise<boolean>;
|
|
58
|
+
getSnapshot(): Promise<RouterLedgerState>;
|
|
59
|
+
}
|
|
60
|
+
export declare function createDurableRouterLedger(adapter: StorageAdapterWithCapabilities & CasStore, options?: DurableRouterLedgerOptions): DurableRouterLedger;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Durable settled-segment ledger (RFC-007 G9).
|
|
4
|
+
*
|
|
5
|
+
* Payment execution is multi-channel: a route spans several HTLC hops, each
|
|
6
|
+
* fulfilled in reverse order by revealing the preimage. If the host dies
|
|
7
|
+
* mid-route (after some hops settled, before others), the already-settled
|
|
8
|
+
* segments — channel + HTLC + revealed preimage + settled-at — must survive a
|
|
9
|
+
* restart so the node can (a) never re-lock or re-settle an already-committed
|
|
10
|
+
* segment, and (b) reconcile still-pending locks. This ledger records exactly
|
|
11
|
+
* those settled segments, keyed `channelId:htlcId`, idempotently.
|
|
12
|
+
*
|
|
13
|
+
* Backed by the shared revision-CAS snapshot store: corruption is surfaced
|
|
14
|
+
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
15
|
+
* settlement is never lost.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.createDurableRouterLedger = createDurableRouterLedger;
|
|
19
|
+
const snapshot_1 = require("@totemsdk/storage/snapshot");
|
|
20
|
+
const errors_1 = require("@totemsdk/storage/errors");
|
|
21
|
+
const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
|
|
22
|
+
function segmentKey(channelId, htlcId) {
|
|
23
|
+
return `${channelId}:${htlcId}`;
|
|
24
|
+
}
|
|
25
|
+
function assertLedgerState(state) {
|
|
26
|
+
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
27
|
+
throw new errors_1.StorageError('omnia-router ledger state is not an object', 'corrupt');
|
|
28
|
+
}
|
|
29
|
+
const value = state.segments;
|
|
30
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
31
|
+
throw new errors_1.StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function createDurableRouterLedger(adapter, options = {}) {
|
|
35
|
+
const snapshots = (0, snapshot_1.createRevisionedSnapshotStore)(adapter, {
|
|
36
|
+
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
37
|
+
requireAckMode: options.requireAckMode,
|
|
38
|
+
empty: () => ({ segments: {} }),
|
|
39
|
+
validate: assertLedgerState,
|
|
40
|
+
});
|
|
41
|
+
async function mutate(fn) {
|
|
42
|
+
await snapshots.mutate(fn);
|
|
43
|
+
}
|
|
44
|
+
async function loadSegment(channelId, htlcId) {
|
|
45
|
+
const state = await snapshots.load();
|
|
46
|
+
return state.segments[segmentKey(channelId, htlcId)];
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
async recordSettled(segment) {
|
|
50
|
+
// Short-circuit already-recorded segments: re-recording is a no-op and
|
|
51
|
+
// must not advance the revision or rewrite an immutable record.
|
|
52
|
+
if (await loadSegment(segment.channelId, segment.htlcId))
|
|
53
|
+
return;
|
|
54
|
+
await mutate((state) => {
|
|
55
|
+
const key = segmentKey(segment.channelId, segment.htlcId);
|
|
56
|
+
return { ...state, segments: { ...state.segments, [key]: segment } };
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
isSettled(channelId, htlcId) {
|
|
60
|
+
return loadSegment(channelId, htlcId).then((seg) => seg !== undefined);
|
|
61
|
+
},
|
|
62
|
+
getSettled: loadSegment,
|
|
63
|
+
async listSettled(channelId) {
|
|
64
|
+
const state = await snapshots.load();
|
|
65
|
+
const all = Object.values(state.segments);
|
|
66
|
+
if (channelId === undefined)
|
|
67
|
+
return all;
|
|
68
|
+
return all.filter((s) => s.channelId === channelId);
|
|
69
|
+
},
|
|
70
|
+
async markReconciled(channelId, htlcId) {
|
|
71
|
+
await mutate((state) => {
|
|
72
|
+
const key = segmentKey(channelId, htlcId);
|
|
73
|
+
const existing = state.segments[key];
|
|
74
|
+
if (!existing)
|
|
75
|
+
return state;
|
|
76
|
+
return {
|
|
77
|
+
...state,
|
|
78
|
+
segments: { ...state.segments, [key]: { ...existing, reconciled: true } },
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
getRevision: () => snapshots.getRevision(),
|
|
83
|
+
hasState: () => snapshots.hasState(),
|
|
84
|
+
async getSnapshot() {
|
|
85
|
+
return snapshots.load();
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, LeaseProvider, ChannelHTLC, RouterFeeProof } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Execute a single-token multi-hop payment atomically:
|
|
4
|
+
*
|
|
5
|
+
* 1. Forward phase — lock HTLCs across each hop in route.hops.
|
|
6
|
+
* 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
|
|
7
|
+
*
|
|
8
|
+
* Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
|
|
9
|
+
* failure, including failures that occur during the reveal phase — so stranded
|
|
10
|
+
* HTLCs are never left behind silently.
|
|
11
|
+
*
|
|
12
|
+
* `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
|
|
13
|
+
*
|
|
14
|
+
* The `channels` map is updated in-place after each HTLC operation.
|
|
15
|
+
*/
|
|
16
|
+
export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
|
|
17
|
+
export declare const ROUTER_FEE_PROOF_DOMAIN = "totemsdk/omnia-router/fee-proof/v1";
|
|
18
|
+
/**
|
|
19
|
+
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
20
|
+
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
21
|
+
* real fulfilled payment, never a declared string.
|
|
22
|
+
*/
|
|
23
|
+
export declare function buildRouterFeeProof(channel: RouterChannel, htlc: ChannelHTLC, settledAt?: number): RouterFeeProof;
|
|
24
|
+
export declare function computeRouterFeeProofHash(proof: RouterFeeProof): string;
|
|
25
|
+
/**
|
|
26
|
+
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
27
|
+
* Call this explicitly to roll back before or without attempting execution.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cancelPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, leaseProviders: Map<string, LeaseProvider>): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Execute a cross-token payment atomically.
|
|
32
|
+
*
|
|
33
|
+
* For each SwapHop:
|
|
34
|
+
* 1. Lock the inbound HTLC (tokenIn side).
|
|
35
|
+
* 2. Lock the outbound HTLC (tokenOut side).
|
|
36
|
+
* Both use the same hashlock — the intermediary can only claim by revealing
|
|
37
|
+
* the preimage on both sides simultaneously.
|
|
38
|
+
*
|
|
39
|
+
* Then forward-locks all remaining non-swap hops, and reveals the preimage
|
|
40
|
+
* backwards across all locked channels.
|
|
41
|
+
*
|
|
42
|
+
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
43
|
+
* all still-pending locked HTLCs.
|
|
44
|
+
*/
|
|
45
|
+
export declare function executeCrossTokenPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: CrossTokenRoute, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
|