@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,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @totemsdk/omnia-router — public types
|
|
3
|
+
*
|
|
4
|
+
* All monetary values are scaled bigints (SCALE = 10^8).
|
|
5
|
+
* The router uses local mirrors of OmniaChannel/HTLCRecord so the package
|
|
6
|
+
* has no hard runtime dependency on @totemsdk/omnia — callers pass the
|
|
7
|
+
* real objects (structural typing ensures compatibility).
|
|
8
|
+
*/
|
|
9
|
+
export interface ChannelParty {
|
|
10
|
+
partyId: string;
|
|
11
|
+
publicKeyDigest: string;
|
|
12
|
+
addressIndex: number;
|
|
13
|
+
}
|
|
14
|
+
export type HTLCStatus = 'pending' | 'fulfilled' | 'timed_out';
|
|
15
|
+
export interface ChannelHTLC {
|
|
16
|
+
htlcId: string;
|
|
17
|
+
amount: bigint;
|
|
18
|
+
hashlock: string;
|
|
19
|
+
timeoutBlock: bigint;
|
|
20
|
+
direction: 'offered' | 'received';
|
|
21
|
+
status: HTLCStatus;
|
|
22
|
+
htlcAddress: string;
|
|
23
|
+
senderPublicKeyDigest: string;
|
|
24
|
+
recipientPublicKeyDigest: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ChannelSigner {
|
|
27
|
+
publicKeyDigest: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Minimal mirror of OmniaChannel — the fields the router actually reads.
|
|
31
|
+
* Structurally compatible with @totemsdk/omnia's OmniaChannel so callers
|
|
32
|
+
* can pass real channel objects without an adapter.
|
|
33
|
+
*/
|
|
34
|
+
export interface RouterChannel {
|
|
35
|
+
channelId: string;
|
|
36
|
+
tokenId: string;
|
|
37
|
+
parties: ChannelParty[];
|
|
38
|
+
balances: Record<string, bigint>;
|
|
39
|
+
pendingHTLCs: ChannelHTLC[];
|
|
40
|
+
totalValue: bigint;
|
|
41
|
+
currentSequence: number;
|
|
42
|
+
status: string;
|
|
43
|
+
localSigner?: ChannelSigner;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Parameters for adding an HTLC — mirrors @totemsdk/omnia's AddHTLCParams.
|
|
47
|
+
*/
|
|
48
|
+
export interface HTLCParams {
|
|
49
|
+
amount: bigint;
|
|
50
|
+
hashlock: string;
|
|
51
|
+
timeoutBlock: bigint;
|
|
52
|
+
direction: 'offered' | 'received';
|
|
53
|
+
counterpartPublicKeyDigest: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Opaque lease-provider handle — the router passes it through to the
|
|
57
|
+
* underlying HTLC operations but never inspects it.
|
|
58
|
+
*/
|
|
59
|
+
export type LeaseProvider = unknown;
|
|
60
|
+
/**
|
|
61
|
+
* Dependency-injected HTLC operations.
|
|
62
|
+
*
|
|
63
|
+
* In production, wire in the real functions from @totemsdk/omnia:
|
|
64
|
+
* import { addHTLC, fulfillHTLC, timeoutHTLC } from '@totemsdk/omnia';
|
|
65
|
+
* const ops: ChannelOps = { addHTLC, fulfillHTLC, timeoutHTLC };
|
|
66
|
+
*
|
|
67
|
+
* In tests, pass mocks directly — no jest.mock() needed.
|
|
68
|
+
*/
|
|
69
|
+
export interface ChannelOps {
|
|
70
|
+
addHTLC(channel: RouterChannel, params: HTLCParams, leaseProvider: LeaseProvider): Promise<{
|
|
71
|
+
channel: RouterChannel;
|
|
72
|
+
htlcId: string;
|
|
73
|
+
error?: string;
|
|
74
|
+
}>;
|
|
75
|
+
fulfillHTLC(channel: RouterChannel, htlcId: string, preimage: string, leaseProvider: LeaseProvider): Promise<{
|
|
76
|
+
channel: RouterChannel;
|
|
77
|
+
error?: string;
|
|
78
|
+
}>;
|
|
79
|
+
timeoutHTLC(channel: RouterChannel, htlcId: string, leaseProvider: LeaseProvider): Promise<{
|
|
80
|
+
channel: RouterChannel;
|
|
81
|
+
error?: string;
|
|
82
|
+
}>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A directed edge in the channel graph.
|
|
86
|
+
* For a bidirectional channel, add two edges (one per direction).
|
|
87
|
+
*/
|
|
88
|
+
export interface ChannelGraphEdge {
|
|
89
|
+
channelId: string;
|
|
90
|
+
/** Sender's public key digest */
|
|
91
|
+
from: string;
|
|
92
|
+
/** Recipient's public key digest */
|
|
93
|
+
to: string;
|
|
94
|
+
tokenId: string;
|
|
95
|
+
/** Sender's available balance in scaled units */
|
|
96
|
+
availableBalance: bigint;
|
|
97
|
+
/** Maximum additional HTLC capacity in scaled units */
|
|
98
|
+
htlcCapacity: bigint;
|
|
99
|
+
/** Fee per SCALE units of amount (e.g. 100_000n = 0.1%) */
|
|
100
|
+
feeRate: bigint;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* In-memory channel graph with a swap announcement index.
|
|
104
|
+
*
|
|
105
|
+
* A single logical channel may have up to two directed edges (one per
|
|
106
|
+
* direction of flow, e.g. Alice→Bob and Bob→Alice). Both edges share the
|
|
107
|
+
* same `channelId` and are stored together in `edgesByChannel`.
|
|
108
|
+
*/
|
|
109
|
+
export interface ChannelGraph {
|
|
110
|
+
/** Directed edges keyed by sender pubkey */
|
|
111
|
+
nodeEdges: Map<string, ChannelGraphEdge[]>;
|
|
112
|
+
/**
|
|
113
|
+
* All directed edges for a channel, keyed by channelId.
|
|
114
|
+
* Value is an array because a bidirectional channel has two directed edges.
|
|
115
|
+
*/
|
|
116
|
+
edgesByChannel: Map<string, ChannelGraphEdge[]>;
|
|
117
|
+
/** Swap announcements keyed by `${tokenIn}:${tokenOut}` */
|
|
118
|
+
swapIndex: Map<string, SwapAnnouncement[]>;
|
|
119
|
+
}
|
|
120
|
+
export interface RoutingHop {
|
|
121
|
+
channelId: string;
|
|
122
|
+
from: string;
|
|
123
|
+
to: string;
|
|
124
|
+
amount: bigint;
|
|
125
|
+
tokenId: string;
|
|
126
|
+
/** Populated during payment execution */
|
|
127
|
+
htlcId?: string;
|
|
128
|
+
}
|
|
129
|
+
export interface SwapHop extends RoutingHop {
|
|
130
|
+
isSwap: true;
|
|
131
|
+
tokenIn: string;
|
|
132
|
+
tokenOut: string;
|
|
133
|
+
amountIn: bigint;
|
|
134
|
+
amountOut: bigint;
|
|
135
|
+
/** "amountOut per amountIn" expressed as decimal string, e.g. "0.95" */
|
|
136
|
+
rate: string;
|
|
137
|
+
inboundChannelId: string;
|
|
138
|
+
outboundChannelId: string;
|
|
139
|
+
}
|
|
140
|
+
export interface Route {
|
|
141
|
+
hops: (RoutingHop | SwapHop)[];
|
|
142
|
+
totalFees: bigint;
|
|
143
|
+
tokenIn: string;
|
|
144
|
+
tokenOut: string;
|
|
145
|
+
estimatedBlocks: number;
|
|
146
|
+
}
|
|
147
|
+
export interface CrossTokenRoute extends Route {
|
|
148
|
+
swapHops: SwapHop[];
|
|
149
|
+
}
|
|
150
|
+
export interface SwapAnnouncement {
|
|
151
|
+
intermediaryPubKey: string;
|
|
152
|
+
tokenIn: string;
|
|
153
|
+
tokenOut: string;
|
|
154
|
+
/** How many tokenOut scaled units per tokenIn scaled unit */
|
|
155
|
+
rate: string;
|
|
156
|
+
inboundChannelId: string;
|
|
157
|
+
outboundChannelId: string;
|
|
158
|
+
maxAmountIn: bigint;
|
|
159
|
+
}
|
|
160
|
+
export interface PaymentRequest {
|
|
161
|
+
/** SHA3-256 hex of preimage */
|
|
162
|
+
hashlock: string;
|
|
163
|
+
/**
|
|
164
|
+
* Known to the payer (returned by buildPaymentRequest).
|
|
165
|
+
* Strip this before sharing the request with intermediaries.
|
|
166
|
+
*/
|
|
167
|
+
preimage?: string;
|
|
168
|
+
amount: bigint;
|
|
169
|
+
tokenId: string;
|
|
170
|
+
expiryBlock: bigint;
|
|
171
|
+
description?: string;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A verifiable fee-provenance record for a settled hop (#29): the artifact a
|
|
175
|
+
* pool's `recordPoolFee` earn-proof consumes. Binds channel + HTLC + recipient
|
|
176
|
+
* + amount so a fee record traces to a real fulfilled payment.
|
|
177
|
+
*/
|
|
178
|
+
export interface RouterFeeProof {
|
|
179
|
+
channelId: string;
|
|
180
|
+
htlcId: string;
|
|
181
|
+
recipientPublicKeyDigest: string;
|
|
182
|
+
amount: bigint;
|
|
183
|
+
tokenId: string;
|
|
184
|
+
settledAt: number;
|
|
185
|
+
proofHash: string;
|
|
186
|
+
}
|
|
187
|
+
export interface PaymentResult {
|
|
188
|
+
success: boolean;
|
|
189
|
+
/** Hex preimage revealed during settlement (present on success) */
|
|
190
|
+
preimage?: string;
|
|
191
|
+
error?: string;
|
|
192
|
+
/** htlcIds that were successfully settled */
|
|
193
|
+
settledHops: string[];
|
|
194
|
+
/** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
|
|
195
|
+
feeProofs?: RouterFeeProof[];
|
|
196
|
+
}
|
|
197
|
+
export interface RouteOptions {
|
|
198
|
+
/** Maximum number of hops (default: 8) */
|
|
199
|
+
maxHops?: number;
|
|
200
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @totemsdk/omnia-router — public types
|
|
4
|
+
*
|
|
5
|
+
* All monetary values are scaled bigints (SCALE = 10^8).
|
|
6
|
+
* The router uses local mirrors of OmniaChannel/HTLCRecord so the package
|
|
7
|
+
* has no hard runtime dependency on @totemsdk/omnia — callers pass the
|
|
8
|
+
* real objects (structural typing ensures compatibility).
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
1
|
/**
|
|
3
2
|
* Durable settled-segment ledger (RFC-007 G9).
|
|
4
3
|
*
|
|
@@ -14,25 +13,23 @@
|
|
|
14
13
|
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
15
14
|
* settlement is never lost.
|
|
16
15
|
*/
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const snapshot_1 = require("@totemsdk/storage/snapshot");
|
|
20
|
-
const errors_1 = require("@totemsdk/storage/errors");
|
|
16
|
+
import { createRevisionedSnapshotStore, } from '@totemsdk/storage/snapshot';
|
|
17
|
+
import { StorageError } from '@totemsdk/storage/errors';
|
|
21
18
|
const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
|
|
22
19
|
function segmentKey(channelId, htlcId) {
|
|
23
20
|
return `${channelId}:${htlcId}`;
|
|
24
21
|
}
|
|
25
22
|
function assertLedgerState(state) {
|
|
26
23
|
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
27
|
-
throw new
|
|
24
|
+
throw new StorageError('omnia-router ledger state is not an object', 'corrupt');
|
|
28
25
|
}
|
|
29
26
|
const value = state.segments;
|
|
30
27
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
31
|
-
throw new
|
|
28
|
+
throw new StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
|
|
32
29
|
}
|
|
33
30
|
}
|
|
34
|
-
function createDurableRouterLedger(adapter, options = {}) {
|
|
35
|
-
const snapshots =
|
|
31
|
+
export function createDurableRouterLedger(adapter, options = {}) {
|
|
32
|
+
const snapshots = createRevisionedSnapshotStore(adapter, {
|
|
36
33
|
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
37
34
|
requireAckMode: options.requireAckMode,
|
|
38
35
|
empty: () => ({ segments: {} }),
|
package/dist/execute.js
CHANGED
|
@@ -1,12 +1,4 @@
|
|
|
1
|
-
|
|
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");
|
|
1
|
+
import { bytesToHex, sha3_256 } from '@totemsdk/core';
|
|
10
2
|
// ─── Type guard ───────────────────────────────────────────────────────────────
|
|
11
3
|
function isSwapHop(hop) {
|
|
12
4
|
return hop.isSwap === true;
|
|
@@ -53,7 +45,7 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders) {
|
|
|
53
45
|
*
|
|
54
46
|
* The `channels` map is updated in-place after each HTLC operation.
|
|
55
47
|
*/
|
|
56
|
-
async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
48
|
+
export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
57
49
|
const preimage = paymentRequest.preimage;
|
|
58
50
|
if (!preimage) {
|
|
59
51
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
@@ -132,13 +124,13 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
|
|
|
132
124
|
}
|
|
133
125
|
return { success: true, preimage, settledHops: settled, feeProofs };
|
|
134
126
|
}
|
|
135
|
-
|
|
127
|
+
export const ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
|
|
136
128
|
/**
|
|
137
129
|
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
138
130
|
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
139
131
|
* real fulfilled payment, never a declared string.
|
|
140
132
|
*/
|
|
141
|
-
function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
133
|
+
export function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
142
134
|
const ts = settledAt ?? Date.now();
|
|
143
135
|
const proof = {
|
|
144
136
|
channelId: channel.channelId,
|
|
@@ -152,10 +144,10 @@ function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
|
152
144
|
proof.proofHash = computeRouterFeeProofHash(proof);
|
|
153
145
|
return proof;
|
|
154
146
|
}
|
|
155
|
-
function computeRouterFeeProofHash(proof) {
|
|
147
|
+
export function computeRouterFeeProofHash(proof) {
|
|
156
148
|
const { proofHash, ...rest } = proof;
|
|
157
|
-
const input = `${
|
|
158
|
-
return
|
|
149
|
+
const input = `${ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
|
|
150
|
+
return bytesToHex(sha3_256(new TextEncoder().encode(input)));
|
|
159
151
|
}
|
|
160
152
|
function canonicalJson(value) {
|
|
161
153
|
if (typeof value === 'bigint')
|
|
@@ -175,7 +167,7 @@ function canonicalJson(value) {
|
|
|
175
167
|
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
176
168
|
* Call this explicitly to roll back before or without attempting execution.
|
|
177
169
|
*/
|
|
178
|
-
async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
170
|
+
export async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
179
171
|
const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
|
|
180
172
|
await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
|
|
181
173
|
}
|
|
@@ -195,7 +187,7 @@ async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
|
195
187
|
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
196
188
|
* all still-pending locked HTLCs.
|
|
197
189
|
*/
|
|
198
|
-
async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
190
|
+
export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
199
191
|
const preimage = paymentRequest.preimage;
|
|
200
192
|
if (!preimage) {
|
|
201
193
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
@@ -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;
|
package/dist/forward.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
/**
|
|
14
|
+
* Cleartext routing codec: the envelope is the JSON of the remaining hops.
|
|
15
|
+
* No confidentiality — a forwarder sees the path. Suitable for the RFC-035
|
|
16
|
+
* "known counterparties" scope; swap for an onion codec when path privacy is
|
|
17
|
+
* required.
|
|
18
|
+
*/
|
|
19
|
+
export function createCleartextRoutingCodec() {
|
|
20
|
+
return {
|
|
21
|
+
build(hops) {
|
|
22
|
+
const wire = hops.map((h) => ({
|
|
23
|
+
channelId: h.channelId,
|
|
24
|
+
to: h.to,
|
|
25
|
+
amount: h.amount.toString(),
|
|
26
|
+
tokenId: h.tokenId,
|
|
27
|
+
}));
|
|
28
|
+
return JSON.stringify(wire);
|
|
29
|
+
},
|
|
30
|
+
peel(envelope) {
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(envelope);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { kind: 'final' };
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
39
|
+
return { kind: 'final' };
|
|
40
|
+
const [head, ...rest] = parsed;
|
|
41
|
+
const next = {
|
|
42
|
+
via: head.to,
|
|
43
|
+
amount: BigInt(head.amount),
|
|
44
|
+
tokenId: head.tokenId,
|
|
45
|
+
...(head.channelId ? { channelId: head.channelId } : {}),
|
|
46
|
+
...(head.timeoutBlock ? { timeoutBlock: BigInt(head.timeoutBlock) } : {}),
|
|
47
|
+
};
|
|
48
|
+
return rest.length > 0
|
|
49
|
+
? { kind: 'forward', next, onward: JSON.stringify(rest) }
|
|
50
|
+
: { kind: 'forward', next };
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
package/dist/graph.js
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
|
|
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");
|
|
1
|
+
import { parseRateToScaled } from './pathfind.js';
|
|
9
2
|
/** Create an empty ChannelGraph. */
|
|
10
|
-
function createChannelGraph() {
|
|
3
|
+
export function createChannelGraph() {
|
|
11
4
|
return {
|
|
12
5
|
nodeEdges: new Map(),
|
|
13
6
|
edgesByChannel: new Map(),
|
|
@@ -23,7 +16,7 @@ function createChannelGraph() {
|
|
|
23
16
|
* `addChannel` twice with the same `(channelId, from)` replaces the first
|
|
24
17
|
* entry (balance update semantics).
|
|
25
18
|
*/
|
|
26
|
-
function addChannel(graph, edge) {
|
|
19
|
+
export function addChannel(graph, edge) {
|
|
27
20
|
const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
|
|
28
21
|
// Replace any edge for the same (channelId, from) direction.
|
|
29
22
|
const idx = existing.findIndex(e => e.from === edge.from);
|
|
@@ -44,7 +37,7 @@ function addChannel(graph, edge) {
|
|
|
44
37
|
* Remove ALL directed edges for `channelId` (i.e. both directions).
|
|
45
38
|
* No-op if the channelId is not present.
|
|
46
39
|
*/
|
|
47
|
-
function removeChannel(graph, channelId) {
|
|
40
|
+
export function removeChannel(graph, channelId) {
|
|
48
41
|
const edges = graph.edgesByChannel.get(channelId);
|
|
49
42
|
if (!edges)
|
|
50
43
|
return;
|
|
@@ -74,8 +67,8 @@ function _removeFromNodeEdges(graph, edge) {
|
|
|
74
67
|
* Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
|
|
75
68
|
* are replaced to prevent stale rate data.
|
|
76
69
|
*/
|
|
77
|
-
function announceSwap(graph, announcement) {
|
|
78
|
-
const rateScaled =
|
|
70
|
+
export function announceSwap(graph, announcement) {
|
|
71
|
+
const rateScaled = parseRateToScaled(announcement.rate);
|
|
79
72
|
if (rateScaled <= 0n) {
|
|
80
73
|
throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
|
|
81
74
|
}
|
|
@@ -94,7 +87,7 @@ function announceSwap(graph, announcement) {
|
|
|
94
87
|
/**
|
|
95
88
|
* Return all swap announcements for a given token pair, or an empty array.
|
|
96
89
|
*/
|
|
97
|
-
function getSwapAnnouncements(graph, tokenIn, tokenOut) {
|
|
90
|
+
export function getSwapAnnouncements(graph, tokenIn, tokenOut) {
|
|
98
91
|
return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
|
|
99
92
|
}
|
|
100
93
|
function _swapKey(tokenIn, tokenOut) {
|
package/dist/index.d.ts
CHANGED
|
@@ -4,5 +4,7 @@ export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from '.
|
|
|
4
4
|
export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
|
|
5
5
|
export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
|
|
6
6
|
export type { RouterFeeProof } from './types.js';
|
|
7
|
+
export { createCleartextRoutingCodec } from './forward.js';
|
|
8
|
+
export type { RoutingEnvelopeCodec, ForwardHop, PeelResult } from './forward.js';
|
|
7
9
|
export { createDurableRouterLedger, } from './durable-router-ledger.js';
|
|
8
10
|
export type { SettledSegment, RouterLedgerState, DurableRouterLedger, DurableRouterLedgerOptions, } from './durable-router-ledger.js';
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
var durable_router_ledger_js_1 = require("./durable-router-ledger.js");
|
|
26
|
-
Object.defineProperty(exports, "createDurableRouterLedger", { enumerable: true, get: function () { return durable_router_ledger_js_1.createDurableRouterLedger; } });
|
|
1
|
+
export { createChannelGraph, addChannel, removeChannel, announceSwap, getSwapAnnouncements, } from './graph.js';
|
|
2
|
+
export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from './pathfind.js';
|
|
3
|
+
export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
|
|
4
|
+
export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
|
|
5
|
+
// RFC-035 B4 — pluggable forwarding envelopes (cleartext now; onion behind the same seam).
|
|
6
|
+
export { createCleartextRoutingCodec } from './forward.js';
|
|
7
|
+
export { createDurableRouterLedger, } from './durable-router-ledger.js';
|
package/dist/pathfind.js
CHANGED
|
@@ -1,17 +1,11 @@
|
|
|
1
|
-
|
|
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");
|
|
1
|
+
import { getSwapAnnouncements } from './graph.js';
|
|
8
2
|
const SCALE = 100000000n;
|
|
9
3
|
// ─── Numeric helpers ──────────────────────────────────────────────────────────
|
|
10
4
|
/**
|
|
11
5
|
* Parse a decimal rate string to a scaled bigint (SCALE = 10^8).
|
|
12
6
|
* "0.95" → 95_000_000n, "1.5" → 150_000_000n, "2" → 200_000_000n.
|
|
13
7
|
*/
|
|
14
|
-
function parseRateToScaled(rate) {
|
|
8
|
+
export function parseRateToScaled(rate) {
|
|
15
9
|
const neg = rate.startsWith('-');
|
|
16
10
|
const abs = neg ? rate.slice(1) : rate;
|
|
17
11
|
const dot = abs.indexOf('.');
|
|
@@ -23,7 +17,7 @@ function parseRateToScaled(rate) {
|
|
|
23
17
|
return neg ? -result : result;
|
|
24
18
|
}
|
|
25
19
|
/** Apply rate to amount: amountOut = amountIn × rateScaled / SCALE */
|
|
26
|
-
function applyRate(amountIn, rate) {
|
|
20
|
+
export function applyRate(amountIn, rate) {
|
|
27
21
|
const rateScaled = parseRateToScaled(rate);
|
|
28
22
|
return (amountIn * rateScaled) / SCALE;
|
|
29
23
|
}
|
|
@@ -34,7 +28,7 @@ function applyRate(amountIn, rate) {
|
|
|
34
28
|
*
|
|
35
29
|
* Returns null if no path exists within maxHops.
|
|
36
30
|
*/
|
|
37
|
-
function findRoute(graph, from, to, amount, tokenId, opts) {
|
|
31
|
+
export function findRoute(graph, from, to, amount, tokenId, opts) {
|
|
38
32
|
return _reconstruct(graph, from, to, amount, tokenId, opts?.maxHops ?? 8);
|
|
39
33
|
}
|
|
40
34
|
/** Full path reconstruction (used once Dijkstra confirms a route exists). */
|
|
@@ -98,8 +92,8 @@ function _reconstruct(graph, from, to, amount, tokenId, maxHops) {
|
|
|
98
92
|
* Selection criteria: lowest total fee (including swap fee), then fewest hops,
|
|
99
93
|
* then fewest swap hops.
|
|
100
94
|
*/
|
|
101
|
-
function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
|
|
102
|
-
const announcements =
|
|
95
|
+
export function findCrossTokenRoute(graph, from, to, amountIn, tokenIn, tokenOut, opts) {
|
|
96
|
+
const announcements = getSwapAnnouncements(graph, tokenIn, tokenOut);
|
|
103
97
|
if (announcements.length === 0)
|
|
104
98
|
return null;
|
|
105
99
|
let best = null;
|
package/dist/request.js
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.buildPaymentRequest = buildPaymentRequest;
|
|
4
|
-
exports.buildCrossTokenRequest = buildCrossTokenRequest;
|
|
5
|
-
const core_1 = require("@totemsdk/core");
|
|
1
|
+
import { F, hex } from '@totemsdk/core';
|
|
6
2
|
/**
|
|
7
3
|
* Generate a random 32-byte preimage, compute SHA3-256(preimage) as the
|
|
8
4
|
* hashlock, and return a PaymentRequest that is ready to share.
|
|
@@ -14,11 +10,11 @@ const core_1 = require("@totemsdk/core");
|
|
|
14
10
|
* Compatible with Bare/Pear environments: uses globalThis.crypto.getRandomValues
|
|
15
11
|
* (Web Crypto API, available in Node ≥18, browsers, and Pear/Bare runtimes).
|
|
16
12
|
*/
|
|
17
|
-
function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
|
|
13
|
+
export function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
|
|
18
14
|
const preimageBytes = new Uint8Array(32);
|
|
19
15
|
globalThis.crypto.getRandomValues(preimageBytes);
|
|
20
|
-
const preimage = '0x' +
|
|
21
|
-
const hashlock = '0x' +
|
|
16
|
+
const preimage = '0x' + hex(preimageBytes);
|
|
17
|
+
const hashlock = '0x' + hex(F(preimageBytes));
|
|
22
18
|
return {
|
|
23
19
|
hashlock,
|
|
24
20
|
preimage,
|
|
@@ -33,6 +29,6 @@ function buildPaymentRequest(amount, tokenId, expiryBlock, description) {
|
|
|
33
29
|
* to receive. The API is identical to buildPaymentRequest — the distinction
|
|
34
30
|
* is conceptual (recipient generates hashlock; sender sources liquidity).
|
|
35
31
|
*/
|
|
36
|
-
function buildCrossTokenRequest(amountOut, tokenOut, expiryBlock, description) {
|
|
32
|
+
export function buildCrossTokenRequest(amountOut, tokenOut, expiryBlock, description) {
|
|
37
33
|
return buildPaymentRequest(amountOut, tokenOut, expiryBlock, description);
|
|
38
34
|
}
|
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
|
-
|
|
9
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@totemsdk/omnia-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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
|
-
"
|
|
10
|
-
|
|
11
|
-
|
|
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": [
|
|
@@ -21,7 +26,7 @@
|
|
|
21
26
|
"@totemsdk/storage": "^0.1.0"
|
|
22
27
|
},
|
|
23
28
|
"peerDependencies": {
|
|
24
|
-
"@totemsdk/omnia": "^
|
|
29
|
+
"@totemsdk/omnia": "^2.0.0"
|
|
25
30
|
},
|
|
26
31
|
"peerDependenciesMeta": {
|
|
27
32
|
"@totemsdk/omnia": {
|
|
@@ -69,8 +74,9 @@
|
|
|
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
82
|
"test": "jest"
|