@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
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UnsupportedRoutingModeError = exports.FIXED_AMOUNT_COST_MODEL = exports.DEFAULT_MAX_HOPS = void 0;
|
|
4
|
+
exports.createRoutingGraphSnapshot = createRoutingGraphSnapshot;
|
|
5
|
+
exports.selectRoutingEngine = selectRoutingEngine;
|
|
6
|
+
exports.routeCacheKey = routeCacheKey;
|
|
7
|
+
const bounded_search_js_1 = require("./bounded-search.js");
|
|
8
|
+
const graph_js_1 = require("./graph.js");
|
|
9
|
+
exports.DEFAULT_MAX_HOPS = 8;
|
|
10
|
+
function createRoutingGraphSnapshot(graph) {
|
|
11
|
+
return { graph, revision: (0, graph_js_1.getGraphRevisions)(graph) };
|
|
12
|
+
}
|
|
13
|
+
exports.FIXED_AMOUNT_COST_MODEL = {
|
|
14
|
+
id: 'fixed-amount-v1',
|
|
15
|
+
nonNegative: true,
|
|
16
|
+
additive: true,
|
|
17
|
+
amountDependent: false,
|
|
18
|
+
edgeFee: bounded_search_js_1.defaultEdgeFee,
|
|
19
|
+
compare(a, b) {
|
|
20
|
+
if (a.fees < b.fees)
|
|
21
|
+
return -1;
|
|
22
|
+
if (a.fees > b.fees)
|
|
23
|
+
return 1;
|
|
24
|
+
return a.hops - b.hops;
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
class UnsupportedRoutingModeError extends Error {
|
|
28
|
+
constructor(mode) {
|
|
29
|
+
super(`Routing mode unsupported: ${mode}`);
|
|
30
|
+
this.mode = mode;
|
|
31
|
+
this.name = 'UnsupportedRoutingModeError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
exports.UnsupportedRoutingModeError = UnsupportedRoutingModeError;
|
|
35
|
+
function resolveMaxHops(query) {
|
|
36
|
+
if (query.maxHops === undefined)
|
|
37
|
+
return exports.DEFAULT_MAX_HOPS;
|
|
38
|
+
if (query.maxHops === null)
|
|
39
|
+
throw new UnsupportedRoutingModeError('unbounded');
|
|
40
|
+
if (!Number.isInteger(query.maxHops) || query.maxHops < 0) {
|
|
41
|
+
throw new Error(`maxHops must be a non-negative integer (got ${String(query.maxHops)})`);
|
|
42
|
+
}
|
|
43
|
+
return query.maxHops;
|
|
44
|
+
}
|
|
45
|
+
class LayeredRoutingEngine {
|
|
46
|
+
constructor() {
|
|
47
|
+
this.id = 'layered-bounded-v1';
|
|
48
|
+
this.capabilities = {
|
|
49
|
+
bounded: true,
|
|
50
|
+
unbounded: false,
|
|
51
|
+
oneToMany: true,
|
|
52
|
+
incremental: false,
|
|
53
|
+
crossToken: true,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
findRoute(snapshot, query, costModel = exports.FIXED_AMOUNT_COST_MODEL) {
|
|
57
|
+
const maxHops = resolveMaxHops(query);
|
|
58
|
+
if (query.amount <= 0n || !query.destination)
|
|
59
|
+
return null;
|
|
60
|
+
if ((0, bounded_search_js_1.isZeroFeeToken)(snapshot.graph, query.tokenId, query.amount, costModel.edgeFee)) {
|
|
61
|
+
return (0, bounded_search_js_1.bfsRoute)(snapshot.graph, query.source, query.destination, query.amount, query.tokenId, maxHops);
|
|
62
|
+
}
|
|
63
|
+
const layers = (0, bounded_search_js_1.computeLayers)(snapshot.graph, query.source, query.amount, query.tokenId, maxHops, costModel.edgeFee);
|
|
64
|
+
return (0, bounded_search_js_1.routeFromLayers)(layers, query.destination, query.amount, query.tokenId, maxHops);
|
|
65
|
+
}
|
|
66
|
+
computeTree(snapshot, query, costModel = exports.FIXED_AMOUNT_COST_MODEL) {
|
|
67
|
+
const maxHops = resolveMaxHops(query);
|
|
68
|
+
let layers;
|
|
69
|
+
if (query.amount <= 0n) {
|
|
70
|
+
layers = Array.from({ length: maxHops + 1 }, () => new Map());
|
|
71
|
+
}
|
|
72
|
+
else if ((0, bounded_search_js_1.isZeroFeeToken)(snapshot.graph, query.tokenId, query.amount, costModel.edgeFee)) {
|
|
73
|
+
// Zero-fee trees carry shortest-hop labels only (longer zero-fee paths are never better).
|
|
74
|
+
layers = (0, bounded_search_js_1.bfsLayers)(snapshot.graph, query.source, query.amount, query.tokenId, maxHops);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
layers = (0, bounded_search_js_1.computeLayers)(snapshot.graph, query.source, query.amount, query.tokenId, maxHops, costModel.edgeFee);
|
|
78
|
+
}
|
|
79
|
+
return createRoutingTree(snapshot, query, costModel, maxHops, layers);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function createRoutingTree(snapshot, query, costModel, maxHops, layers) {
|
|
83
|
+
const destinations = new Set();
|
|
84
|
+
for (const layer of layers) {
|
|
85
|
+
for (const node of layer.keys())
|
|
86
|
+
destinations.add(node);
|
|
87
|
+
}
|
|
88
|
+
const labelAt = (destination, hops) => {
|
|
89
|
+
if (!Number.isInteger(hops) || hops < 0 || hops > maxHops)
|
|
90
|
+
return null;
|
|
91
|
+
const label = layers[hops]?.get(destination);
|
|
92
|
+
if (!label)
|
|
93
|
+
return null;
|
|
94
|
+
const routeHops = (0, bounded_search_js_1.reconstructFromLayers)(layers, hops, destination, query.amount, query.tokenId);
|
|
95
|
+
return {
|
|
96
|
+
hops,
|
|
97
|
+
totalFees: label.totalFees,
|
|
98
|
+
route: {
|
|
99
|
+
hops: routeHops,
|
|
100
|
+
totalFees: label.totalFees,
|
|
101
|
+
tokenIn: query.tokenId,
|
|
102
|
+
tokenOut: query.tokenId,
|
|
103
|
+
estimatedBlocks: routeHops.length * 2,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
source: query.source,
|
|
109
|
+
amount: query.amount,
|
|
110
|
+
tokenId: query.tokenId,
|
|
111
|
+
maxHops,
|
|
112
|
+
revision: snapshot.revision,
|
|
113
|
+
costModelId: costModel.id,
|
|
114
|
+
destinations: [...destinations].sort(),
|
|
115
|
+
labelAt,
|
|
116
|
+
routeTo(destination) {
|
|
117
|
+
let bestH = -1;
|
|
118
|
+
let bestFees = 0n;
|
|
119
|
+
for (let h = 0; h <= maxHops; h++) {
|
|
120
|
+
const label = layers[h]?.get(destination);
|
|
121
|
+
if (!label)
|
|
122
|
+
continue;
|
|
123
|
+
if (bestH === -1 ||
|
|
124
|
+
label.totalFees < bestFees ||
|
|
125
|
+
(label.totalFees === bestFees && h < bestH)) {
|
|
126
|
+
bestH = h;
|
|
127
|
+
bestFees = label.totalFees;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (bestH === -1)
|
|
131
|
+
return null;
|
|
132
|
+
return labelAt(destination, bestH)?.route ?? null;
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const LAYERED_ENGINE = new LayeredRoutingEngine();
|
|
137
|
+
function selectRoutingEngine(_snapshot) {
|
|
138
|
+
return LAYERED_ENGINE;
|
|
139
|
+
}
|
|
140
|
+
/** Cache key includes every input that materially affects correctness. */
|
|
141
|
+
function routeCacheKey(snapshot, query, costModel = exports.FIXED_AMOUNT_COST_MODEL) {
|
|
142
|
+
return [
|
|
143
|
+
snapshot.revision.topology,
|
|
144
|
+
snapshot.revision.economics,
|
|
145
|
+
snapshot.revision.live,
|
|
146
|
+
query.source,
|
|
147
|
+
query.destination ?? '*',
|
|
148
|
+
query.amount.toString(),
|
|
149
|
+
query.tokenId,
|
|
150
|
+
query.targetToken ?? '',
|
|
151
|
+
query.maxHops === null ? 'unbounded' : String(query.maxHops ?? 'default'),
|
|
152
|
+
costModel.id,
|
|
153
|
+
].join('|');
|
|
154
|
+
}
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -123,6 +123,8 @@ export interface RoutingHop {
|
|
|
123
123
|
to: string;
|
|
124
124
|
amount: bigint;
|
|
125
125
|
tokenId: string;
|
|
126
|
+
/** Edge fee rate (per SCALE); populated by the routing engine. */
|
|
127
|
+
feeRate?: bigint;
|
|
126
128
|
/** Populated during payment execution */
|
|
127
129
|
htlcId?: string;
|
|
128
130
|
}
|
|
@@ -189,12 +191,17 @@ export interface PaymentResult {
|
|
|
189
191
|
/** Hex preimage revealed during settlement (present on success) */
|
|
190
192
|
preimage?: string;
|
|
191
193
|
error?: string;
|
|
194
|
+
/** Machine-readable failure code (e.g. ROUTE_REVALIDATION_FAILED). */
|
|
195
|
+
errorCode?: string;
|
|
192
196
|
/** htlcIds that were successfully settled */
|
|
193
197
|
settledHops: string[];
|
|
194
198
|
/** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
|
|
195
199
|
feeProofs?: RouterFeeProof[];
|
|
196
200
|
}
|
|
197
201
|
export interface RouteOptions {
|
|
198
|
-
/**
|
|
202
|
+
/**
|
|
203
|
+
* Maximum number of hops for the whole route (default: 8). For cross-token
|
|
204
|
+
* routes this is a global end-to-end budget.
|
|
205
|
+
*/
|
|
199
206
|
maxHops?: number;
|
|
200
207
|
}
|
package/dist/execute.js
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { bytesToHex, sha3_256 } from '@totemsdk/core';
|
|
2
|
+
import { validateChannelSpend, validateRoute, validateRoutingHop, swapIntermediary } from './route-validation.js';
|
|
3
|
+
import { SCALE } from './rates.js';
|
|
2
4
|
// ─── Type guard ───────────────────────────────────────────────────────────────
|
|
3
5
|
function isSwapHop(hop) {
|
|
4
6
|
return hop.isSwap === true;
|
|
5
7
|
}
|
|
8
|
+
function revalidationErrorCode(message) {
|
|
9
|
+
return message.includes('ROUTE_REVALIDATION_FAILED') ? 'ROUTE_REVALIDATION_FAILED' : undefined;
|
|
10
|
+
}
|
|
6
11
|
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
7
12
|
/** Determine the counterparty public key digest relative to the local signer. */
|
|
8
13
|
function counterpartPkd(channel) {
|
|
@@ -51,6 +56,25 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
|
|
|
51
56
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
52
57
|
}
|
|
53
58
|
const plainHops = route.hops.filter(h => !isSwapHop(h));
|
|
59
|
+
// Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
|
|
60
|
+
// downstream intermediaries; the fee for the final edge belongs to the
|
|
61
|
+
// recipient and is not charged. Intermediary i retains
|
|
62
|
+
// hopAmount[i] - hopAmount[i+1]. With no fee rates this is the legacy
|
|
63
|
+
// same-amount behaviour.
|
|
64
|
+
const fees = plainHops.map((hop) => hop.feeRate && hop.feeRate > 0n ? (paymentRequest.amount * hop.feeRate) / SCALE : 0n);
|
|
65
|
+
for (let i = 0; i < plainHops.length; i++) {
|
|
66
|
+
const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
|
|
67
|
+
plainHops[i].amount = paymentRequest.amount + downstream;
|
|
68
|
+
}
|
|
69
|
+
const routeValidation = validateRoute(channels, route);
|
|
70
|
+
if (!routeValidation.ok) {
|
|
71
|
+
return {
|
|
72
|
+
success: false,
|
|
73
|
+
error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
|
|
74
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
75
|
+
settledHops: [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
54
78
|
const locked = [];
|
|
55
79
|
// ── Forward: lock HTLCs ───────────────────────────────────────────────────
|
|
56
80
|
for (let i = 0; i < plainHops.length; i++) {
|
|
@@ -65,6 +89,16 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
|
|
|
65
89
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
66
90
|
return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
|
|
67
91
|
}
|
|
92
|
+
const hopValidation = validateRoutingHop(channels, hop);
|
|
93
|
+
if (!hopValidation.ok) {
|
|
94
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
95
|
+
return {
|
|
96
|
+
success: false,
|
|
97
|
+
error: `ROUTE_REVALIDATION_FAILED: ${hopValidation.error}`,
|
|
98
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
99
|
+
settledHops: [],
|
|
100
|
+
};
|
|
101
|
+
}
|
|
68
102
|
// Timeouts decrease toward the recipient so each hop has time to claim.
|
|
69
103
|
const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
|
|
70
104
|
let addResult;
|
|
@@ -192,18 +226,30 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
|
|
|
192
226
|
if (!preimage) {
|
|
193
227
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
194
228
|
}
|
|
229
|
+
const routeValidation = validateRoute(channels, route);
|
|
230
|
+
if (!routeValidation.ok) {
|
|
231
|
+
return {
|
|
232
|
+
success: false,
|
|
233
|
+
error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
|
|
234
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
235
|
+
settledHops: [],
|
|
236
|
+
};
|
|
237
|
+
}
|
|
195
238
|
const locked = [];
|
|
196
239
|
/**
|
|
197
240
|
* Lock a single HTLC, add it to `locked`, and return the htlcId.
|
|
198
241
|
* Throws on any error so callers can handle rollback uniformly.
|
|
199
242
|
*/
|
|
200
|
-
async function lockHTLC(channelId, amount, hashlock, timeoutBlock) {
|
|
243
|
+
async function lockHTLC(channelId, amount, hashlock, timeoutBlock, tokenId, sender) {
|
|
201
244
|
const channel = channels.get(channelId);
|
|
202
245
|
const lp = leaseProviders.get(channelId);
|
|
203
246
|
if (!channel)
|
|
204
247
|
throw new Error(`Channel ${channelId} not found`);
|
|
205
248
|
if (!lp)
|
|
206
249
|
throw new Error(`No lease provider for channel ${channelId}`);
|
|
250
|
+
const spend = validateChannelSpend(channel, sender, amount, tokenId);
|
|
251
|
+
if (!spend.ok)
|
|
252
|
+
throw new Error(`ROUTE_REVALIDATION_FAILED: ${spend.error}`);
|
|
207
253
|
// Let addHTLC exceptions propagate — they carry the original error message.
|
|
208
254
|
const result = await ops.addHTLC(channel, {
|
|
209
255
|
amount,
|
|
@@ -240,30 +286,40 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
|
|
|
240
286
|
// Inbound channel (sender → intermediary, tokenIn side)
|
|
241
287
|
const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
242
288
|
try {
|
|
243
|
-
hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout);
|
|
289
|
+
hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
|
|
244
290
|
}
|
|
245
291
|
catch (err) {
|
|
246
292
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
247
|
-
return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
293
|
+
return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
248
294
|
}
|
|
249
295
|
// Outbound channel (intermediary → recipient, tokenOut side)
|
|
250
296
|
const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
297
|
+
const intermediary = swapIntermediary(channels, hop);
|
|
298
|
+
if (!intermediary) {
|
|
299
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
300
|
+
return {
|
|
301
|
+
success: false,
|
|
302
|
+
error: `ROUTE_REVALIDATION_FAILED: no intermediary for ${hop.inboundChannelId}`,
|
|
303
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
304
|
+
settledHops: [],
|
|
305
|
+
};
|
|
306
|
+
}
|
|
251
307
|
try {
|
|
252
|
-
await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout);
|
|
308
|
+
await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout, hop.tokenOut, intermediary);
|
|
253
309
|
}
|
|
254
310
|
catch (err) {
|
|
255
311
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
256
|
-
return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
312
|
+
return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
257
313
|
}
|
|
258
314
|
}
|
|
259
315
|
else {
|
|
260
316
|
const timeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
261
317
|
try {
|
|
262
|
-
hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout);
|
|
318
|
+
hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
|
|
263
319
|
}
|
|
264
320
|
catch (err) {
|
|
265
321
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
266
|
-
return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
322
|
+
return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
267
323
|
}
|
|
268
324
|
}
|
|
269
325
|
}
|
package/dist/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/graph.js
CHANGED
|
@@ -1,11 +1,34 @@
|
|
|
1
|
-
import { parseRateToScaled } from './
|
|
1
|
+
import { parseRateToScaled } from './rates.js';
|
|
2
|
+
const graphRevisions = new WeakMap();
|
|
3
|
+
function ensureRevisions(graph) {
|
|
4
|
+
let revisions = graphRevisions.get(graph);
|
|
5
|
+
if (!revisions) {
|
|
6
|
+
revisions = { topology: 0, economics: 0, live: 0 };
|
|
7
|
+
graphRevisions.set(graph, revisions);
|
|
8
|
+
}
|
|
9
|
+
return revisions;
|
|
10
|
+
}
|
|
11
|
+
/** Snapshot-consistent revision marker for routing caches and trees. */
|
|
12
|
+
export function getGraphRevisions(graph) {
|
|
13
|
+
return { ...ensureRevisions(graph) };
|
|
14
|
+
}
|
|
15
|
+
function bumpTopology(graph) {
|
|
16
|
+
const revisions = ensureRevisions(graph);
|
|
17
|
+
revisions.topology += 1;
|
|
18
|
+
revisions.live += 1;
|
|
19
|
+
}
|
|
20
|
+
function bumpEconomics(graph) {
|
|
21
|
+
ensureRevisions(graph).economics += 1;
|
|
22
|
+
}
|
|
2
23
|
/** Create an empty ChannelGraph. */
|
|
3
24
|
export function createChannelGraph() {
|
|
4
|
-
|
|
25
|
+
const graph = {
|
|
5
26
|
nodeEdges: new Map(),
|
|
6
27
|
edgesByChannel: new Map(),
|
|
7
28
|
swapIndex: new Map(),
|
|
8
29
|
};
|
|
30
|
+
graphRevisions.set(graph, { topology: 0, economics: 0, live: 0 });
|
|
31
|
+
return graph;
|
|
9
32
|
}
|
|
10
33
|
/**
|
|
11
34
|
* Add a directed channel edge to the graph.
|
|
@@ -17,6 +40,18 @@ export function createChannelGraph() {
|
|
|
17
40
|
* entry (balance update semantics).
|
|
18
41
|
*/
|
|
19
42
|
export function addChannel(graph, edge) {
|
|
43
|
+
if (!edge.channelId || !edge.from || !edge.to || !edge.tokenId) {
|
|
44
|
+
throw new Error('addChannel requires non-empty channelId, from, to and tokenId');
|
|
45
|
+
}
|
|
46
|
+
if (edge.feeRate < 0n) {
|
|
47
|
+
throw new Error(`Invalid feeRate ${edge.feeRate.toString()} for channel ${edge.channelId}: must be non-negative`);
|
|
48
|
+
}
|
|
49
|
+
if (edge.availableBalance < 0n) {
|
|
50
|
+
throw new Error(`Invalid availableBalance ${edge.availableBalance.toString()} for channel ${edge.channelId}: must be non-negative`);
|
|
51
|
+
}
|
|
52
|
+
if (edge.htlcCapacity < 0n) {
|
|
53
|
+
throw new Error(`Invalid htlcCapacity ${edge.htlcCapacity.toString()} for channel ${edge.channelId}: must be non-negative`);
|
|
54
|
+
}
|
|
20
55
|
const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
|
|
21
56
|
// Replace any edge for the same (channelId, from) direction.
|
|
22
57
|
const idx = existing.findIndex(e => e.from === edge.from);
|
|
@@ -32,6 +67,7 @@ export function addChannel(graph, edge) {
|
|
|
32
67
|
const nodeList = graph.nodeEdges.get(edge.from) ?? [];
|
|
33
68
|
nodeList.push(edge);
|
|
34
69
|
graph.nodeEdges.set(edge.from, nodeList);
|
|
70
|
+
bumpTopology(graph);
|
|
35
71
|
}
|
|
36
72
|
/**
|
|
37
73
|
* Remove ALL directed edges for `channelId` (i.e. both directions).
|
|
@@ -45,6 +81,7 @@ export function removeChannel(graph, channelId) {
|
|
|
45
81
|
_removeFromNodeEdges(graph, edge);
|
|
46
82
|
}
|
|
47
83
|
graph.edgesByChannel.delete(channelId);
|
|
84
|
+
bumpTopology(graph);
|
|
48
85
|
}
|
|
49
86
|
function _removeFromNodeEdges(graph, edge) {
|
|
50
87
|
const nodeList = graph.nodeEdges.get(edge.from);
|
|
@@ -83,6 +120,7 @@ export function announceSwap(graph, announcement) {
|
|
|
83
120
|
list.push(announcement);
|
|
84
121
|
}
|
|
85
122
|
graph.swapIndex.set(key, list);
|
|
123
|
+
bumpEconomics(graph);
|
|
86
124
|
}
|
|
87
125
|
/**
|
|
88
126
|
* Return all swap announcements for a given token pair, or an empty array.
|
package/dist/pathfind.d.ts
CHANGED
|
@@ -1,25 +1,24 @@
|
|
|
1
1
|
import type { ChannelGraph, Route, CrossTokenRoute, RouteOptions } from './types.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
|
|
5
|
-
*/
|
|
6
|
-
export declare function parseRateToScaled(rate: string): bigint;
|
|
7
|
-
/** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
|
|
8
|
-
export declare function applyRate(amountIn: bigint, rate: string): bigint;
|
|
2
|
+
import { applyRate, parseRateToScaled } from './rates.js';
|
|
3
|
+
export { parseRateToScaled, applyRate };
|
|
9
4
|
/**
|
|
10
5
|
* Find the cheapest route (lowest total fee, then fewest hops) from `from` to
|
|
11
|
-
* `to` carrying `amount` of `tokenId`.
|
|
12
|
-
* availableBalance.
|
|
6
|
+
* `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
|
|
7
|
+
* availableBalance. Returns null if no path exists within maxHops.
|
|
13
8
|
*
|
|
14
|
-
*
|
|
9
|
+
* Delegates to the routing engine (zero-fee BFS / layered bounded search).
|
|
15
10
|
*/
|
|
16
11
|
export declare function findRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, opts?: RouteOptions): Route | null;
|
|
17
12
|
/**
|
|
18
13
|
* Find a cross-token route where the sender spends `tokenIn` and the
|
|
19
|
-
* recipient receives `tokenOut`.
|
|
14
|
+
* recipient receives `tokenOut`. The path may include one or more swap hops
|
|
20
15
|
* provided by bridging intermediaries registered via announceSwap.
|
|
21
16
|
*
|
|
22
17
|
* Selection criteria: lowest total fee (including swap fee), then fewest hops,
|
|
23
|
-
* then fewest swap hops.
|
|
18
|
+
* then fewest swap hops, then a deterministic route key.
|
|
19
|
+
*
|
|
20
|
+
* `maxHops` is a **global** end-to-end budget: preHops + 1 (swap) + postHops
|
|
21
|
+
* must not exceed it (RFC-055 §2.5). The inbound leg is computed once for all
|
|
22
|
+
* announcements; the outbound leg is cached per `(postDst, amountOut, tokenOut)`.
|
|
24
23
|
*/
|
|
25
24
|
export declare function findCrossTokenRoute(graph: ChannelGraph, from: string, to: string, amountIn: bigint, tokenIn: string, tokenOut: string, opts?: RouteOptions): CrossTokenRoute | null;
|