@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.
Files changed (47) hide show
  1. package/dist/bounded-search.d.ts +36 -0
  2. package/dist/bounded-search.js +164 -0
  3. package/dist/cjs/bounded-search.d.ts +36 -0
  4. package/dist/cjs/bounded-search.js +174 -0
  5. package/dist/cjs/durable-router-ledger.d.ts +60 -0
  6. package/dist/cjs/durable-router-ledger.js +88 -0
  7. package/dist/cjs/execute.d.ts +45 -0
  8. package/dist/cjs/execute.js +359 -0
  9. package/dist/cjs/forward.d.ts +50 -0
  10. package/dist/cjs/forward.js +56 -0
  11. package/dist/cjs/graph.d.ts +40 -0
  12. package/dist/cjs/graph.js +141 -0
  13. package/dist/cjs/index.d.ts +10 -0
  14. package/dist/cjs/index.js +29 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/pathfind.d.ts +24 -0
  17. package/dist/cjs/pathfind.js +151 -0
  18. package/dist/cjs/rates.d.ts +9 -0
  19. package/dist/cjs/rates.js +27 -0
  20. package/dist/cjs/request.d.ts +19 -0
  21. package/dist/cjs/request.js +38 -0
  22. package/dist/cjs/route-validation.d.ts +24 -0
  23. package/dist/cjs/route-validation.js +91 -0
  24. package/dist/cjs/routing-engine.d.ts +86 -0
  25. package/dist/cjs/routing-engine.js +154 -0
  26. package/dist/cjs/types.d.ts +207 -0
  27. package/dist/cjs/types.js +10 -0
  28. package/dist/durable-router-ledger.js +6 -9
  29. package/dist/execute.js +72 -24
  30. package/dist/forward.d.ts +50 -0
  31. package/dist/forward.js +53 -0
  32. package/dist/graph.d.ts +8 -0
  33. package/dist/graph.js +46 -15
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +7 -26
  36. package/dist/pathfind.d.ts +11 -12
  37. package/dist/pathfind.js +88 -196
  38. package/dist/rates.d.ts +9 -0
  39. package/dist/rates.js +22 -0
  40. package/dist/request.js +5 -9
  41. package/dist/route-validation.d.ts +24 -0
  42. package/dist/route-validation.js +84 -0
  43. package/dist/routing-engine.d.ts +86 -0
  44. package/dist/routing-engine.js +147 -0
  45. package/dist/types.d.ts +8 -1
  46. package/dist/types.js +1 -2
  47. package/package.json +17 -10
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROUTER_FEE_PROOF_DOMAIN = void 0;
4
+ exports.executeMultiHopPayment = executeMultiHopPayment;
5
+ exports.buildRouterFeeProof = buildRouterFeeProof;
6
+ exports.computeRouterFeeProofHash = computeRouterFeeProofHash;
7
+ exports.cancelPayment = cancelPayment;
8
+ exports.executeCrossTokenPayment = executeCrossTokenPayment;
9
+ const core_1 = require("@totemsdk/core");
10
+ const route_validation_js_1 = require("./route-validation.js");
11
+ const rates_js_1 = require("./rates.js");
12
+ // ─── Type guard ───────────────────────────────────────────────────────────────
13
+ function isSwapHop(hop) {
14
+ return hop.isSwap === true;
15
+ }
16
+ function revalidationErrorCode(message) {
17
+ return message.includes('ROUTE_REVALIDATION_FAILED') ? 'ROUTE_REVALIDATION_FAILED' : undefined;
18
+ }
19
+ // ─── Internal helpers ─────────────────────────────────────────────────────────
20
+ /** Determine the counterparty public key digest relative to the local signer. */
21
+ function counterpartPkd(channel) {
22
+ const localPkd = channel.localSigner?.publicKeyDigest;
23
+ const other = channel.parties.find(p => p.publicKeyDigest !== localPkd);
24
+ if (!other)
25
+ throw new Error(`Channel ${channel.channelId}: cannot determine counterpart`);
26
+ return other.publicKeyDigest;
27
+ }
28
+ /**
29
+ * Best-effort timeout of a set of locked HTLCs.
30
+ * Errors from individual timeoutHTLC calls are silently ignored so rollback
31
+ * always completes as many cancellations as possible.
32
+ */
33
+ async function cancelHtlcs(ops, channels, locked, leaseProviders) {
34
+ for (const { channelId, htlcId } of [...locked].reverse()) {
35
+ const ch = channels.get(channelId);
36
+ const lp = leaseProviders.get(channelId);
37
+ if (!ch || !lp)
38
+ continue;
39
+ try {
40
+ const res = await ops.timeoutHTLC(ch, htlcId, lp);
41
+ channels.set(channelId, res.channel);
42
+ }
43
+ catch { /* best-effort: continue rolling back other hops */ }
44
+ }
45
+ }
46
+ // ─── Single-token multi-hop payment ──────────────────────────────────────────
47
+ /**
48
+ * Execute a single-token multi-hop payment atomically:
49
+ *
50
+ * 1. Forward phase — lock HTLCs across each hop in route.hops.
51
+ * 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
52
+ *
53
+ * Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
54
+ * failure, including failures that occur during the reveal phase — so stranded
55
+ * HTLCs are never left behind silently.
56
+ *
57
+ * `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
58
+ *
59
+ * The `channels` map is updated in-place after each HTLC operation.
60
+ */
61
+ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
62
+ const preimage = paymentRequest.preimage;
63
+ if (!preimage) {
64
+ return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
65
+ }
66
+ const plainHops = route.hops.filter(h => !isSwapHop(h));
67
+ // Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
68
+ // downstream intermediaries; the fee for the final edge belongs to the
69
+ // recipient and is not charged. Intermediary i retains
70
+ // hopAmount[i] - hopAmount[i+1]. With no fee rates this is the legacy
71
+ // same-amount behaviour.
72
+ const fees = plainHops.map((hop) => hop.feeRate && hop.feeRate > 0n ? (paymentRequest.amount * hop.feeRate) / rates_js_1.SCALE : 0n);
73
+ for (let i = 0; i < plainHops.length; i++) {
74
+ const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
75
+ plainHops[i].amount = paymentRequest.amount + downstream;
76
+ }
77
+ const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route);
78
+ if (!routeValidation.ok) {
79
+ return {
80
+ success: false,
81
+ error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
82
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
83
+ settledHops: [],
84
+ };
85
+ }
86
+ const locked = [];
87
+ // ── Forward: lock HTLCs ───────────────────────────────────────────────────
88
+ for (let i = 0; i < plainHops.length; i++) {
89
+ const hop = plainHops[i];
90
+ const channel = channels.get(hop.channelId);
91
+ if (!channel) {
92
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
93
+ return { success: false, error: `Channel ${hop.channelId} not found`, settledHops: [] };
94
+ }
95
+ const lp = leaseProviders.get(hop.channelId);
96
+ if (!lp) {
97
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
98
+ return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
99
+ }
100
+ const hopValidation = (0, route_validation_js_1.validateRoutingHop)(channels, hop);
101
+ if (!hopValidation.ok) {
102
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
103
+ return {
104
+ success: false,
105
+ error: `ROUTE_REVALIDATION_FAILED: ${hopValidation.error}`,
106
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
107
+ settledHops: [],
108
+ };
109
+ }
110
+ // Timeouts decrease toward the recipient so each hop has time to claim.
111
+ const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
112
+ let addResult;
113
+ try {
114
+ addResult = await ops.addHTLC(channel, {
115
+ amount: hop.amount,
116
+ hashlock: paymentRequest.hashlock,
117
+ timeoutBlock,
118
+ direction: 'offered',
119
+ counterpartPublicKeyDigest: counterpartPkd(channel),
120
+ }, lp);
121
+ }
122
+ catch (err) {
123
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
124
+ return { success: false, error: String(err), settledHops: [] };
125
+ }
126
+ if (addResult.error) {
127
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
128
+ return { success: false, error: addResult.error, settledHops: [] };
129
+ }
130
+ channels.set(hop.channelId, addResult.channel);
131
+ hop.htlcId = addResult.htlcId;
132
+ locked.push({ channelId: hop.channelId, htlcId: addResult.htlcId });
133
+ }
134
+ // ── Backward: reveal preimage ─────────────────────────────────────────────
135
+ // Track fulfilled IDs so that on failure we can timeout only the still-pending
136
+ // ones (already-fulfilled HTLCs are irreversible and must not be retouched).
137
+ const settled = [];
138
+ const fulfilledSet = new Set();
139
+ const feeProofs = [];
140
+ for (const { channelId, htlcId } of [...locked].reverse()) {
141
+ const channel = channels.get(channelId);
142
+ const lp = leaseProviders.get(channelId);
143
+ let fulfillResult;
144
+ try {
145
+ fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
146
+ }
147
+ catch (err) {
148
+ // Timeout every still-pending lock (not yet fulfilled)
149
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
150
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
151
+ return { success: false, error: String(err), settledHops: settled };
152
+ }
153
+ if (fulfillResult.error) {
154
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
155
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
156
+ return { success: false, error: fulfillResult.error, settledHops: settled };
157
+ }
158
+ channels.set(channelId, fulfillResult.channel);
159
+ settled.push(htlcId);
160
+ fulfilledSet.add(htlcId);
161
+ // Build the verifiable fee proof for this settled hop (#29).
162
+ const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
163
+ if (htlc) {
164
+ feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
165
+ }
166
+ }
167
+ return { success: true, preimage, settledHops: settled, feeProofs };
168
+ }
169
+ exports.ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
170
+ /**
171
+ * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
172
+ * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
173
+ * real fulfilled payment, never a declared string.
174
+ */
175
+ function buildRouterFeeProof(channel, htlc, settledAt) {
176
+ const ts = settledAt ?? Date.now();
177
+ const proof = {
178
+ channelId: channel.channelId,
179
+ htlcId: htlc.htlcId,
180
+ recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
181
+ amount: htlc.amount,
182
+ tokenId: channel.tokenId,
183
+ settledAt: ts,
184
+ proofHash: '',
185
+ };
186
+ proof.proofHash = computeRouterFeeProofHash(proof);
187
+ return proof;
188
+ }
189
+ function computeRouterFeeProofHash(proof) {
190
+ const { proofHash, ...rest } = proof;
191
+ const input = `${exports.ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
192
+ return (0, core_1.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode(input)));
193
+ }
194
+ function canonicalJson(value) {
195
+ if (typeof value === 'bigint')
196
+ return JSON.stringify({ __bigint: value.toString() });
197
+ if (Array.isArray(value))
198
+ return `[${value.map(canonicalJson).join(',')}]`;
199
+ if (value && typeof value === 'object') {
200
+ const keys = Object.keys(value).sort();
201
+ const pairs = keys
202
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
203
+ .filter((p) => p !== `${JSON.stringify('')}:null`);
204
+ return `{${pairs.join(',')}}`;
205
+ }
206
+ return JSON.stringify(value);
207
+ }
208
+ /**
209
+ * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
210
+ * Call this explicitly to roll back before or without attempting execution.
211
+ */
212
+ async function cancelPayment(ops, channels, route, leaseProviders) {
213
+ const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
214
+ await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
215
+ }
216
+ // ─── Cross-token multi-hop payment ───────────────────────────────────────────
217
+ /**
218
+ * Execute a cross-token payment atomically.
219
+ *
220
+ * For each SwapHop:
221
+ * 1. Lock the inbound HTLC (tokenIn side).
222
+ * 2. Lock the outbound HTLC (tokenOut side).
223
+ * Both use the same hashlock — the intermediary can only claim by revealing
224
+ * the preimage on both sides simultaneously.
225
+ *
226
+ * Then forward-locks all remaining non-swap hops, and reveals the preimage
227
+ * backwards across all locked channels.
228
+ *
229
+ * Rollback fires on ANY failure (forward OR backward phase) by timing out
230
+ * all still-pending locked HTLCs.
231
+ */
232
+ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
233
+ const preimage = paymentRequest.preimage;
234
+ if (!preimage) {
235
+ return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
236
+ }
237
+ const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route);
238
+ if (!routeValidation.ok) {
239
+ return {
240
+ success: false,
241
+ error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
242
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
243
+ settledHops: [],
244
+ };
245
+ }
246
+ const locked = [];
247
+ /**
248
+ * Lock a single HTLC, add it to `locked`, and return the htlcId.
249
+ * Throws on any error so callers can handle rollback uniformly.
250
+ */
251
+ async function lockHTLC(channelId, amount, hashlock, timeoutBlock, tokenId, sender) {
252
+ const channel = channels.get(channelId);
253
+ const lp = leaseProviders.get(channelId);
254
+ if (!channel)
255
+ throw new Error(`Channel ${channelId} not found`);
256
+ if (!lp)
257
+ throw new Error(`No lease provider for channel ${channelId}`);
258
+ const spend = (0, route_validation_js_1.validateChannelSpend)(channel, sender, amount, tokenId);
259
+ if (!spend.ok)
260
+ throw new Error(`ROUTE_REVALIDATION_FAILED: ${spend.error}`);
261
+ // Let addHTLC exceptions propagate — they carry the original error message.
262
+ const result = await ops.addHTLC(channel, {
263
+ amount,
264
+ hashlock,
265
+ timeoutBlock,
266
+ direction: 'offered',
267
+ counterpartPublicKeyDigest: counterpartPkd(channel),
268
+ }, lp);
269
+ if (result.error)
270
+ throw new Error(result.error);
271
+ channels.set(channelId, result.channel);
272
+ locked.push({ channelId, htlcId: result.htlcId });
273
+ return result.htlcId;
274
+ }
275
+ // ── Lock HTLCs in full route order with monotonically decreasing timeouts ──
276
+ //
277
+ // Correct HTLC safety requires timeouts to DECREASE toward the recipient:
278
+ // sender (highest timeout) → ... → recipient (lowest timeout)
279
+ //
280
+ // We iterate route.hops in their declared order. For each RoutingHop we
281
+ // consume one position. For each SwapHop we consume two consecutive
282
+ // positions: inbound channel first (higher timeout), outbound second (lower).
283
+ //
284
+ // position 0: preHops[0] ← highest timeout
285
+ // position 1: preHops[1]
286
+ // ...
287
+ // position k: swapInbound
288
+ // position k+1: swapOutbound
289
+ // ...
290
+ // position n: postHops[last] ← lowest timeout
291
+ let pos = 0;
292
+ for (const hop of route.hops) {
293
+ if (isSwapHop(hop)) {
294
+ // Inbound channel (sender → intermediary, tokenIn side)
295
+ const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
296
+ try {
297
+ hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
298
+ }
299
+ catch (err) {
300
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
301
+ return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
302
+ }
303
+ // Outbound channel (intermediary → recipient, tokenOut side)
304
+ const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
305
+ const intermediary = (0, route_validation_js_1.swapIntermediary)(channels, hop);
306
+ if (!intermediary) {
307
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
308
+ return {
309
+ success: false,
310
+ error: `ROUTE_REVALIDATION_FAILED: no intermediary for ${hop.inboundChannelId}`,
311
+ errorCode: 'ROUTE_REVALIDATION_FAILED',
312
+ settledHops: [],
313
+ };
314
+ }
315
+ try {
316
+ await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout, hop.tokenOut, intermediary);
317
+ }
318
+ catch (err) {
319
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
320
+ return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
321
+ }
322
+ }
323
+ else {
324
+ const timeout = paymentRequest.expiryBlock - BigInt(pos++);
325
+ try {
326
+ hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
327
+ }
328
+ catch (err) {
329
+ await cancelHtlcs(ops, channels, locked, leaseProviders);
330
+ return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
331
+ }
332
+ }
333
+ }
334
+ // ── Reveal preimage backward ──────────────────────────────────────────────
335
+ const settled = [];
336
+ const fulfilledSet = new Set();
337
+ for (const { channelId, htlcId } of [...locked].reverse()) {
338
+ const channel = channels.get(channelId);
339
+ const lp = leaseProviders.get(channelId);
340
+ let fulfillResult;
341
+ try {
342
+ fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
343
+ }
344
+ catch (err) {
345
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
346
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
347
+ return { success: false, error: String(err), settledHops: settled };
348
+ }
349
+ if (fulfillResult.error) {
350
+ const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
351
+ await cancelHtlcs(ops, channels, stillPending, leaseProviders);
352
+ return { success: false, error: fulfillResult.error, settledHops: settled };
353
+ }
354
+ channels.set(channelId, fulfillResult.channel);
355
+ settled.push(htlcId);
356
+ fulfilledSet.add(htlcId);
357
+ }
358
+ return { success: true, preimage, settledHops: settled };
359
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Multi-hop forwarding envelopes (RFC-035 B4).
3
+ *
4
+ * A forwarder is handed an opaque `routingEnvelope` alongside an incoming HTLC
5
+ * and peels one hop from it: it learns the next hop, locks an HTLC onward, and
6
+ * passes the remaining (smaller) envelope to that hop.
7
+ *
8
+ * The envelope is deliberately **opaque** so the representation is pluggable: the
9
+ * cleartext codec (below) is the first implementation; an onion (X25519 + AEAD,
10
+ * per-hop encryption keys advertised on graph edges) can be added behind the same
11
+ * `RoutingEnvelopeCodec` seam without changing the message types.
12
+ */
13
+ import type { RoutingHop, SwapHop } from './types.js';
14
+ /** Onward instruction the forwarder peels from an envelope. */
15
+ export interface ForwardHop {
16
+ /** Next-hop party public-key digest (the immediate recipient of the outgoing HTLC). */
17
+ via: string;
18
+ /** Optional explicit outgoing channel id (else the forwarder finds its channel to `via`). */
19
+ channelId?: string;
20
+ amount: bigint;
21
+ tokenId: string;
22
+ /** Absolute timeout (block) for the outgoing HTLC, when the envelope carries one. */
23
+ timeoutBlock?: bigint;
24
+ }
25
+ export type PeelResult =
26
+ /** This node is the recipient — no onward hop. */
27
+ {
28
+ kind: 'final';
29
+ }
30
+ /** Forward to `next`; `onward` is the remaining envelope for that hop (absent at the last hop). */
31
+ | {
32
+ kind: 'forward';
33
+ next: ForwardHop;
34
+ onward?: string;
35
+ };
36
+ export interface RoutingEnvelopeCodec {
37
+ /** Sender: build the envelope from the onward hops (already excludes the first hop). */
38
+ build(hops: (RoutingHop | SwapHop)[]): string;
39
+ /** Forwarder: peel one hop for `self`. */
40
+ peel(envelope: string, self: {
41
+ publicKeyDigest: string;
42
+ }): PeelResult;
43
+ }
44
+ /**
45
+ * Cleartext routing codec: the envelope is the JSON of the remaining hops.
46
+ * No confidentiality — a forwarder sees the path. Suitable for the RFC-035
47
+ * "known counterparties" scope; swap for an onion codec when path privacy is
48
+ * required.
49
+ */
50
+ export declare function createCleartextRoutingCodec(): RoutingEnvelopeCodec;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ /**
3
+ * Multi-hop forwarding envelopes (RFC-035 B4).
4
+ *
5
+ * A forwarder is handed an opaque `routingEnvelope` alongside an incoming HTLC
6
+ * and peels one hop from it: it learns the next hop, locks an HTLC onward, and
7
+ * passes the remaining (smaller) envelope to that hop.
8
+ *
9
+ * The envelope is deliberately **opaque** so the representation is pluggable: the
10
+ * cleartext codec (below) is the first implementation; an onion (X25519 + AEAD,
11
+ * per-hop encryption keys advertised on graph edges) can be added behind the same
12
+ * `RoutingEnvelopeCodec` seam without changing the message types.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createCleartextRoutingCodec = createCleartextRoutingCodec;
16
+ /**
17
+ * Cleartext routing codec: the envelope is the JSON of the remaining hops.
18
+ * No confidentiality — a forwarder sees the path. Suitable for the RFC-035
19
+ * "known counterparties" scope; swap for an onion codec when path privacy is
20
+ * required.
21
+ */
22
+ function createCleartextRoutingCodec() {
23
+ return {
24
+ build(hops) {
25
+ const wire = hops.map((h) => ({
26
+ channelId: h.channelId,
27
+ to: h.to,
28
+ amount: h.amount.toString(),
29
+ tokenId: h.tokenId,
30
+ }));
31
+ return JSON.stringify(wire);
32
+ },
33
+ peel(envelope) {
34
+ let parsed;
35
+ try {
36
+ parsed = JSON.parse(envelope);
37
+ }
38
+ catch {
39
+ return { kind: 'final' };
40
+ }
41
+ if (!Array.isArray(parsed) || parsed.length === 0)
42
+ return { kind: 'final' };
43
+ const [head, ...rest] = parsed;
44
+ const next = {
45
+ via: head.to,
46
+ amount: BigInt(head.amount),
47
+ tokenId: head.tokenId,
48
+ ...(head.channelId ? { channelId: head.channelId } : {}),
49
+ ...(head.timeoutBlock ? { timeoutBlock: BigInt(head.timeoutBlock) } : {}),
50
+ };
51
+ return rest.length > 0
52
+ ? { kind: 'forward', next, onward: JSON.stringify(rest) }
53
+ : { kind: 'forward', next };
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,40 @@
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;
10
+ /** Create an empty ChannelGraph. */
11
+ export declare function createChannelGraph(): ChannelGraph;
12
+ /**
13
+ * Add a directed channel edge to the graph.
14
+ *
15
+ * A single logical channel between two parties has two directed edges — one
16
+ * per direction of flow. Both may be added independently using the same
17
+ * `channelId` because they are keyed by `(channelId, from)`. Calling
18
+ * `addChannel` twice with the same `(channelId, from)` replaces the first
19
+ * entry (balance update semantics).
20
+ */
21
+ export declare function addChannel(graph: ChannelGraph, edge: ChannelGraphEdge): void;
22
+ /**
23
+ * Remove ALL directed edges for `channelId` (i.e. both directions).
24
+ * No-op if the channelId is not present.
25
+ */
26
+ export declare function removeChannel(graph: ChannelGraph, channelId: string): void;
27
+ /**
28
+ * Register a swap announcement from a bridging intermediary.
29
+ *
30
+ * Validates that the rate is a positive finite decimal before storing.
31
+ * Throws `Error` if the rate is zero or negative.
32
+ *
33
+ * Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
34
+ * are replaced to prevent stale rate data.
35
+ */
36
+ export declare function announceSwap(graph: ChannelGraph, announcement: SwapAnnouncement): void;
37
+ /**
38
+ * Return all swap announcements for a given token pair, or an empty array.
39
+ */
40
+ export declare function getSwapAnnouncements(graph: ChannelGraph, tokenIn: string, tokenOut: string): SwapAnnouncement[];
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGraphRevisions = getGraphRevisions;
4
+ exports.createChannelGraph = createChannelGraph;
5
+ exports.addChannel = addChannel;
6
+ exports.removeChannel = removeChannel;
7
+ exports.announceSwap = announceSwap;
8
+ exports.getSwapAnnouncements = getSwapAnnouncements;
9
+ const rates_js_1 = require("./rates.js");
10
+ const graphRevisions = new WeakMap();
11
+ function ensureRevisions(graph) {
12
+ let revisions = graphRevisions.get(graph);
13
+ if (!revisions) {
14
+ revisions = { topology: 0, economics: 0, live: 0 };
15
+ graphRevisions.set(graph, revisions);
16
+ }
17
+ return revisions;
18
+ }
19
+ /** Snapshot-consistent revision marker for routing caches and trees. */
20
+ function getGraphRevisions(graph) {
21
+ return { ...ensureRevisions(graph) };
22
+ }
23
+ function bumpTopology(graph) {
24
+ const revisions = ensureRevisions(graph);
25
+ revisions.topology += 1;
26
+ revisions.live += 1;
27
+ }
28
+ function bumpEconomics(graph) {
29
+ ensureRevisions(graph).economics += 1;
30
+ }
31
+ /** Create an empty ChannelGraph. */
32
+ function createChannelGraph() {
33
+ const graph = {
34
+ nodeEdges: new Map(),
35
+ edgesByChannel: new Map(),
36
+ swapIndex: new Map(),
37
+ };
38
+ graphRevisions.set(graph, { topology: 0, economics: 0, live: 0 });
39
+ return graph;
40
+ }
41
+ /**
42
+ * Add a directed channel edge to the graph.
43
+ *
44
+ * A single logical channel between two parties has two directed edges — one
45
+ * per direction of flow. Both may be added independently using the same
46
+ * `channelId` because they are keyed by `(channelId, from)`. Calling
47
+ * `addChannel` twice with the same `(channelId, from)` replaces the first
48
+ * entry (balance update semantics).
49
+ */
50
+ function addChannel(graph, edge) {
51
+ if (!edge.channelId || !edge.from || !edge.to || !edge.tokenId) {
52
+ throw new Error('addChannel requires non-empty channelId, from, to and tokenId');
53
+ }
54
+ if (edge.feeRate < 0n) {
55
+ throw new Error(`Invalid feeRate ${edge.feeRate.toString()} for channel ${edge.channelId}: must be non-negative`);
56
+ }
57
+ if (edge.availableBalance < 0n) {
58
+ throw new Error(`Invalid availableBalance ${edge.availableBalance.toString()} for channel ${edge.channelId}: must be non-negative`);
59
+ }
60
+ if (edge.htlcCapacity < 0n) {
61
+ throw new Error(`Invalid htlcCapacity ${edge.htlcCapacity.toString()} for channel ${edge.channelId}: must be non-negative`);
62
+ }
63
+ const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
64
+ // Replace any edge for the same (channelId, from) direction.
65
+ const idx = existing.findIndex(e => e.from === edge.from);
66
+ if (idx >= 0) {
67
+ _removeFromNodeEdges(graph, existing[idx]);
68
+ existing.splice(idx, 1, edge);
69
+ }
70
+ else {
71
+ existing.push(edge);
72
+ }
73
+ graph.edgesByChannel.set(edge.channelId, existing);
74
+ // Register in nodeEdges for O(1) Dijkstra lookup.
75
+ const nodeList = graph.nodeEdges.get(edge.from) ?? [];
76
+ nodeList.push(edge);
77
+ graph.nodeEdges.set(edge.from, nodeList);
78
+ bumpTopology(graph);
79
+ }
80
+ /**
81
+ * Remove ALL directed edges for `channelId` (i.e. both directions).
82
+ * No-op if the channelId is not present.
83
+ */
84
+ function removeChannel(graph, channelId) {
85
+ const edges = graph.edgesByChannel.get(channelId);
86
+ if (!edges)
87
+ return;
88
+ for (const edge of edges) {
89
+ _removeFromNodeEdges(graph, edge);
90
+ }
91
+ graph.edgesByChannel.delete(channelId);
92
+ bumpTopology(graph);
93
+ }
94
+ function _removeFromNodeEdges(graph, edge) {
95
+ const nodeList = graph.nodeEdges.get(edge.from);
96
+ if (!nodeList)
97
+ return;
98
+ const filtered = nodeList.filter(e => !(e.channelId === edge.channelId && e.from === edge.from));
99
+ if (filtered.length === 0) {
100
+ graph.nodeEdges.delete(edge.from);
101
+ }
102
+ else {
103
+ graph.nodeEdges.set(edge.from, filtered);
104
+ }
105
+ }
106
+ /**
107
+ * Register a swap announcement from a bridging intermediary.
108
+ *
109
+ * Validates that the rate is a positive finite decimal before storing.
110
+ * Throws `Error` if the rate is zero or negative.
111
+ *
112
+ * Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
113
+ * are replaced to prevent stale rate data.
114
+ */
115
+ function announceSwap(graph, announcement) {
116
+ const rateScaled = (0, rates_js_1.parseRateToScaled)(announcement.rate);
117
+ if (rateScaled <= 0n) {
118
+ throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
119
+ }
120
+ const key = _swapKey(announcement.tokenIn, announcement.tokenOut);
121
+ const list = graph.swapIndex.get(key) ?? [];
122
+ const idx = list.findIndex(a => a.intermediaryPubKey === announcement.intermediaryPubKey &&
123
+ a.inboundChannelId === announcement.inboundChannelId);
124
+ if (idx >= 0) {
125
+ list[idx] = announcement;
126
+ }
127
+ else {
128
+ list.push(announcement);
129
+ }
130
+ graph.swapIndex.set(key, list);
131
+ bumpEconomics(graph);
132
+ }
133
+ /**
134
+ * Return all swap announcements for a given token pair, or an empty array.
135
+ */
136
+ function getSwapAnnouncements(graph, tokenIn, tokenOut) {
137
+ return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
138
+ }
139
+ function _swapKey(tokenIn, tokenOut) {
140
+ return `${tokenIn}:${tokenOut}`;
141
+ }
@@ -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';