@totemsdk/omnia-router 0.2.1 → 0.3.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/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 +303 -0
- package/dist/cjs/forward.d.ts +50 -0
- package/dist/cjs/forward.js +56 -0
- package/dist/cjs/graph.d.ts +32 -0
- package/dist/cjs/graph.js +102 -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 +25 -0
- package/dist/cjs/pathfind.js +253 -0
- package/dist/cjs/request.d.ts +19 -0
- package/dist/cjs/request.js +38 -0
- package/dist/cjs/types.d.ts +200 -0
- package/dist/cjs/types.js +10 -0
- package/dist/durable-router-ledger.js +6 -9
- package/dist/execute.js +9 -17
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +53 -0
- package/dist/graph.js +7 -14
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -26
- package/dist/pathfind.js +6 -12
- package/dist/request.js +5 -9
- package/dist/types.js +1 -2
- package/package.json +14 -8
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createChannelGraph = createChannelGraph;
|
|
4
|
+
exports.addChannel = addChannel;
|
|
5
|
+
exports.removeChannel = removeChannel;
|
|
6
|
+
exports.announceSwap = announceSwap;
|
|
7
|
+
exports.getSwapAnnouncements = getSwapAnnouncements;
|
|
8
|
+
const pathfind_js_1 = require("./pathfind.js");
|
|
9
|
+
/** Create an empty ChannelGraph. */
|
|
10
|
+
function createChannelGraph() {
|
|
11
|
+
return {
|
|
12
|
+
nodeEdges: new Map(),
|
|
13
|
+
edgesByChannel: new Map(),
|
|
14
|
+
swapIndex: new Map(),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Add a directed channel edge to the graph.
|
|
19
|
+
*
|
|
20
|
+
* A single logical channel between two parties has two directed edges — one
|
|
21
|
+
* per direction of flow. Both may be added independently using the same
|
|
22
|
+
* `channelId` because they are keyed by `(channelId, from)`. Calling
|
|
23
|
+
* `addChannel` twice with the same `(channelId, from)` replaces the first
|
|
24
|
+
* entry (balance update semantics).
|
|
25
|
+
*/
|
|
26
|
+
function addChannel(graph, edge) {
|
|
27
|
+
const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
|
|
28
|
+
// Replace any edge for the same (channelId, from) direction.
|
|
29
|
+
const idx = existing.findIndex(e => e.from === edge.from);
|
|
30
|
+
if (idx >= 0) {
|
|
31
|
+
_removeFromNodeEdges(graph, existing[idx]);
|
|
32
|
+
existing.splice(idx, 1, edge);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
existing.push(edge);
|
|
36
|
+
}
|
|
37
|
+
graph.edgesByChannel.set(edge.channelId, existing);
|
|
38
|
+
// Register in nodeEdges for O(1) Dijkstra lookup.
|
|
39
|
+
const nodeList = graph.nodeEdges.get(edge.from) ?? [];
|
|
40
|
+
nodeList.push(edge);
|
|
41
|
+
graph.nodeEdges.set(edge.from, nodeList);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Remove ALL directed edges for `channelId` (i.e. both directions).
|
|
45
|
+
* No-op if the channelId is not present.
|
|
46
|
+
*/
|
|
47
|
+
function removeChannel(graph, channelId) {
|
|
48
|
+
const edges = graph.edgesByChannel.get(channelId);
|
|
49
|
+
if (!edges)
|
|
50
|
+
return;
|
|
51
|
+
for (const edge of edges) {
|
|
52
|
+
_removeFromNodeEdges(graph, edge);
|
|
53
|
+
}
|
|
54
|
+
graph.edgesByChannel.delete(channelId);
|
|
55
|
+
}
|
|
56
|
+
function _removeFromNodeEdges(graph, edge) {
|
|
57
|
+
const nodeList = graph.nodeEdges.get(edge.from);
|
|
58
|
+
if (!nodeList)
|
|
59
|
+
return;
|
|
60
|
+
const filtered = nodeList.filter(e => !(e.channelId === edge.channelId && e.from === edge.from));
|
|
61
|
+
if (filtered.length === 0) {
|
|
62
|
+
graph.nodeEdges.delete(edge.from);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
graph.nodeEdges.set(edge.from, filtered);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Register a swap announcement from a bridging intermediary.
|
|
70
|
+
*
|
|
71
|
+
* Validates that the rate is a positive finite decimal before storing.
|
|
72
|
+
* Throws `Error` if the rate is zero or negative.
|
|
73
|
+
*
|
|
74
|
+
* Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
|
|
75
|
+
* are replaced to prevent stale rate data.
|
|
76
|
+
*/
|
|
77
|
+
function announceSwap(graph, announcement) {
|
|
78
|
+
const rateScaled = (0, pathfind_js_1.parseRateToScaled)(announcement.rate);
|
|
79
|
+
if (rateScaled <= 0n) {
|
|
80
|
+
throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
|
|
81
|
+
}
|
|
82
|
+
const key = _swapKey(announcement.tokenIn, announcement.tokenOut);
|
|
83
|
+
const list = graph.swapIndex.get(key) ?? [];
|
|
84
|
+
const idx = list.findIndex(a => a.intermediaryPubKey === announcement.intermediaryPubKey &&
|
|
85
|
+
a.inboundChannelId === announcement.inboundChannelId);
|
|
86
|
+
if (idx >= 0) {
|
|
87
|
+
list[idx] = announcement;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
list.push(announcement);
|
|
91
|
+
}
|
|
92
|
+
graph.swapIndex.set(key, list);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Return all swap announcements for a given token pair, or an empty array.
|
|
96
|
+
*/
|
|
97
|
+
function getSwapAnnouncements(graph, tokenIn, tokenOut) {
|
|
98
|
+
return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
|
|
99
|
+
}
|
|
100
|
+
function _swapKey(tokenIn, tokenOut) {
|
|
101
|
+
return `${tokenIn}:${tokenOut}`;
|
|
102
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type { RouterChannel, ChannelParty, ChannelHTLC, HTLCStatus, ChannelSigner, ChannelOps, HTLCParams, LeaseProvider, ChannelGraphEdge, ChannelGraph, RoutingHop, SwapHop, Route, CrossTokenRoute, SwapAnnouncement, PaymentRequest, PaymentResult, RouteOptions, } from './types.js';
|
|
2
|
+
export { createChannelGraph, addChannel, removeChannel, announceSwap, getSwapAnnouncements, } from './graph.js';
|
|
3
|
+
export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from './pathfind.js';
|
|
4
|
+
export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
|
|
5
|
+
export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
|
|
6
|
+
export type { RouterFeeProof } from './types.js';
|
|
7
|
+
export { createCleartextRoutingCodec } from './forward.js';
|
|
8
|
+
export type { RoutingEnvelopeCodec, ForwardHop, PeelResult } from './forward.js';
|
|
9
|
+
export { createDurableRouterLedger, } from './durable-router-ledger.js';
|
|
10
|
+
export type { SettledSegment, RouterLedgerState, DurableRouterLedger, DurableRouterLedgerOptions, } from './durable-router-ledger.js';
|
|
@@ -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,25 @@
|
|
|
1
|
+
import type { ChannelGraph, Route, CrossTokenRoute, RouteOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
|
|
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;
|
|
9
|
+
/**
|
|
10
|
+
* Find the cheapest route (lowest total fee, then fewest hops) from `from` to
|
|
11
|
+
* `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
|
|
12
|
+
* availableBalance.
|
|
13
|
+
*
|
|
14
|
+
* Returns null if no path exists within maxHops.
|
|
15
|
+
*/
|
|
16
|
+
export declare function findRoute(graph: ChannelGraph, from: string, to: string, amount: bigint, tokenId: string, opts?: RouteOptions): Route | null;
|
|
17
|
+
/**
|
|
18
|
+
* Find a cross-token route where the sender spends `tokenIn` and the
|
|
19
|
+
* recipient receives `tokenOut`. The path may include one or more swap hops
|
|
20
|
+
* provided by bridging intermediaries registered via announceSwap.
|
|
21
|
+
*
|
|
22
|
+
* Selection criteria: lowest total fee (including swap fee), then fewest hops,
|
|
23
|
+
* then fewest swap hops.
|
|
24
|
+
*/
|
|
25
|
+
export declare function findCrossTokenRoute(graph: ChannelGraph, from: string, to: string, amountIn: bigint, tokenIn: string, tokenOut: string, opts?: RouteOptions): CrossTokenRoute | null;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseRateToScaled = parseRateToScaled;
|
|
4
|
+
exports.applyRate = applyRate;
|
|
5
|
+
exports.findRoute = findRoute;
|
|
6
|
+
exports.findCrossTokenRoute = findCrossTokenRoute;
|
|
7
|
+
const graph_js_1 = require("./graph.js");
|
|
8
|
+
const SCALE = 100000000n;
|
|
9
|
+
// ─── Numeric helpers ──────────────────────────────────────────────────────────
|
|
10
|
+
/**
|
|
11
|
+
* Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
|
|
12
|
+
* "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
|
|
13
|
+
*/
|
|
14
|
+
function parseRateToScaled(rate) {
|
|
15
|
+
const neg = rate.startsWith('-');
|
|
16
|
+
const abs = neg ? rate.slice(1) : rate;
|
|
17
|
+
const dot = abs.indexOf('.');
|
|
18
|
+
const intPart = dot === -1 ? abs : (abs.slice(0, dot) || '0');
|
|
19
|
+
const fracFull = dot === -1 ? '' : abs.slice(dot + 1);
|
|
20
|
+
const fracStr = fracFull.slice(0, 8).padEnd(8, '0');
|
|
21
|
+
const ninth = fracFull.length > 8 ? parseInt(fracFull[8] ?? '0', 10) : 0;
|
|
22
|
+
const result = BigInt(intPart) * SCALE + BigInt(fracStr) + (ninth >= 5 ? 1n : 0n);
|
|
23
|
+
return neg ? -result : result;
|
|
24
|
+
}
|
|
25
|
+
/** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
|
|
26
|
+
function applyRate(amountIn, rate) {
|
|
27
|
+
const rateScaled = parseRateToScaled(rate);
|
|
28
|
+
return (amountIn * rateScaled) / SCALE;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Find the cheapest route (lowest total fee, then fewest hops) from `from` to
|
|
32
|
+
* `to` carrying `amount` of `tokenId`. Edges are filtered by tokenId and
|
|
33
|
+
* availableBalance.
|
|
34
|
+
*
|
|
35
|
+
* Returns null if no path exists within maxHops.
|
|
36
|
+
*/
|
|
37
|
+
function findRoute(graph, from, to, amount, tokenId, opts) {
|
|
38
|
+
return _reconstruct(graph, from, to, amount, tokenId, opts?.maxHops ?? 8);
|
|
39
|
+
}
|
|
40
|
+
/** Full path reconstruction (used once Dijkstra confirms a route exists). */
|
|
41
|
+
function _reconstruct(graph, from, to, amount, tokenId, maxHops) {
|
|
42
|
+
const dist = new Map();
|
|
43
|
+
const queue = [{ node: from, totalFees: 0n, hops: 0, path: [] }];
|
|
44
|
+
dist.set(from, { totalFees: 0n, hops: 0, path: [] });
|
|
45
|
+
while (queue.length > 0) {
|
|
46
|
+
const { node, totalFees, hops, path } = _dequeue(queue);
|
|
47
|
+
if (node === to) {
|
|
48
|
+
return {
|
|
49
|
+
hops: path,
|
|
50
|
+
totalFees,
|
|
51
|
+
tokenIn: tokenId,
|
|
52
|
+
tokenOut: tokenId,
|
|
53
|
+
estimatedBlocks: path.length * 2,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (hops >= maxHops)
|
|
57
|
+
continue;
|
|
58
|
+
for (const edge of (graph.nodeEdges.get(node) ?? [])) {
|
|
59
|
+
if (edge.tokenId !== tokenId)
|
|
60
|
+
continue;
|
|
61
|
+
if (edge.availableBalance < amount)
|
|
62
|
+
continue;
|
|
63
|
+
const fee = _edgeFee(amount, edge);
|
|
64
|
+
const newFees = totalFees + fee;
|
|
65
|
+
const newHops = hops + 1;
|
|
66
|
+
const best = dist.get(edge.to);
|
|
67
|
+
if (best && _notBetter(newFees, newHops, best.totalFees, best.hops))
|
|
68
|
+
continue;
|
|
69
|
+
const hop = {
|
|
70
|
+
channelId: edge.channelId,
|
|
71
|
+
from: edge.from,
|
|
72
|
+
to: edge.to,
|
|
73
|
+
amount,
|
|
74
|
+
tokenId,
|
|
75
|
+
};
|
|
76
|
+
const newPath = [...path, hop];
|
|
77
|
+
dist.set(edge.to, { totalFees: newFees, hops: newHops, path: newPath });
|
|
78
|
+
_enqueue(queue, { node: edge.to, totalFees: newFees, hops: newHops, path: newPath });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const best = dist.get(to);
|
|
82
|
+
if (!best)
|
|
83
|
+
return null;
|
|
84
|
+
return {
|
|
85
|
+
hops: best.path,
|
|
86
|
+
totalFees: best.totalFees,
|
|
87
|
+
tokenIn: tokenId,
|
|
88
|
+
tokenOut: tokenId,
|
|
89
|
+
estimatedBlocks: best.path.length * 2,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
// ─── Cross-token Dijkstra ─────────────────────────────────────────────────────
|
|
93
|
+
/**
|
|
94
|
+
* Find a cross-token route where the sender spends `tokenIn` and the
|
|
95
|
+
* recipient receives `tokenOut`. The path may include one or more swap hops
|
|
96
|
+
* provided by bridging intermediaries registered via announceSwap.
|
|
97
|
+
*
|
|
98
|
+
* Selection criteria: lowest total fee (including swap fee), then fewest hops,
|
|
99
|
+
* then fewest swap hops.
|
|
100
|
+
*/
|
|
101
|
+
function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
|
|
102
|
+
const announcements = (0, graph_js_1.getSwapAnnouncements)(graph, tokenIn, tokenOut);
|
|
103
|
+
if (announcements.length === 0)
|
|
104
|
+
return null;
|
|
105
|
+
let best = null;
|
|
106
|
+
for (const ann of announcements) {
|
|
107
|
+
// Validate maxAmountIn
|
|
108
|
+
if (amountIn > ann.maxAmountIn)
|
|
109
|
+
continue;
|
|
110
|
+
// Inbound segment: from → intermediary via tokenIn.
|
|
111
|
+
// Look up the directed edge whose `to` is the intermediary (the edge ends
|
|
112
|
+
// at the intermediary so they can claim the inbound HTLC).
|
|
113
|
+
const inboundEdges = graph.edgesByChannel.get(ann.inboundChannelId) ?? [];
|
|
114
|
+
const inboundEdge = inboundEdges.find(e => e.to === ann.intermediaryPubKey && e.tokenId === tokenIn);
|
|
115
|
+
if (!inboundEdge)
|
|
116
|
+
continue;
|
|
117
|
+
// Check the inbound edge has sufficient balance
|
|
118
|
+
if (inboundEdge.availableBalance < amountIn)
|
|
119
|
+
continue;
|
|
120
|
+
// amountOut from rate — must be positive (validated at announceSwap, but
|
|
121
|
+
// guard here defensively in case of adversarial state or direct graph edits)
|
|
122
|
+
const amountOut = applyRate(amountIn, ann.rate);
|
|
123
|
+
if (amountOut <= 0n)
|
|
124
|
+
continue;
|
|
125
|
+
// Outbound segment: intermediary → recipient via tokenOut.
|
|
126
|
+
// Look up the directed edge whose `from` is the intermediary.
|
|
127
|
+
const outboundEdges = graph.edgesByChannel.get(ann.outboundChannelId) ?? [];
|
|
128
|
+
const outboundEdge = outboundEdges.find(e => e.from === ann.intermediaryPubKey && e.tokenId === tokenOut);
|
|
129
|
+
if (!outboundEdge)
|
|
130
|
+
continue;
|
|
131
|
+
if (outboundEdge.availableBalance < amountOut)
|
|
132
|
+
continue;
|
|
133
|
+
// SwapHop represents the ENTIRE atomic bridge crossing — both the inbound
|
|
134
|
+
// and outbound channels are locked together with the same hashlock inside
|
|
135
|
+
// executeCrossTokenPayment. We must NOT also include those channels as
|
|
136
|
+
// ordinary RoutingHops, or execution would try to lock them twice.
|
|
137
|
+
//
|
|
138
|
+
// Therefore:
|
|
139
|
+
// pre-swap = route from `from` → inboundEdge.from
|
|
140
|
+
// post-swap = route from outboundEdge.to → `to`
|
|
141
|
+
//
|
|
142
|
+
// Fees for the swap channels themselves (inboundFee + outboundFee) are
|
|
143
|
+
// accounted for separately and NOT included in pre/post route totals.
|
|
144
|
+
const preSrc = inboundEdge.from; // sender side of the inbound channel
|
|
145
|
+
const postDst = outboundEdge.to; // receiver side of the outbound channel
|
|
146
|
+
// Pre-swap route: from → preSrc (empty when from IS the inbound channel sender)
|
|
147
|
+
let preRoute;
|
|
148
|
+
if (from === preSrc) {
|
|
149
|
+
preRoute = { hops: [], totalFees: 0n, tokenIn, tokenOut: tokenIn, estimatedBlocks: 0 };
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
preRoute = findRoute(graph, from, preSrc, amountIn, tokenIn, opts);
|
|
153
|
+
}
|
|
154
|
+
if (!preRoute)
|
|
155
|
+
continue;
|
|
156
|
+
// Post-swap route: postDst → to (empty when postDst IS the final recipient)
|
|
157
|
+
let postRoute;
|
|
158
|
+
if (postDst === to) {
|
|
159
|
+
postRoute = { hops: [], totalFees: 0n, tokenIn: tokenOut, tokenOut, estimatedBlocks: 0 };
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
postRoute = findRoute(graph, postDst, to, amountOut, tokenOut, opts);
|
|
163
|
+
}
|
|
164
|
+
if (!postRoute)
|
|
165
|
+
continue;
|
|
166
|
+
// Build the swap hop (encompasses both swap channels)
|
|
167
|
+
const swapHop = {
|
|
168
|
+
isSwap: true,
|
|
169
|
+
channelId: ann.inboundChannelId,
|
|
170
|
+
from: preSrc,
|
|
171
|
+
to: postDst,
|
|
172
|
+
amount: amountIn,
|
|
173
|
+
tokenId: tokenIn,
|
|
174
|
+
tokenIn,
|
|
175
|
+
tokenOut,
|
|
176
|
+
amountIn,
|
|
177
|
+
amountOut,
|
|
178
|
+
rate: ann.rate,
|
|
179
|
+
inboundChannelId: ann.inboundChannelId,
|
|
180
|
+
outboundChannelId: ann.outboundChannelId,
|
|
181
|
+
};
|
|
182
|
+
// Fees: pre + inbound swap channel + outbound swap channel + post
|
|
183
|
+
// (no double-counting — swap channels are NOT in preRoute/postRoute hops)
|
|
184
|
+
const inboundFee = _edgeFee(amountIn, inboundEdge);
|
|
185
|
+
const outboundFee = _edgeFee(amountOut, outboundEdge);
|
|
186
|
+
const totalFees = preRoute.totalFees + inboundFee + outboundFee + postRoute.totalFees;
|
|
187
|
+
const allHops = [
|
|
188
|
+
...preRoute.hops,
|
|
189
|
+
swapHop,
|
|
190
|
+
...postRoute.hops,
|
|
191
|
+
];
|
|
192
|
+
const candidate = {
|
|
193
|
+
hops: allHops,
|
|
194
|
+
totalFees,
|
|
195
|
+
tokenIn,
|
|
196
|
+
tokenOut,
|
|
197
|
+
estimatedBlocks: allHops.length * 2,
|
|
198
|
+
swapHops: [swapHop],
|
|
199
|
+
};
|
|
200
|
+
if (!best || _crossTokenBetter(candidate, best)) {
|
|
201
|
+
best = candidate;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return best;
|
|
205
|
+
}
|
|
206
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
207
|
+
function _edgeFee(amount, edge) {
|
|
208
|
+
return (amount * edge.feeRate) / SCALE;
|
|
209
|
+
}
|
|
210
|
+
/** Returns true if (newFees, newHops) is NOT better than (bestFees, bestHops). */
|
|
211
|
+
function _notBetter(newFees, newHops, bestFees, bestHops) {
|
|
212
|
+
if (newFees > bestFees)
|
|
213
|
+
return true;
|
|
214
|
+
if (newFees < bestFees)
|
|
215
|
+
return false;
|
|
216
|
+
return newHops >= bestHops;
|
|
217
|
+
}
|
|
218
|
+
function _crossTokenBetter(a, b) {
|
|
219
|
+
if (a.totalFees < b.totalFees)
|
|
220
|
+
return true;
|
|
221
|
+
if (a.totalFees > b.totalFees)
|
|
222
|
+
return false;
|
|
223
|
+
if (a.hops.length < b.hops.length)
|
|
224
|
+
return true;
|
|
225
|
+
if (a.hops.length > b.hops.length)
|
|
226
|
+
return false;
|
|
227
|
+
return a.swapHops.length < b.swapHops.length;
|
|
228
|
+
}
|
|
229
|
+
/** Extract a single-edge route when `from` → `to` via `edge` is a direct hop. */
|
|
230
|
+
function _singleEdgeRoute(edge, from, to, amount, tokenId) {
|
|
231
|
+
if (edge.from !== from || edge.to !== to)
|
|
232
|
+
return null;
|
|
233
|
+
if (edge.tokenId !== tokenId)
|
|
234
|
+
return null;
|
|
235
|
+
if (edge.availableBalance < amount)
|
|
236
|
+
return null;
|
|
237
|
+
const hop = { channelId: edge.channelId, from, to, amount, tokenId };
|
|
238
|
+
return { hops: [hop], totalFees: _edgeFee(amount, edge), tokenIn: tokenId, tokenOut: tokenId, estimatedBlocks: 2 };
|
|
239
|
+
}
|
|
240
|
+
/** Dequeue the minimum-cost state from the priority queue. */
|
|
241
|
+
function _dequeue(queue) {
|
|
242
|
+
let minIdx = 0;
|
|
243
|
+
for (let i = 1; i < queue.length; i++) {
|
|
244
|
+
const a = queue[i], b = queue[minIdx];
|
|
245
|
+
if (a.totalFees < b.totalFees || (a.totalFees === b.totalFees && a.hops < b.hops)) {
|
|
246
|
+
minIdx = i;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return queue.splice(minIdx, 1)[0];
|
|
250
|
+
}
|
|
251
|
+
function _enqueue(queue, state) {
|
|
252
|
+
queue.push(state);
|
|
253
|
+
}
|
|
@@ -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
|
+
}
|