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