@totemsdk/omnia-splice 0.3.0 → 0.3.2

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/splice.js CHANGED
@@ -99,6 +99,77 @@ function bindDraftToParams(channel, proposal) {
99
99
  'the TX draft may have been tampered with');
100
100
  }
101
101
  }
102
+ /**
103
+ * Build the deterministic splice draft/digest without signing. Used by the
104
+ * wallet/coordinator flow: the caller signs `digest` and attaches the
105
+ * signature before finalization.
106
+ */
107
+ export function buildSpliceProposal(channel, params, proposerPublicKeyDigest) {
108
+ validateChannelQuiesced(channel);
109
+ validateProposalParams(channel, params);
110
+ const proposerInChannel = channel.parties.find(p => p.publicKeyDigest === proposerPublicKeyDigest);
111
+ if (!proposerInChannel)
112
+ throw new SpliceMissingPartyError(proposerPublicKeyDigest);
113
+ const draft = buildSpliceTx(channel, params);
114
+ return {
115
+ spliceId: generateSpliceId(),
116
+ channelId: channel.channelId,
117
+ params,
118
+ spliceTxHex: Buffer.from(spliceDraftToMinimaBytes(draft)).toString('hex'),
119
+ spliceTxDraft: draft,
120
+ proposerPublicKeyDigest,
121
+ digest: computeSpliceTxDigest(draft),
122
+ };
123
+ }
124
+ /** Build an unsigned splice-in proposal (see `buildSpliceProposal`). */
125
+ export function buildSpliceInProposal(channel, additionalCoinId, additionalAmount, proposerPublicKeyDigest, newBalances) {
126
+ validateChannelQuiesced(channel);
127
+ const newTotal = channel.totalValue + additionalAmount;
128
+ const effectiveNewBalances = newBalances ?? scaleBalances(channel.balances, channel.totalValue, newTotal);
129
+ return buildSpliceProposal(channel, {
130
+ type: 'splice_in',
131
+ newTotalValue: newTotal,
132
+ newBalances: effectiveNewBalances,
133
+ additionalCoinId,
134
+ additionalAmount,
135
+ }, proposerPublicKeyDigest);
136
+ }
137
+ /** Build an unsigned splice-out proposal (see `buildSpliceProposal`). */
138
+ export function buildSpliceOutProposal(channel, withdrawAmount, withdrawAddress, proposerPublicKeyDigest, newBalances, extraOutputs) {
139
+ validateChannelQuiesced(channel);
140
+ const extraSum = (extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
141
+ const totalOutflow = withdrawAmount + extraSum;
142
+ if (totalOutflow > channel.totalValue) {
143
+ throw new Error(`buildSpliceOutProposal: total outflow (withdraw ${withdrawAmount} + extra outputs ${extraSum} = ${totalOutflow}) ` +
144
+ `exceeds channel totalValue (${channel.totalValue})`);
145
+ }
146
+ const remainingTotal = channel.totalValue - totalOutflow;
147
+ const effectiveNewBalances = newBalances ?? (() => {
148
+ const ratio = channel.totalValue > 0n ? remainingTotal * 1000n / channel.totalValue : 0n;
149
+ const adjusted = {};
150
+ let assigned = 0n;
151
+ const partyIds = Object.keys(channel.balances);
152
+ for (let i = 0; i < partyIds.length - 1; i++) {
153
+ const pid = partyIds[i];
154
+ const prev = channel.balances[pid] ?? 0n;
155
+ const scaled = (prev * ratio) / 1000n;
156
+ adjusted[pid] = scaled;
157
+ assigned += scaled;
158
+ }
159
+ const lastId = partyIds[partyIds.length - 1];
160
+ if (lastId)
161
+ adjusted[lastId] = remainingTotal - assigned;
162
+ return adjusted;
163
+ })();
164
+ return buildSpliceProposal(channel, {
165
+ type: 'splice_out',
166
+ newTotalValue: remainingTotal,
167
+ newBalances: effectiveNewBalances,
168
+ withdrawAmount,
169
+ withdrawAddress,
170
+ extraOutputs,
171
+ }, proposerPublicKeyDigest);
172
+ }
102
173
  /**
103
174
  * Initiating party proposes a splice-in: add external funds to the channel.
104
175
  *
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Splice successor observation and interrupted-broadcast recovery (RFC-078 §3.5).
3
+ *
4
+ * A splice spends the old channel coin and creates a successor at the same
5
+ * eltoo address. The successor coin id is not known from the transaction alone
6
+ * because the channel input floats (`COINID_ELTOO`). The only trustworthy
7
+ * answer comes from observing the funding address after broadcast. This module
8
+ * provides that observation plus a small journal seam so a process that dies
9
+ * between broadcast and confirmation can finish or retry safely.
10
+ */
11
+ import type { ChannelStatus } from '@totemsdk/omnia';
12
+ /** Minimal chain surface needed by splice observation. */
13
+ export interface SpliceChainObserver {
14
+ getCoins(query: {
15
+ address?: string;
16
+ tokenId?: string;
17
+ coinId?: string;
18
+ relevant?: boolean;
19
+ }): Promise<Array<{
20
+ coinid: string;
21
+ amount: string;
22
+ address: string;
23
+ tokenid: string;
24
+ spent?: boolean;
25
+ created?: string;
26
+ mmrentry?: string;
27
+ }>>;
28
+ getTip(): Promise<{
29
+ block: number;
30
+ }>;
31
+ }
32
+ export interface SpliceSuccessorOptions {
33
+ /** Channel funding address the successor must pay to. */
34
+ address: string;
35
+ /** Token id of the channel coin. */
36
+ tokenId: string;
37
+ /** Exact successor amount. */
38
+ amount: bigint;
39
+ /** Confirmations required before the channel is active. Default 1. */
40
+ confirmations?: number;
41
+ /** Give up after this long and leave the channel funding-pending. Default 30s. */
42
+ timeoutMs?: number;
43
+ /** Poll interval. Default 1s. */
44
+ pollIntervalMs?: number;
45
+ /** Absolute deadline override (used by recovery paths). */
46
+ now?: () => number;
47
+ /** Injected sleep (tests). */
48
+ sleep?: (ms: number) => Promise<void>;
49
+ }
50
+ export interface ObservedSuccessor {
51
+ coinId: string;
52
+ confirmations: number;
53
+ confirmed: boolean;
54
+ coin: {
55
+ coinid: string;
56
+ amount: string;
57
+ address: string;
58
+ tokenid: string;
59
+ created?: string;
60
+ };
61
+ }
62
+ /**
63
+ * Find the successor coin at the channel address, excluding the spent old
64
+ * coin. A coin with `spent: true` is never a valid successor. Confirmation
65
+ * depth is derived from the coin's creation height when the provider supplies
66
+ * it; otherwise it is treated as unconfirmed.
67
+ */
68
+ export declare function observeSpliceSuccessor(chain: SpliceChainObserver, options: SpliceSuccessorOptions): Promise<ObservedSuccessor | null>;
69
+ /** Durable record written before broadcast so a restart can reconcile. */
70
+ export interface PendingSpliceRecord {
71
+ spliceId: string;
72
+ channelId: string;
73
+ txHex: string;
74
+ txpowId: string;
75
+ coinId?: string;
76
+ broadcastAt: number;
77
+ }
78
+ export interface PendingSpliceStore {
79
+ save(record: PendingSpliceRecord): Promise<void> | void;
80
+ clear(spliceId: string): Promise<void> | void;
81
+ list(): Promise<PendingSpliceRecord[]> | PendingSpliceRecord[];
82
+ }
83
+ /** Outcome of reconciling one interrupted splice. */
84
+ export interface SpliceRecoveryResult {
85
+ spliceId: string;
86
+ status: ChannelStatus;
87
+ coinId?: string;
88
+ rebroadcast: boolean;
89
+ error?: string;
90
+ }
91
+ /**
92
+ * Reconcile interrupted broadcasts.
93
+ *
94
+ * - If the successor is already visible, record its coin id and clear the
95
+ * pending entry.
96
+ * - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
97
+ * and leave the entry pending for the next pass.
98
+ */
99
+ export declare function recoverInterruptedSplices(store: PendingSpliceStore, chain: SpliceChainObserver, observe: Omit<SpliceSuccessorOptions, 'now'>, broadcast: (txHex: string) => Promise<{
100
+ txpowid?: string;
101
+ success?: boolean;
102
+ }>): Promise<SpliceRecoveryResult[]>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Splice successor observation and interrupted-broadcast recovery (RFC-078 §3.5).
3
+ *
4
+ * A splice spends the old channel coin and creates a successor at the same
5
+ * eltoo address. The successor coin id is not known from the transaction alone
6
+ * because the channel input floats (`COINID_ELTOO`). The only trustworthy
7
+ * answer comes from observing the funding address after broadcast. This module
8
+ * provides that observation plus a small journal seam so a process that dies
9
+ * between broadcast and confirmation can finish or retry safely.
10
+ */
11
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+ /**
13
+ * Find the successor coin at the channel address, excluding the spent old
14
+ * coin. A coin with `spent: true` is never a valid successor. Confirmation
15
+ * depth is derived from the coin's creation height when the provider supplies
16
+ * it; otherwise it is treated as unconfirmed.
17
+ */
18
+ export async function observeSpliceSuccessor(chain, options) {
19
+ const required = options.confirmations ?? 1;
20
+ const timeoutMs = options.timeoutMs ?? 30000;
21
+ const pollMs = options.pollIntervalMs ?? 1000;
22
+ const now = options.now ?? (() => Date.now());
23
+ const sleep = options.sleep ?? defaultSleep;
24
+ const deadline = now() + timeoutMs;
25
+ for (;;) {
26
+ const coins = await chain.getCoins({ address: options.address, tokenId: options.tokenId });
27
+ const candidate = coins.find((coin) => !coin.spent
28
+ && coin.address.toLowerCase() === options.address.toLowerCase()
29
+ && coin.tokenid.toLowerCase() === options.tokenId.toLowerCase()
30
+ && BigInt(coin.amount) === options.amount);
31
+ if (candidate) {
32
+ const tip = await chain.getTip();
33
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
34
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
35
+ if (confirmations >= required) {
36
+ return { coinId: candidate.coinid, confirmations, confirmed: true, coin: candidate };
37
+ }
38
+ // Found but not deep enough; keep polling until the deadline.
39
+ }
40
+ if (now() >= deadline) {
41
+ if (candidate) {
42
+ const tip = await chain.getTip();
43
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
44
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
45
+ return { coinId: candidate.coinid, confirmations, confirmed: confirmations >= required, coin: candidate };
46
+ }
47
+ return null;
48
+ }
49
+ await sleep(pollMs);
50
+ }
51
+ }
52
+ /**
53
+ * Reconcile interrupted broadcasts.
54
+ *
55
+ * - If the successor is already visible, record its coin id and clear the
56
+ * pending entry.
57
+ * - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
58
+ * and leave the entry pending for the next pass.
59
+ */
60
+ export async function recoverInterruptedSplices(store, chain, observe, broadcast) {
61
+ const pending = await store.list();
62
+ const results = [];
63
+ for (const record of pending) {
64
+ try {
65
+ const observed = await observeSpliceSuccessor(chain, { ...observe, timeoutMs: observe.timeoutMs ?? 0 });
66
+ if (observed?.confirmed) {
67
+ await store.clear(record.spliceId);
68
+ results.push({
69
+ spliceId: record.spliceId,
70
+ status: 'active',
71
+ coinId: observed.coinId,
72
+ rebroadcast: false,
73
+ });
74
+ continue;
75
+ }
76
+ const rebroadcast = await broadcast(record.txHex);
77
+ if (rebroadcast.success === false && !rebroadcast.txpowid) {
78
+ results.push({
79
+ spliceId: record.spliceId,
80
+ status: 'funding_pending',
81
+ rebroadcast: true,
82
+ error: 'rebroadcast rejected',
83
+ });
84
+ }
85
+ else {
86
+ results.push({
87
+ spliceId: record.spliceId,
88
+ status: observed ? 'funding_pending' : 'funding_pending',
89
+ ...(observed ? { coinId: observed.coinId } : {}),
90
+ rebroadcast: true,
91
+ });
92
+ }
93
+ }
94
+ catch (error) {
95
+ results.push({
96
+ spliceId: record.spliceId,
97
+ status: 'funding_pending',
98
+ rebroadcast: false,
99
+ error: String(error),
100
+ });
101
+ }
102
+ }
103
+ return results;
104
+ }
package/dist/types.d.ts CHANGED
@@ -32,11 +32,15 @@ export interface SpliceTxOutput {
32
32
  storeState: boolean;
33
33
  stateVarSettlement: boolean;
34
34
  stateVarSequence: number;
35
+ /** Optional V2 state commitment (binds off-chain balances to the splice TX). */
36
+ stateVarCommitment?: string;
35
37
  }
36
38
  export interface SpliceTxDraft {
37
39
  inputs: SpliceTxInput[];
38
40
  outputs: SpliceTxOutput[];
39
41
  channelId: string;
42
+ /** Sequence the new channel coin commits to (must exceed the old channel). */
43
+ nextSequence: number;
40
44
  params: SpliceParams;
41
45
  }
42
46
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-splice",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Channel splicing for @totemsdk/omnia — resize Minima eltoo channels without a close+reopen cycle",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -21,21 +21,19 @@
21
21
  "rust/pkg/",
22
22
  "rust/pkg-node/",
23
23
  "README.md",
24
- "LICENSE"
24
+ "LICENSE",
25
+ "NOTICE"
25
26
  ],
26
27
  "dependencies": {
27
- "@totemsdk/core": "^1.2.11",
28
- "@totemsdk/omnia": "^2.0.0",
29
- "@totemsdk/tx-builder": "^0.2.1",
30
- "@totemsdk/txpow": "^1.0.2",
31
- "@totemsdk/wots-lease": "^1.0.1",
32
- "@totemsdk/storage": "^0.1.0"
28
+ "@totemsdk/omnia": "^2.4.1",
29
+ "@totemsdk/core": "^1.4.2",
30
+ "@totemsdk/txpow": "^1.1.1",
31
+ "@totemsdk/wots-lease": "^1.0.2",
32
+ "@totemsdk/tx-builder": "^0.3.1",
33
+ "@totemsdk/storage": "^0.2.2"
33
34
  },
34
35
  "devDependencies": {
35
- "@types/jest": "^30.0.0",
36
36
  "@types/node": "^20.0.0",
37
- "jest": "^30.4.2",
38
- "ts-jest": "^29.0.0",
39
37
  "typescript": "^7.0.2"
40
38
  },
41
39
  "engines": {
@@ -44,7 +42,7 @@
44
42
  "publishConfig": {
45
43
  "access": "public"
46
44
  },
47
- "license": "MIT",
45
+ "license": "Apache-2.0",
48
46
  "author": "Totem SDK",
49
47
  "homepage": "https://docs.totem.ing",
50
48
  "bugs": {
@@ -75,7 +73,7 @@
75
73
  "scripts": {
76
74
  "build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
77
75
  "clean": "rm -rf dist rust/pkg rust/pkg-node rust/target",
78
- "test": "jest",
76
+ "test": "jest --config ../../tests/jest/omnia-splice.cjs",
79
77
  "build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
80
78
  }
81
79
  }
@@ -6,7 +6,7 @@
6
6
  ],
7
7
  "description": "Channel splice commitment layer — splice TX digest computation, balance scaling, proposal validation (Rust/WASM)",
8
8
  "version": "0.1.0",
9
- "license": "MIT",
9
+ "license": "Apache-2.0",
10
10
  "repository": {
11
11
  "type": "git",
12
12
  "url": "https://github.com/Totem-Edge/totem-sdk"
@@ -5,7 +5,7 @@
5
5
  ],
6
6
  "description": "Channel splice commitment layer — splice TX digest computation, balance scaling, proposal validation (Rust/WASM)",
7
7
  "version": "0.1.0",
8
- "license": "MIT",
8
+ "license": "Apache-2.0",
9
9
  "repository": {
10
10
  "type": "git",
11
11
  "url": "https://github.com/Totem-Edge/totem-sdk"