@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,84 @@
1
+ function fail(error) {
2
+ return { ok: false, error };
3
+ }
4
+ function partyFor(channel, pkd) {
5
+ return channel.parties.find((party) => party.publicKeyDigest === pkd);
6
+ }
7
+ function otherParty(channel, pkd) {
8
+ return channel.parties.find((party) => party.publicKeyDigest !== pkd);
9
+ }
10
+ /** Validate a single channel spend (status, token, sender, balance). */
11
+ export function validateChannelSpend(channel, sender, amount, tokenId) {
12
+ if (channel.status !== 'active') {
13
+ return fail(`channel ${channel.channelId} is ${channel.status}`);
14
+ }
15
+ if (channel.tokenId !== tokenId) {
16
+ return fail(`channel ${channel.channelId} token ${channel.tokenId} != ${tokenId}`);
17
+ }
18
+ if (amount <= 0n) {
19
+ return fail(`channel ${channel.channelId} spend amount must be positive`);
20
+ }
21
+ const party = partyFor(channel, sender);
22
+ if (!party) {
23
+ return fail(`sender ${sender} is not a party on channel ${channel.channelId}`);
24
+ }
25
+ const balance = channel.balances[party.partyId] ?? 0n;
26
+ if (balance < amount) {
27
+ return fail(`insufficient balance on channel ${channel.channelId}: ${balance.toString()} < ${amount.toString()}`);
28
+ }
29
+ return { ok: true };
30
+ }
31
+ /** Validate a single-token hop. */
32
+ export function validateRoutingHop(channels, hop) {
33
+ const channel = channels.get(hop.channelId);
34
+ if (!channel)
35
+ return fail(`channel ${hop.channelId} not found`);
36
+ if (hop.from === hop.to)
37
+ return fail(`hop ${hop.channelId} has identical from/to`);
38
+ if (!partyFor(channel, hop.to)) {
39
+ return fail(`recipient ${hop.to} is not a party on channel ${hop.channelId}`);
40
+ }
41
+ return validateChannelSpend(channel, hop.from, hop.amount, hop.tokenId);
42
+ }
43
+ /** The intermediary that connects a swap's inbound and outbound channels. */
44
+ export function swapIntermediary(channels, hop) {
45
+ const inbound = channels.get(hop.inboundChannelId);
46
+ if (!inbound)
47
+ return undefined;
48
+ return otherParty(inbound, hop.from)?.publicKeyDigest;
49
+ }
50
+ /** Validate both legs of a swap hop. */
51
+ export function validateSwapHop(channels, hop) {
52
+ const inbound = channels.get(hop.inboundChannelId);
53
+ if (!inbound)
54
+ return fail(`inbound channel ${hop.inboundChannelId} not found`);
55
+ const outbound = channels.get(hop.outboundChannelId);
56
+ if (!outbound)
57
+ return fail(`outbound channel ${hop.outboundChannelId} not found`);
58
+ const inResult = validateChannelSpend(inbound, hop.from, hop.amountIn, hop.tokenIn);
59
+ if (!inResult.ok)
60
+ return inResult;
61
+ const intermediary = otherParty(inbound, hop.from)?.publicKeyDigest;
62
+ if (!intermediary) {
63
+ return fail(`inbound channel ${hop.inboundChannelId} has no intermediary`);
64
+ }
65
+ if (!partyFor(outbound, hop.to)) {
66
+ return fail(`recipient ${hop.to} is not a party on outbound channel ${hop.outboundChannelId}`);
67
+ }
68
+ const outIntermediary = otherParty(outbound, hop.to)?.publicKeyDigest;
69
+ if (outIntermediary !== intermediary) {
70
+ return fail(`swap intermediary mismatch: ${intermediary} != ${outIntermediary ?? 'none'}`);
71
+ }
72
+ return validateChannelSpend(outbound, intermediary, hop.amountOut, hop.tokenOut);
73
+ }
74
+ /** Validate every hop of a route against live channel state. */
75
+ export function validateRoute(channels, route) {
76
+ for (const hop of route.hops) {
77
+ const result = hop.isSwap
78
+ ? validateSwapHop(channels, hop)
79
+ : validateRoutingHop(channels, hop);
80
+ if (!result.ok)
81
+ return result;
82
+ }
83
+ return { ok: true };
84
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Routing engine contracts (RFC-055 Phase 1).
3
+ *
4
+ * Internal module: not exported from the package barrel until the semantics are
5
+ * sufficiently tested. `findRoute` and `findCrossTokenRoute` consume it.
6
+ */
7
+ import type { ChannelGraph, Route } from './types.js';
8
+ import { type FeeFunction } from './bounded-search.js';
9
+ export declare const DEFAULT_MAX_HOPS = 8;
10
+ export interface RoutingGraphRevision {
11
+ topology: number;
12
+ economics: number;
13
+ live: number;
14
+ }
15
+ export interface RoutingGraphSnapshot {
16
+ readonly graph: ChannelGraph;
17
+ readonly revision: RoutingGraphRevision;
18
+ }
19
+ export declare function createRoutingGraphSnapshot(graph: ChannelGraph): RoutingGraphSnapshot;
20
+ export interface RoutingQuery {
21
+ source: string;
22
+ destination?: string;
23
+ amount: bigint;
24
+ tokenId: string;
25
+ targetToken?: string;
26
+ /** `undefined` ⇒ default 8; `null` ⇒ unbounded (rejected until implemented). */
27
+ maxHops?: number | null;
28
+ objective?: 'fees-then-hops';
29
+ costModelId?: string;
30
+ }
31
+ /**
32
+ * Versioned cost-model contract. The current model is additive, fixed-amount
33
+ * and non-negative; future models declare amount dependence explicitly.
34
+ */
35
+ export interface RoutingCostModel {
36
+ readonly id: string;
37
+ readonly nonNegative: boolean;
38
+ readonly additive: boolean;
39
+ readonly amountDependent: boolean;
40
+ edgeFee: FeeFunction;
41
+ compare(a: {
42
+ fees: bigint;
43
+ hops: number;
44
+ }, b: {
45
+ fees: bigint;
46
+ hops: number;
47
+ }): number;
48
+ }
49
+ export declare const FIXED_AMOUNT_COST_MODEL: RoutingCostModel;
50
+ export declare class UnsupportedRoutingModeError extends Error {
51
+ readonly mode: string;
52
+ constructor(mode: string);
53
+ }
54
+ export interface RoutingTreeLabel {
55
+ readonly hops: number;
56
+ readonly totalFees: bigint;
57
+ readonly route: Route;
58
+ }
59
+ /** Reusable one-to-many search result. Routes are reconstructed on demand. */
60
+ export interface RoutingTree {
61
+ readonly source: string;
62
+ readonly amount: bigint;
63
+ readonly tokenId: string;
64
+ readonly maxHops: number;
65
+ readonly revision: RoutingGraphRevision;
66
+ readonly costModelId: string;
67
+ readonly destinations: readonly string[];
68
+ labelAt(destination: string, hops: number): RoutingTreeLabel | null;
69
+ routeTo(destination: string): Route | null;
70
+ }
71
+ export interface RoutingEngineCapabilities {
72
+ readonly bounded: boolean;
73
+ readonly unbounded: boolean;
74
+ readonly oneToMany: boolean;
75
+ readonly incremental: boolean;
76
+ readonly crossToken: boolean;
77
+ }
78
+ export interface RoutingEngine {
79
+ readonly id: string;
80
+ readonly capabilities: RoutingEngineCapabilities;
81
+ findRoute(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): Route | null;
82
+ computeTree(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): RoutingTree;
83
+ }
84
+ export declare function selectRoutingEngine(_snapshot: RoutingGraphSnapshot): RoutingEngine;
85
+ /** Cache key includes every input that materially affects correctness. */
86
+ export declare function routeCacheKey(snapshot: RoutingGraphSnapshot, query: RoutingQuery, costModel?: RoutingCostModel): string;
@@ -0,0 +1,147 @@
1
+ import { bfsLayers, bfsRoute, computeLayers, defaultEdgeFee, isZeroFeeToken, reconstructFromLayers, routeFromLayers, } from './bounded-search.js';
2
+ import { getGraphRevisions } from './graph.js';
3
+ export const DEFAULT_MAX_HOPS = 8;
4
+ export function createRoutingGraphSnapshot(graph) {
5
+ return { graph, revision: getGraphRevisions(graph) };
6
+ }
7
+ export const FIXED_AMOUNT_COST_MODEL = {
8
+ id: 'fixed-amount-v1',
9
+ nonNegative: true,
10
+ additive: true,
11
+ amountDependent: false,
12
+ edgeFee: defaultEdgeFee,
13
+ compare(a, b) {
14
+ if (a.fees < b.fees)
15
+ return -1;
16
+ if (a.fees > b.fees)
17
+ return 1;
18
+ return a.hops - b.hops;
19
+ },
20
+ };
21
+ export class UnsupportedRoutingModeError extends Error {
22
+ constructor(mode) {
23
+ super(`Routing mode unsupported: ${mode}`);
24
+ this.mode = mode;
25
+ this.name = 'UnsupportedRoutingModeError';
26
+ }
27
+ }
28
+ function resolveMaxHops(query) {
29
+ if (query.maxHops === undefined)
30
+ return DEFAULT_MAX_HOPS;
31
+ if (query.maxHops === null)
32
+ throw new UnsupportedRoutingModeError('unbounded');
33
+ if (!Number.isInteger(query.maxHops) || query.maxHops < 0) {
34
+ throw new Error(`maxHops must be a non-negative integer (got ${String(query.maxHops)})`);
35
+ }
36
+ return query.maxHops;
37
+ }
38
+ class LayeredRoutingEngine {
39
+ constructor() {
40
+ this.id = 'layered-bounded-v1';
41
+ this.capabilities = {
42
+ bounded: true,
43
+ unbounded: false,
44
+ oneToMany: true,
45
+ incremental: false,
46
+ crossToken: true,
47
+ };
48
+ }
49
+ findRoute(snapshot, query, costModel = FIXED_AMOUNT_COST_MODEL) {
50
+ const maxHops = resolveMaxHops(query);
51
+ if (query.amount <= 0n || !query.destination)
52
+ return null;
53
+ if (isZeroFeeToken(snapshot.graph, query.tokenId, query.amount, costModel.edgeFee)) {
54
+ return bfsRoute(snapshot.graph, query.source, query.destination, query.amount, query.tokenId, maxHops);
55
+ }
56
+ const layers = computeLayers(snapshot.graph, query.source, query.amount, query.tokenId, maxHops, costModel.edgeFee);
57
+ return routeFromLayers(layers, query.destination, query.amount, query.tokenId, maxHops);
58
+ }
59
+ computeTree(snapshot, query, costModel = FIXED_AMOUNT_COST_MODEL) {
60
+ const maxHops = resolveMaxHops(query);
61
+ let layers;
62
+ if (query.amount <= 0n) {
63
+ layers = Array.from({ length: maxHops + 1 }, () => new Map());
64
+ }
65
+ else if (isZeroFeeToken(snapshot.graph, query.tokenId, query.amount, costModel.edgeFee)) {
66
+ // Zero-fee trees carry shortest-hop labels only (longer zero-fee paths are never better).
67
+ layers = bfsLayers(snapshot.graph, query.source, query.amount, query.tokenId, maxHops);
68
+ }
69
+ else {
70
+ layers = computeLayers(snapshot.graph, query.source, query.amount, query.tokenId, maxHops, costModel.edgeFee);
71
+ }
72
+ return createRoutingTree(snapshot, query, costModel, maxHops, layers);
73
+ }
74
+ }
75
+ function createRoutingTree(snapshot, query, costModel, maxHops, layers) {
76
+ const destinations = new Set();
77
+ for (const layer of layers) {
78
+ for (const node of layer.keys())
79
+ destinations.add(node);
80
+ }
81
+ const labelAt = (destination, hops) => {
82
+ if (!Number.isInteger(hops) || hops < 0 || hops > maxHops)
83
+ return null;
84
+ const label = layers[hops]?.get(destination);
85
+ if (!label)
86
+ return null;
87
+ const routeHops = reconstructFromLayers(layers, hops, destination, query.amount, query.tokenId);
88
+ return {
89
+ hops,
90
+ totalFees: label.totalFees,
91
+ route: {
92
+ hops: routeHops,
93
+ totalFees: label.totalFees,
94
+ tokenIn: query.tokenId,
95
+ tokenOut: query.tokenId,
96
+ estimatedBlocks: routeHops.length * 2,
97
+ },
98
+ };
99
+ };
100
+ return {
101
+ source: query.source,
102
+ amount: query.amount,
103
+ tokenId: query.tokenId,
104
+ maxHops,
105
+ revision: snapshot.revision,
106
+ costModelId: costModel.id,
107
+ destinations: [...destinations].sort(),
108
+ labelAt,
109
+ routeTo(destination) {
110
+ let bestH = -1;
111
+ let bestFees = 0n;
112
+ for (let h = 0; h <= maxHops; h++) {
113
+ const label = layers[h]?.get(destination);
114
+ if (!label)
115
+ continue;
116
+ if (bestH === -1 ||
117
+ label.totalFees < bestFees ||
118
+ (label.totalFees === bestFees && h < bestH)) {
119
+ bestH = h;
120
+ bestFees = label.totalFees;
121
+ }
122
+ }
123
+ if (bestH === -1)
124
+ return null;
125
+ return labelAt(destination, bestH)?.route ?? null;
126
+ },
127
+ };
128
+ }
129
+ const LAYERED_ENGINE = new LayeredRoutingEngine();
130
+ export function selectRoutingEngine(_snapshot) {
131
+ return LAYERED_ENGINE;
132
+ }
133
+ /** Cache key includes every input that materially affects correctness. */
134
+ export function routeCacheKey(snapshot, query, costModel = FIXED_AMOUNT_COST_MODEL) {
135
+ return [
136
+ snapshot.revision.topology,
137
+ snapshot.revision.economics,
138
+ snapshot.revision.live,
139
+ query.source,
140
+ query.destination ?? '*',
141
+ query.amount.toString(),
142
+ query.tokenId,
143
+ query.targetToken ?? '',
144
+ query.maxHops === null ? 'unbounded' : String(query.maxHops ?? 'default'),
145
+ costModel.id,
146
+ ].join('|');
147
+ }
package/dist/types.d.ts CHANGED
@@ -123,6 +123,8 @@ export interface RoutingHop {
123
123
  to: string;
124
124
  amount: bigint;
125
125
  tokenId: string;
126
+ /** Edge fee rate (per SCALE); populated by the routing engine. */
127
+ feeRate?: bigint;
126
128
  /** Populated during payment execution */
127
129
  htlcId?: string;
128
130
  }
@@ -189,12 +191,17 @@ export interface PaymentResult {
189
191
  /** Hex preimage revealed during settlement (present on success) */
190
192
  preimage?: string;
191
193
  error?: string;
194
+ /** Machine-readable failure code (e.g. ROUTE_REVALIDATION_FAILED). */
195
+ errorCode?: string;
192
196
  /** htlcIds that were successfully settled */
193
197
  settledHops: string[];
194
198
  /** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
195
199
  feeProofs?: RouterFeeProof[];
196
200
  }
197
201
  export interface RouteOptions {
198
- /** Maximum number of hops (default: 8) */
202
+ /**
203
+ * Maximum number of hops for the whole route (default: 8). For cross-token
204
+ * routes this is a global end-to-end budget.
205
+ */
199
206
  maxHops?: number;
200
207
  }
package/dist/types.js CHANGED
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /**
3
2
  * @totemsdk/omnia-router — public types
4
3
  *
@@ -7,4 +6,4 @@
7
6
  * has no hard runtime dependency on @totemsdk/omnia — callers pass the
8
7
  * real objects (structural typing ensures compatibility).
9
8
  */
10
- Object.defineProperty(exports, "__esModule", { value: true });
9
+ export {};
package/package.json CHANGED
@@ -1,14 +1,19 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-router",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Multi-hop payment routing over Omnia channels — single-token and cross-token paths",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
5
+ "main": "dist/cjs/index.js",
6
+ "types": "dist/cjs/index.d.ts",
7
7
  "exports": {
8
8
  ".": {
9
- "types": "./dist/index.d.ts",
10
- "require": "./dist/index.js",
11
- "import": "./dist/index.js"
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/cjs/index.d.ts",
15
+ "default": "./dist/cjs/index.js"
16
+ }
12
17
  }
13
18
  },
14
19
  "files": [
@@ -17,11 +22,11 @@
17
22
  "LICENSE"
18
23
  ],
19
24
  "dependencies": {
20
- "@totemsdk/core": "^1.2.11",
25
+ "@totemsdk/core": "^1.4.0",
21
26
  "@totemsdk/storage": "^0.1.0"
22
27
  },
23
28
  "peerDependencies": {
24
- "@totemsdk/omnia": "^1.0.2"
29
+ "@totemsdk/omnia": "^2.3.0"
25
30
  },
26
31
  "peerDependenciesMeta": {
27
32
  "@totemsdk/omnia": {
@@ -69,10 +74,12 @@
69
74
  "htlc",
70
75
  "dijkstra"
71
76
  ],
77
+ "type": "module",
72
78
  "scripts": {
73
- "build": "tsc",
79
+ "build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
74
80
  "build:go": "cd go && go build -o ../bin/omnia-router ./cmd/omnia-router",
75
81
  "clean": "rm -rf dist bin",
76
- "test": "jest"
82
+ "test": "jest",
83
+ "bench": "node bench/route-bench.mjs"
77
84
  }
78
85
  }