@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,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createDurableRouterLedger = exports.createCleartextRoutingCodec = exports.ROUTER_FEE_PROOF_DOMAIN = exports.computeRouterFeeProofHash = exports.buildRouterFeeProof = exports.cancelPayment = exports.executeCrossTokenPayment = exports.executeMultiHopPayment = exports.buildCrossTokenRequest = exports.buildPaymentRequest = exports.parseRateToScaled = exports.applyRate = exports.findCrossTokenRoute = exports.findRoute = exports.getSwapAnnouncements = exports.announceSwap = exports.removeChannel = exports.addChannel = exports.createChannelGraph = void 0;
|
|
4
|
+
var graph_js_1 = require("./graph.js");
|
|
5
|
+
Object.defineProperty(exports, "createChannelGraph", { enumerable: true, get: function () { return graph_js_1.createChannelGraph; } });
|
|
6
|
+
Object.defineProperty(exports, "addChannel", { enumerable: true, get: function () { return graph_js_1.addChannel; } });
|
|
7
|
+
Object.defineProperty(exports, "removeChannel", { enumerable: true, get: function () { return graph_js_1.removeChannel; } });
|
|
8
|
+
Object.defineProperty(exports, "announceSwap", { enumerable: true, get: function () { return graph_js_1.announceSwap; } });
|
|
9
|
+
Object.defineProperty(exports, "getSwapAnnouncements", { enumerable: true, get: function () { return graph_js_1.getSwapAnnouncements; } });
|
|
10
|
+
var pathfind_js_1 = require("./pathfind.js");
|
|
11
|
+
Object.defineProperty(exports, "findRoute", { enumerable: true, get: function () { return pathfind_js_1.findRoute; } });
|
|
12
|
+
Object.defineProperty(exports, "findCrossTokenRoute", { enumerable: true, get: function () { return pathfind_js_1.findCrossTokenRoute; } });
|
|
13
|
+
Object.defineProperty(exports, "applyRate", { enumerable: true, get: function () { return pathfind_js_1.applyRate; } });
|
|
14
|
+
Object.defineProperty(exports, "parseRateToScaled", { enumerable: true, get: function () { return pathfind_js_1.parseRateToScaled; } });
|
|
15
|
+
var request_js_1 = require("./request.js");
|
|
16
|
+
Object.defineProperty(exports, "buildPaymentRequest", { enumerable: true, get: function () { return request_js_1.buildPaymentRequest; } });
|
|
17
|
+
Object.defineProperty(exports, "buildCrossTokenRequest", { enumerable: true, get: function () { return request_js_1.buildCrossTokenRequest; } });
|
|
18
|
+
var execute_js_1 = require("./execute.js");
|
|
19
|
+
Object.defineProperty(exports, "executeMultiHopPayment", { enumerable: true, get: function () { return execute_js_1.executeMultiHopPayment; } });
|
|
20
|
+
Object.defineProperty(exports, "executeCrossTokenPayment", { enumerable: true, get: function () { return execute_js_1.executeCrossTokenPayment; } });
|
|
21
|
+
Object.defineProperty(exports, "cancelPayment", { enumerable: true, get: function () { return execute_js_1.cancelPayment; } });
|
|
22
|
+
Object.defineProperty(exports, "buildRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.buildRouterFeeProof; } });
|
|
23
|
+
Object.defineProperty(exports, "computeRouterFeeProofHash", { enumerable: true, get: function () { return execute_js_1.computeRouterFeeProofHash; } });
|
|
24
|
+
Object.defineProperty(exports, "ROUTER_FEE_PROOF_DOMAIN", { enumerable: true, get: function () { return execute_js_1.ROUTER_FEE_PROOF_DOMAIN; } });
|
|
25
|
+
// RFC-035 B4 — pluggable forwarding envelopes (cleartext now; onion behind the same seam).
|
|
26
|
+
var forward_js_1 = require("./forward.js");
|
|
27
|
+
Object.defineProperty(exports, "createCleartextRoutingCodec", { enumerable: true, get: function () { return forward_js_1.createCleartextRoutingCodec; } });
|
|
28
|
+
var durable_router_ledger_js_1 = require("./durable-router-ledger.js");
|
|
29
|
+
Object.defineProperty(exports, "createDurableRouterLedger", { enumerable: true, get: function () { return durable_router_ledger_js_1.createDurableRouterLedger; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ChannelGraph, Route, CrossTokenRoute, RouteOptions } from './types.js';
|
|
2
|
+
import { applyRate, parseRateToScaled } from './rates.js';
|
|
3
|
+
export { parseRateToScaled, applyRate };
|
|
4
|
+
/**
|
|
5
|
+
* Find the cheapest route (lowest total fee, then fewest hops) from `from` to
|
|
6
|
+
* `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
|
|
7
|
+
* availableBalance. Returns null if no path exists within maxHops.
|
|
8
|
+
*
|
|
9
|
+
* Delegates to the routing engine (zero-fee BFS / layered bounded search).
|
|
10
|
+
*/
|
|
11
|
+
export declare function findRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, opts?: RouteOptions): Route | null;
|
|
12
|
+
/**
|
|
13
|
+
* Find a cross-token route where the sender spends `tokenIn` and the
|
|
14
|
+
* recipient receives `tokenOut`. The path may include one or more swap hops
|
|
15
|
+
* provided by bridging intermediaries registered via announceSwap.
|
|
16
|
+
*
|
|
17
|
+
* Selection criteria: lowest total fee (including swap fee), then fewest 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)`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function findCrossTokenRoute(graph: ChannelGraph, from: string, to: string, amountIn: bigint, tokenIn: string, tokenOut: string, opts?: RouteOptions): CrossTokenRoute | null;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.applyRate = exports.parseRateToScaled = void 0;
|
|
4
|
+
exports.findRoute = findRoute;
|
|
5
|
+
exports.findCrossTokenRoute = findCrossTokenRoute;
|
|
6
|
+
const graph_js_1 = require("./graph.js");
|
|
7
|
+
const rates_js_1 = require("./rates.js");
|
|
8
|
+
Object.defineProperty(exports, "applyRate", { enumerable: true, get: function () { return rates_js_1.applyRate; } });
|
|
9
|
+
Object.defineProperty(exports, "parseRateToScaled", { enumerable: true, get: function () { return rates_js_1.parseRateToScaled; } });
|
|
10
|
+
const bounded_search_js_1 = require("./bounded-search.js");
|
|
11
|
+
const routing_engine_js_1 = require("./routing-engine.js");
|
|
12
|
+
// ─── Single-token ─────────────────────────────────────────────────────────────
|
|
13
|
+
/**
|
|
14
|
+
* Find the cheapest route (lowest total fee, then fewest hops) from `from` to
|
|
15
|
+
* `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
|
|
16
|
+
* availableBalance. Returns null if no path exists within maxHops.
|
|
17
|
+
*
|
|
18
|
+
* Delegates to the routing engine (zero-fee BFS / layered bounded search).
|
|
19
|
+
*/
|
|
20
|
+
function findRoute(graph, from, to, amount, tokenId, opts) {
|
|
21
|
+
const snapshot = (0, routing_engine_js_1.createRoutingGraphSnapshot)(graph);
|
|
22
|
+
const engine = (0, routing_engine_js_1.selectRoutingEngine)(snapshot);
|
|
23
|
+
return engine.findRoute(snapshot, {
|
|
24
|
+
source: from,
|
|
25
|
+
destination: to,
|
|
26
|
+
amount,
|
|
27
|
+
tokenId,
|
|
28
|
+
...(opts?.maxHops === undefined ? {} : { maxHops: opts.maxHops }),
|
|
29
|
+
}, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
|
|
30
|
+
}
|
|
31
|
+
// ─── Cross-token ──────────────────────────────────────────────────────────────
|
|
32
|
+
/**
|
|
33
|
+
* Find a cross-token route where the sender spends `tokenIn` and the
|
|
34
|
+
* recipient receives `tokenOut`. The path may include one or more swap hops
|
|
35
|
+
* provided by bridging intermediaries registered via announceSwap.
|
|
36
|
+
*
|
|
37
|
+
* Selection criteria: lowest total fee (including swap fee), then fewest hops,
|
|
38
|
+
* then fewest swap hops, then a deterministic route key.
|
|
39
|
+
*
|
|
40
|
+
* `maxHops` is a **global** end-to-end budget: preHops + 1 (swap) + postHops
|
|
41
|
+
* must not exceed it (RFC-055 §2.5). The inbound leg is computed once for all
|
|
42
|
+
* announcements; the outbound leg is cached per `(postDst, amountOut, tokenOut)`.
|
|
43
|
+
*/
|
|
44
|
+
function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
|
|
45
|
+
const announcements = (0, graph_js_1.getSwapAnnouncements)(graph, tokenIn, tokenOut);
|
|
46
|
+
if (announcements.length === 0)
|
|
47
|
+
return null;
|
|
48
|
+
const maxHops = opts?.maxHops ?? routing_engine_js_1.DEFAULT_MAX_HOPS;
|
|
49
|
+
if (!Number.isInteger(maxHops) || maxHops < 0) {
|
|
50
|
+
throw new Error(`maxHops must be a non-negative integer (got ${String(opts?.maxHops)})`);
|
|
51
|
+
}
|
|
52
|
+
// A swap consumes one hop; pre + swap + post must fit the global budget.
|
|
53
|
+
if (amountIn <= 0n || maxHops < 1)
|
|
54
|
+
return null;
|
|
55
|
+
const snapshot = (0, routing_engine_js_1.createRoutingGraphSnapshot)(graph);
|
|
56
|
+
const engine = (0, routing_engine_js_1.selectRoutingEngine)(snapshot);
|
|
57
|
+
// One bounded inbound tree serves every announcement.
|
|
58
|
+
const preTree = engine.computeTree(snapshot, { source: from, amount: amountIn, tokenId: tokenIn, maxHops: maxHops - 1 }, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
|
|
59
|
+
const postCache = new Map();
|
|
60
|
+
let best = null;
|
|
61
|
+
for (const ann of announcements) {
|
|
62
|
+
if (amountIn > ann.maxAmountIn)
|
|
63
|
+
continue;
|
|
64
|
+
const inboundEdges = graph.edgesByChannel.get(ann.inboundChannelId) ?? [];
|
|
65
|
+
const inboundEdge = inboundEdges.find(e => e.to === ann.intermediaryPubKey && e.tokenId === tokenIn);
|
|
66
|
+
if (!inboundEdge)
|
|
67
|
+
continue;
|
|
68
|
+
if (inboundEdge.availableBalance < amountIn)
|
|
69
|
+
continue;
|
|
70
|
+
const amountOut = (0, rates_js_1.applyRate)(amountIn, ann.rate);
|
|
71
|
+
if (amountOut <= 0n)
|
|
72
|
+
continue;
|
|
73
|
+
const outboundEdges = graph.edgesByChannel.get(ann.outboundChannelId) ?? [];
|
|
74
|
+
const outboundEdge = outboundEdges.find(e => e.from === ann.intermediaryPubKey && e.tokenId === tokenOut);
|
|
75
|
+
if (!outboundEdge)
|
|
76
|
+
continue;
|
|
77
|
+
if (outboundEdge.availableBalance < amountOut)
|
|
78
|
+
continue;
|
|
79
|
+
const preSrc = inboundEdge.from;
|
|
80
|
+
const postDst = outboundEdge.to;
|
|
81
|
+
const postKey = `${postDst}|${amountOut.toString()}|${tokenOut}|${maxHops - 1}`;
|
|
82
|
+
let postTree = postCache.get(postKey);
|
|
83
|
+
if (!postTree) {
|
|
84
|
+
postTree = engine.computeTree(snapshot, { source: postDst, amount: amountOut, tokenId: tokenOut, maxHops: maxHops - 1 }, routing_engine_js_1.FIXED_AMOUNT_COST_MODEL);
|
|
85
|
+
postCache.set(postKey, postTree);
|
|
86
|
+
}
|
|
87
|
+
const inboundFee = (0, bounded_search_js_1.defaultEdgeFee)(amountIn, inboundEdge);
|
|
88
|
+
const outboundFee = (0, bounded_search_js_1.defaultEdgeFee)(amountOut, outboundEdge);
|
|
89
|
+
const swapHop = {
|
|
90
|
+
isSwap: true,
|
|
91
|
+
channelId: ann.inboundChannelId,
|
|
92
|
+
from: preSrc,
|
|
93
|
+
to: postDst,
|
|
94
|
+
amount: amountIn,
|
|
95
|
+
tokenId: tokenIn,
|
|
96
|
+
tokenIn,
|
|
97
|
+
tokenOut,
|
|
98
|
+
amountIn,
|
|
99
|
+
amountOut,
|
|
100
|
+
rate: ann.rate,
|
|
101
|
+
inboundChannelId: ann.inboundChannelId,
|
|
102
|
+
outboundChannelId: ann.outboundChannelId,
|
|
103
|
+
};
|
|
104
|
+
for (let preH = 0; preH <= maxHops - 1; preH++) {
|
|
105
|
+
const preLabel = preTree.labelAt(preSrc, preH);
|
|
106
|
+
if (!preLabel)
|
|
107
|
+
continue;
|
|
108
|
+
for (let postH = 0; postH <= maxHops - 1 - preH; postH++) {
|
|
109
|
+
const postLabel = postTree.labelAt(to, postH);
|
|
110
|
+
if (!postLabel)
|
|
111
|
+
continue;
|
|
112
|
+
const allHops = [
|
|
113
|
+
...preLabel.route.hops,
|
|
114
|
+
swapHop,
|
|
115
|
+
...postLabel.route.hops,
|
|
116
|
+
];
|
|
117
|
+
const candidate = {
|
|
118
|
+
hops: allHops,
|
|
119
|
+
totalFees: preLabel.totalFees + inboundFee + outboundFee + postLabel.totalFees,
|
|
120
|
+
tokenIn,
|
|
121
|
+
tokenOut,
|
|
122
|
+
estimatedBlocks: allHops.length * 2,
|
|
123
|
+
swapHops: [swapHop],
|
|
124
|
+
};
|
|
125
|
+
if (!best || _crossTokenBetter(candidate, best)) {
|
|
126
|
+
best = candidate;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return best;
|
|
132
|
+
}
|
|
133
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
134
|
+
function _crossTokenBetter(a, b) {
|
|
135
|
+
if (a.totalFees !== b.totalFees)
|
|
136
|
+
return a.totalFees < b.totalFees;
|
|
137
|
+
if (a.hops.length !== b.hops.length)
|
|
138
|
+
return a.hops.length < b.hops.length;
|
|
139
|
+
if (a.swapHops.length !== b.swapHops.length)
|
|
140
|
+
return a.swapHops.length < b.swapHops.length;
|
|
141
|
+
return _routeKey(a.hops) < _routeKey(b.hops);
|
|
142
|
+
}
|
|
143
|
+
function _routeKey(hops) {
|
|
144
|
+
return hops.map((hop) => {
|
|
145
|
+
if (hop.isSwap) {
|
|
146
|
+
const swap = hop;
|
|
147
|
+
return `swap:${swap.channelId}:${swap.outboundChannelId}`;
|
|
148
|
+
}
|
|
149
|
+
return (0, bounded_search_js_1.edgeKey)(hop);
|
|
150
|
+
}).join('>');
|
|
151
|
+
}
|
|
@@ -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;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SCALE = void 0;
|
|
4
|
+
exports.parseRateToScaled = parseRateToScaled;
|
|
5
|
+
exports.applyRate = applyRate;
|
|
6
|
+
/** Fixed-point scale shared by routing fees and swap rates. */
|
|
7
|
+
exports.SCALE = 100000000n;
|
|
8
|
+
/**
|
|
9
|
+
* Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
|
|
10
|
+
* "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
|
|
11
|
+
*/
|
|
12
|
+
function parseRateToScaled(rate) {
|
|
13
|
+
const neg = rate.startsWith('-');
|
|
14
|
+
const abs = neg ? rate.slice(1) : rate;
|
|
15
|
+
const dot = abs.indexOf('.');
|
|
16
|
+
const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
|
|
17
|
+
const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
|
|
18
|
+
const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
|
|
19
|
+
const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
|
|
20
|
+
const result = BigInt(intPart) * exports.SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
|
|
21
|
+
return neg ? -result : result;
|
|
22
|
+
}
|
|
23
|
+
/** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
|
|
24
|
+
function applyRate(amountIn, rate) {
|
|
25
|
+
const rateScaled = parseRateToScaled(rate);
|
|
26
|
+
return (amountIn * rateScaled) / exports.SCALE;
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PaymentRequest } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Generate a random 32-byte preimage, compute SHA3-256(preimage) as the
|
|
4
|
+
* hashlock, and return a PaymentRequest that is ready to share.
|
|
5
|
+
*
|
|
6
|
+
* The returned PaymentRequest includes the `preimage` field so the payer
|
|
7
|
+
* can call executeMultiHopPayment. Strip `preimage` before forwarding the
|
|
8
|
+
* request to intermediaries.
|
|
9
|
+
*
|
|
10
|
+
* Compatible with Bare/Pear environments: uses globalThis.crypto.getRandomValues
|
|
11
|
+
* (Web Crypto API, available in Node ≥18, browsers, and Pear/Bare runtimes).
|
|
12
|
+
*/
|
|
13
|
+
export declare function buildPaymentRequest(amount: bigint, tokenId: string, expiryBlock: bigint, description?: string): PaymentRequest;
|
|
14
|
+
/**
|
|
15
|
+
* Recipient-side variant: generates a payment request for the token they want
|
|
16
|
+
* to receive. The API is identical to buildPaymentRequest — the distinction
|
|
17
|
+
* is conceptual (recipient generates hashlock; sender sources liquidity).
|
|
18
|
+
*/
|
|
19
|
+
export declare function buildCrossTokenRequest(amountOut: bigint, tokenOut: string, expiryBlock: bigint, description?: string): PaymentRequest;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildPaymentRequest = buildPaymentRequest;
|
|
4
|
+
exports.buildCrossTokenRequest = buildCrossTokenRequest;
|
|
5
|
+
const core_1 = require("@totemsdk/core");
|
|
6
|
+
/**
|
|
7
|
+
* Generate a random 32-byte preimage, compute SHA3-256(preimage) as the
|
|
8
|
+
* hashlock, and return a PaymentRequest that is ready to share.
|
|
9
|
+
*
|
|
10
|
+
* The returned PaymentRequest includes the `preimage` field so the payer
|
|
11
|
+
* can call executeMultiHopPayment. Strip `preimage` before forwarding the
|
|
12
|
+
* request to intermediaries.
|
|
13
|
+
*
|
|
14
|
+
* Compatible with Bare/Pear environments: uses globalThis.crypto.getRandomValues
|
|
15
|
+
* (Web Crypto API, available in Node ≥18, browsers, and Pear/Bare runtimes).
|
|
16
|
+
*/
|
|
17
|
+
function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
|
|
18
|
+
const preimageBytes = new Uint8Array(32);
|
|
19
|
+
globalThis.crypto.getRandomValues(preimageBytes);
|
|
20
|
+
const preimage = '0x' + (0, core_1.hex)(preimageBytes);
|
|
21
|
+
const hashlock = '0x' + (0, core_1.hex)((0, core_1.F)(preimageBytes));
|
|
22
|
+
return {
|
|
23
|
+
hashlock,
|
|
24
|
+
preimage,
|
|
25
|
+
amount,
|
|
26
|
+
tokenId,
|
|
27
|
+
expiryBlock,
|
|
28
|
+
description,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Recipient-side variant: generates a payment request for the token they want
|
|
33
|
+
* to receive. The API is identical to buildPaymentRequest — the distinction
|
|
34
|
+
* is conceptual (recipient generates hashlock; sender sources liquidity).
|
|
35
|
+
*/
|
|
36
|
+
function buildCrossTokenRequest(amountOut, tokenOut, expiryBlock, description) {
|
|
37
|
+
return buildPaymentRequest(amountOut, tokenOut, expiryBlock, description);
|
|
38
|
+
}
|
|
@@ -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,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateChannelSpend = validateChannelSpend;
|
|
4
|
+
exports.validateRoutingHop = validateRoutingHop;
|
|
5
|
+
exports.swapIntermediary = swapIntermediary;
|
|
6
|
+
exports.validateSwapHop = validateSwapHop;
|
|
7
|
+
exports.validateRoute = validateRoute;
|
|
8
|
+
function fail(error) {
|
|
9
|
+
return { ok: false, error };
|
|
10
|
+
}
|
|
11
|
+
function partyFor(channel, pkd) {
|
|
12
|
+
return channel.parties.find((party) => party.publicKeyDigest === pkd);
|
|
13
|
+
}
|
|
14
|
+
function otherParty(channel, pkd) {
|
|
15
|
+
return channel.parties.find((party) => party.publicKeyDigest !== pkd);
|
|
16
|
+
}
|
|
17
|
+
/** Validate a single channel spend (status, token, sender, balance). */
|
|
18
|
+
function validateChannelSpend(channel, sender, amount, tokenId) {
|
|
19
|
+
if (channel.status !== 'active') {
|
|
20
|
+
return fail(`channel ${channel.channelId} is ${channel.status}`);
|
|
21
|
+
}
|
|
22
|
+
if (channel.tokenId !== tokenId) {
|
|
23
|
+
return fail(`channel ${channel.channelId} token ${channel.tokenId} != ${tokenId}`);
|
|
24
|
+
}
|
|
25
|
+
if (amount <= 0n) {
|
|
26
|
+
return fail(`channel ${channel.channelId} spend amount must be positive`);
|
|
27
|
+
}
|
|
28
|
+
const party = partyFor(channel, sender);
|
|
29
|
+
if (!party) {
|
|
30
|
+
return fail(`sender ${sender} is not a party on channel ${channel.channelId}`);
|
|
31
|
+
}
|
|
32
|
+
const balance = channel.balances[party.partyId] ?? 0n;
|
|
33
|
+
if (balance < amount) {
|
|
34
|
+
return fail(`insufficient balance on channel ${channel.channelId}: ${balance.toString()} < ${amount.toString()}`);
|
|
35
|
+
}
|
|
36
|
+
return { ok: true };
|
|
37
|
+
}
|
|
38
|
+
/** Validate a single-token hop. */
|
|
39
|
+
function validateRoutingHop(channels, hop) {
|
|
40
|
+
const channel = channels.get(hop.channelId);
|
|
41
|
+
if (!channel)
|
|
42
|
+
return fail(`channel ${hop.channelId} not found`);
|
|
43
|
+
if (hop.from === hop.to)
|
|
44
|
+
return fail(`hop ${hop.channelId} has identical from/to`);
|
|
45
|
+
if (!partyFor(channel, hop.to)) {
|
|
46
|
+
return fail(`recipient ${hop.to} is not a party on channel ${hop.channelId}`);
|
|
47
|
+
}
|
|
48
|
+
return validateChannelSpend(channel, hop.from, hop.amount, hop.tokenId);
|
|
49
|
+
}
|
|
50
|
+
/** The intermediary that connects a swap's inbound and outbound channels. */
|
|
51
|
+
function swapIntermediary(channels, hop) {
|
|
52
|
+
const inbound = channels.get(hop.inboundChannelId);
|
|
53
|
+
if (!inbound)
|
|
54
|
+
return undefined;
|
|
55
|
+
return otherParty(inbound, hop.from)?.publicKeyDigest;
|
|
56
|
+
}
|
|
57
|
+
/** Validate both legs of a swap hop. */
|
|
58
|
+
function validateSwapHop(channels, hop) {
|
|
59
|
+
const inbound = channels.get(hop.inboundChannelId);
|
|
60
|
+
if (!inbound)
|
|
61
|
+
return fail(`inbound channel ${hop.inboundChannelId} not found`);
|
|
62
|
+
const outbound = channels.get(hop.outboundChannelId);
|
|
63
|
+
if (!outbound)
|
|
64
|
+
return fail(`outbound channel ${hop.outboundChannelId} not found`);
|
|
65
|
+
const inResult = validateChannelSpend(inbound, hop.from, hop.amountIn, hop.tokenIn);
|
|
66
|
+
if (!inResult.ok)
|
|
67
|
+
return inResult;
|
|
68
|
+
const intermediary = otherParty(inbound, hop.from)?.publicKeyDigest;
|
|
69
|
+
if (!intermediary) {
|
|
70
|
+
return fail(`inbound channel ${hop.inboundChannelId} has no intermediary`);
|
|
71
|
+
}
|
|
72
|
+
if (!partyFor(outbound, hop.to)) {
|
|
73
|
+
return fail(`recipient ${hop.to} is not a party on outbound channel ${hop.outboundChannelId}`);
|
|
74
|
+
}
|
|
75
|
+
const outIntermediary = otherParty(outbound, hop.to)?.publicKeyDigest;
|
|
76
|
+
if (outIntermediary !== intermediary) {
|
|
77
|
+
return fail(`swap intermediary mismatch: ${intermediary} != ${outIntermediary ?? 'none'}`);
|
|
78
|
+
}
|
|
79
|
+
return validateChannelSpend(outbound, intermediary, hop.amountOut, hop.tokenOut);
|
|
80
|
+
}
|
|
81
|
+
/** Validate every hop of a route against live channel state. */
|
|
82
|
+
function validateRoute(channels, route) {
|
|
83
|
+
for (const hop of route.hops) {
|
|
84
|
+
const result = hop.isSwap
|
|
85
|
+
? validateSwapHop(channels, hop)
|
|
86
|
+
: validateRoutingHop(channels, hop);
|
|
87
|
+
if (!result.ok)
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
return { ok: true };
|
|
91
|
+
}
|
|
@@ -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;
|
|
@@ -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
|
+
}
|