@totemsdk/omnia-splice 0.2.1 → 0.3.1

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.
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSpliceTx = buildSpliceTx;
4
+ exports.spliceDraftToMinimaBytes = spliceDraftToMinimaBytes;
5
+ exports.computeSpliceTxDigest = computeSpliceTxDigest;
6
+ const core_1 = require("@totemsdk/core");
7
+ const core_2 = require("@totemsdk/core");
8
+ const omnia_1 = require("@totemsdk/omnia");
9
+ const errors_js_1 = require("./errors.js");
10
+ const STATE_SETTLEMENT_PORT = 100;
11
+ const STATE_SEQUENCE_PORT = 101;
12
+ /**
13
+ * Build a validated SpliceTxDraft from channel + splice params.
14
+ *
15
+ * For splice-in:
16
+ * inputs = [channel coin (latestCoinId), additional coin]
17
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
18
+ *
19
+ * For splice-out:
20
+ * inputs = [channel coin (latestCoinId)]
21
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
22
+ * [withdrawal coin at withdrawAddress]
23
+ * [any extra outputs]
24
+ *
25
+ * The output channel coin always resets STATE(101)=0 so the new channel starts
26
+ * from sequence 0 with a full WOTS signing budget.
27
+ *
28
+ * @param channel - Quiesced or active channel to splice.
29
+ * @param params - Splice parameters (type, amounts, addresses).
30
+ * @returns Validated SpliceTxDraft.
31
+ * @throws {SpliceBalanceConservationError} If output amounts do not sum to newTotalValue.
32
+ * @throws {SpliceInsufficientFundsError} If splice-out exceeds channel holdings.
33
+ */
34
+ function buildSpliceTx(channel, params) {
35
+ const tokenId = channel.tokenId ?? '0x00';
36
+ if (params.type === 'splice_out') {
37
+ const withdrawAmount = params.withdrawAmount ?? 0n;
38
+ const extraSum = (params.extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
39
+ const totalOutflow = withdrawAmount + extraSum;
40
+ if (totalOutflow > channel.totalValue) {
41
+ throw new errors_js_1.SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
42
+ }
43
+ if (params.newTotalValue < 0n) {
44
+ throw new errors_js_1.SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
45
+ }
46
+ }
47
+ const balanceSum = Object.values(params.newBalances).reduce((a, b) => a + b, 0n);
48
+ // `params.newTotalValue` is the amount that will remain locked in the new channel coin
49
+ // after the splice. `newBalances` must sum exactly to that value.
50
+ // Withdrawals and extra outputs are separate outputs, already factored out by the
51
+ // caller when computing `newTotalValue`.
52
+ if (balanceSum !== params.newTotalValue) {
53
+ throw new errors_js_1.SpliceBalanceConservationError(params.newTotalValue, balanceSum);
54
+ }
55
+ const inputs = [
56
+ {
57
+ coinId: omnia_1.COINID_ELTOO,
58
+ address: channel.fundingAddress,
59
+ amount: channel.totalValue,
60
+ tokenId,
61
+ },
62
+ ];
63
+ if (params.type === 'splice_in' && params.additionalCoinId && params.additionalAmount) {
64
+ inputs.push({
65
+ coinId: params.additionalCoinId,
66
+ address: params.additionalCoinAddress ?? '',
67
+ amount: params.additionalAmount,
68
+ tokenId,
69
+ });
70
+ }
71
+ const outputs = [
72
+ {
73
+ address: channel.fundingAddress,
74
+ amount: balanceSum,
75
+ tokenId,
76
+ storeState: true,
77
+ stateVarSettlement: false,
78
+ stateVarSequence: 0,
79
+ },
80
+ ];
81
+ if (params.type === 'splice_out' && params.withdrawAmount && params.withdrawAmount > 0n && params.withdrawAddress) {
82
+ outputs.push({
83
+ address: params.withdrawAddress,
84
+ amount: params.withdrawAmount,
85
+ tokenId,
86
+ storeState: false,
87
+ stateVarSettlement: false,
88
+ stateVarSequence: 0,
89
+ });
90
+ }
91
+ for (const extra of params.extraOutputs ?? []) {
92
+ outputs.push({
93
+ address: extra.address,
94
+ amount: extra.amount,
95
+ tokenId: extra.tokenId ?? tokenId,
96
+ storeState: false,
97
+ stateVarSettlement: false,
98
+ stateVarSequence: 0,
99
+ });
100
+ }
101
+ return {
102
+ inputs,
103
+ outputs,
104
+ channelId: channel.channelId,
105
+ params,
106
+ };
107
+ }
108
+ /**
109
+ * Convert a SpliceTxDraft to canonical Minima binary TX bytes.
110
+ *
111
+ * The resulting bytes cover inputs, outputs, and state variables and are
112
+ * suitable for WOTS signing. Both parties sign the same bytes independently;
113
+ * the final splice TX assembles both signatures into the witness.
114
+ */
115
+ function spliceDraftToMinimaBytes(draft) {
116
+ const toHex = (b) => Buffer.from(b).toString('hex');
117
+ const svToJson = (port, value, type) => {
118
+ let data;
119
+ let svtype;
120
+ if (typeof value === 'bigint') {
121
+ data = value.toString();
122
+ svtype = 'number';
123
+ }
124
+ else if (typeof value === 'boolean') {
125
+ data = value ? 'true' : 'false';
126
+ svtype = 'bool';
127
+ }
128
+ else if (value instanceof Uint8Array) {
129
+ data = '0x' + toHex(value);
130
+ svtype = 'hex';
131
+ }
132
+ else if (typeof value === 'number') {
133
+ data = value.toString();
134
+ svtype = 'number';
135
+ }
136
+ else {
137
+ data = String(value);
138
+ svtype = type;
139
+ }
140
+ return { port, svtype, data };
141
+ };
142
+ const inputs = draft.inputs.map(inp => ({
143
+ coinid: inp.coinId,
144
+ amount: inp.amount.toString(),
145
+ address: inp.address,
146
+ tokenid: inp.tokenId,
147
+ storestate: false,
148
+ mmrentry: '0',
149
+ spent: false,
150
+ created: '0',
151
+ state: [],
152
+ }));
153
+ const outputs = draft.outputs.map(out => ({
154
+ amount: out.amount.toString(),
155
+ address: out.address,
156
+ tokenid: out.tokenId,
157
+ storestate: out.storeState ?? false,
158
+ mmrentry: '0',
159
+ spent: false,
160
+ created: '0',
161
+ state: out.storeState
162
+ ? [
163
+ svToJson(STATE_SETTLEMENT_PORT, out.stateVarSettlement, 'bool'),
164
+ svToJson(STATE_SEQUENCE_PORT, out.stateVarSequence, 'number'),
165
+ ]
166
+ : [],
167
+ }));
168
+ const state = [
169
+ svToJson(STATE_SETTLEMENT_PORT, false, 'bool'),
170
+ svToJson(STATE_SEQUENCE_PORT, 0n, 'number'),
171
+ ];
172
+ return (0, core_2.serializeTransaction)(JSON.stringify({ inputs, outputs, state, linkhash: '0x00' }));
173
+ }
174
+ /**
175
+ * Compute a 32-byte digest over the splice TX draft for WOTS signing.
176
+ * This is the canonical message both parties sign to authorize the splice.
177
+ */
178
+ function computeSpliceTxDigest(draft) {
179
+ const canonical = JSON.stringify({
180
+ channelId: draft.channelId,
181
+ inputs: draft.inputs.map(i => ({
182
+ coinId: i.coinId,
183
+ address: i.address,
184
+ amount: i.amount.toString(),
185
+ tokenId: i.tokenId,
186
+ })),
187
+ outputs: draft.outputs.map(o => ({
188
+ address: o.address,
189
+ amount: o.amount.toString(),
190
+ tokenId: o.tokenId,
191
+ storeState: o.storeState,
192
+ stateVarSettlement: o.storeState ? o.stateVarSettlement : undefined,
193
+ stateVarSequence: o.storeState ? o.stateVarSequence : undefined,
194
+ })),
195
+ params: {
196
+ type: draft.params.type,
197
+ newTotalValue: draft.params.newTotalValue.toString(),
198
+ /**
199
+ * newBalances is sorted by partyId for determinism and included in the
200
+ * digest so that signatures cryptographically bind to the exact per-party
201
+ * balance split. Different allocations with the same sum produce different
202
+ * digests and therefore require new signatures.
203
+ */
204
+ newBalances: Object.entries(draft.params.newBalances)
205
+ .sort(([a], [b]) => a.localeCompare(b))
206
+ .map(([k, v]) => [k, v.toString()]),
207
+ },
208
+ });
209
+ return (0, core_1.sha3_256)(new TextEncoder().encode(canonical));
210
+ }
@@ -0,0 +1,95 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { SpliceParams, SpliceProposal, SpliceAcceptance, SpliceLeaseProvider, QuiescedChannel } from './types.js';
3
+ /** A splice proposal whose proposer signature has not been applied yet. */
4
+ export interface UnsignedSpliceProposal {
5
+ spliceId: string;
6
+ channelId: string;
7
+ params: SpliceParams;
8
+ spliceTxHex: string;
9
+ spliceTxDraft: SpliceProposal['spliceTxDraft'];
10
+ proposerPublicKeyDigest: string;
11
+ digest: Uint8Array;
12
+ }
13
+ /**
14
+ * Build the deterministic splice draft/digest without signing. Used by the
15
+ * wallet/coordinator flow: the caller signs `digest` and attaches the
16
+ * signature before finalization.
17
+ */
18
+ export declare function buildSpliceProposal(channel: OmniaChannel | QuiescedChannel, params: SpliceParams, proposerPublicKeyDigest: string): UnsignedSpliceProposal;
19
+ /** Build an unsigned splice-in proposal (see `buildSpliceProposal`). */
20
+ export declare function buildSpliceInProposal(channel: OmniaChannel | QuiescedChannel, additionalCoinId: string, additionalAmount: bigint, proposerPublicKeyDigest: string, newBalances?: Record<string, bigint>): UnsignedSpliceProposal;
21
+ /** Build an unsigned splice-out proposal (see `buildSpliceProposal`). */
22
+ export declare function buildSpliceOutProposal(channel: OmniaChannel | QuiescedChannel, withdrawAmount: bigint, withdrawAddress: string, proposerPublicKeyDigest: string, newBalances?: Record<string, bigint>, extraOutputs?: Array<{
23
+ address: string;
24
+ amount: bigint;
25
+ tokenId?: string;
26
+ }>): UnsignedSpliceProposal;
27
+ /**
28
+ * Initiating party proposes a splice-in: add external funds to the channel.
29
+ *
30
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
31
+ *
32
+ * WOTS lease safety: a key slot is reserved via `leaseProvider.wotsLease`
33
+ * before signing. The returned `proposerReservationId` and
34
+ * `proposerSigningIndices` must be passed through to `finalizeSplice`
35
+ * (embedded in the `SpliceProposal`) so the reservation is committed on
36
+ * success or burned on failure, preventing one-time-key reuse.
37
+ *
38
+ * @param channel - Quiesced channel to splice.
39
+ * @param additionalCoinId - CoinId of the external coin being spliced in.
40
+ * @param additionalAmount - Amount of the additional coin.
41
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
42
+ * @param newBalances - How the new total should be split after splice.
43
+ * When omitted, existing balances are scaled
44
+ * proportionally to the new total value so that
45
+ * `sum(newBalances) === newTotalValue` is preserved.
46
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
47
+ */
48
+ export declare function proposeSpliceIn(channel: OmniaChannel | QuiescedChannel, additionalCoinId: string, additionalAmount: bigint, leaseProvider: SpliceLeaseProvider, newBalances?: Record<string, bigint>): Promise<SpliceProposal>;
49
+ /**
50
+ * Initiating party proposes a splice-out: withdraw funds from the channel on-chain.
51
+ *
52
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
53
+ *
54
+ * WOTS lease safety: reserves a key slot before signing (same semantics as
55
+ * proposeSpliceIn). The `proposerReservationId` in the returned `SpliceProposal`
56
+ * must be committed/burned by `finalizeSplice`.
57
+ *
58
+ * @param channel - Quiesced channel.
59
+ * @param withdrawAmount - Amount to remove from the channel.
60
+ * @param withdrawAddress - On-chain destination for the withdrawn funds.
61
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
62
+ * @param newBalances - How the remaining total should be split after splice.
63
+ * @param extraOutputs - Optional additional on-chain outputs (third-party payments).
64
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
65
+ */
66
+ export declare function proposeSpliceOut(channel: OmniaChannel | QuiescedChannel, withdrawAmount: bigint, withdrawAddress: string, leaseProvider: SpliceLeaseProvider, newBalances?: Record<string, bigint>, extraOutputs?: Array<{
67
+ address: string;
68
+ amount: bigint;
69
+ tokenId?: string;
70
+ }>): Promise<SpliceProposal>;
71
+ /**
72
+ * Counterparty accepts a splice proposal by co-signing the splice TX digest.
73
+ *
74
+ * Requires the channel to be in 'quiesced' state.
75
+ *
76
+ * WOTS lease safety: reserves a key slot before signing. The returned
77
+ * `acceptorReservationId` and `acceptorSigningIndices` are embedded in the
78
+ * `SpliceAcceptance` and consumed by `finalizeSplice` to commit or burn the
79
+ * acceptor's key-slot reservation.
80
+ *
81
+ * The acceptor independently:
82
+ * 1. Validates party membership (proposer and acceptor both in channel).
83
+ * 2. Validates proposal balance conservation and amount constraints.
84
+ * 3. Cryptographically binds the signed draft to the proposal params by
85
+ * recomputing the expected draft from `params + channel` and comparing
86
+ * digests — rejects if they differ (tamper detection).
87
+ * 4. Reserves a WOTS key slot via `leaseProvider.wotsLease`.
88
+ * 5. Signs the splice TX digest with reserved indices.
89
+ *
90
+ * @param channel - Quiesced channel.
91
+ * @param proposal - Splice proposal from the initiating party.
92
+ * @param leaseProvider - Provides the acceptor signer and WOTS lease.
93
+ * @returns SpliceAcceptance containing acceptor co-signature and lease data.
94
+ */
95
+ export declare function acceptSplice(channel: OmniaChannel | QuiescedChannel, proposal: SpliceProposal, leaseProvider: SpliceLeaseProvider): Promise<SpliceAcceptance>;
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSpliceProposal = buildSpliceProposal;
4
+ exports.buildSpliceInProposal = buildSpliceInProposal;
5
+ exports.buildSpliceOutProposal = buildSpliceOutProposal;
6
+ exports.proposeSpliceIn = proposeSpliceIn;
7
+ exports.proposeSpliceOut = proposeSpliceOut;
8
+ exports.acceptSplice = acceptSplice;
9
+ const splice_tx_js_1 = require("./splice-tx.js");
10
+ const errors_js_1 = require("./errors.js");
11
+ /**
12
+ * Scale existing balances proportionally to a new total, preserving relative
13
+ * ratios. The last party absorbs rounding so that sum(result) === newTotal
14
+ * exactly. Used as the default newBalances when a caller omits the argument.
15
+ */
16
+ function scaleBalances(balances, oldTotal, newTotal) {
17
+ if (oldTotal === 0n) {
18
+ const partyIds = Object.keys(balances);
19
+ const each = partyIds.length > 0 ? newTotal / BigInt(partyIds.length) : 0n;
20
+ const result = {};
21
+ let assigned = 0n;
22
+ for (let i = 0; i < partyIds.length - 1; i++) {
23
+ result[partyIds[i]] = each;
24
+ assigned += each;
25
+ }
26
+ const last = partyIds[partyIds.length - 1];
27
+ if (last !== undefined)
28
+ result[last] = newTotal - assigned;
29
+ return result;
30
+ }
31
+ const partyIds = Object.keys(balances);
32
+ const scaled = {};
33
+ let assigned = 0n;
34
+ for (let i = 0; i < partyIds.length - 1; i++) {
35
+ const pid = partyIds[i];
36
+ const prev = balances[pid] ?? 0n;
37
+ scaled[pid] = (prev * newTotal) / oldTotal;
38
+ assigned += scaled[pid];
39
+ }
40
+ const last = partyIds[partyIds.length - 1];
41
+ if (last !== undefined)
42
+ scaled[last] = newTotal - assigned;
43
+ return scaled;
44
+ }
45
+ function generateSpliceId() {
46
+ const buf = new Uint8Array(16);
47
+ crypto.getRandomValues(buf);
48
+ return '0x' + buf.reduce((hex, b) => hex + b.toString(16).padStart(2, '0'), '');
49
+ }
50
+ /**
51
+ * Gate: all splice operations (propose, accept, finalize) require the channel
52
+ * to be in 'quiesced' state. Quiescing ensures all in-flight HTLCs are settled
53
+ * and the pre-splice balance split is mutually signed before any splice TX is built.
54
+ */
55
+ function validateChannelQuiesced(channel) {
56
+ if (channel.status !== 'quiesced') {
57
+ throw new errors_js_1.SpliceChannelStatusError('quiesced', channel.status);
58
+ }
59
+ const pending = channel.pendingHTLCs.filter(h => h.status === 'pending').length;
60
+ if (pending > 0) {
61
+ throw new errors_js_1.PendingHTLCError(pending);
62
+ }
63
+ }
64
+ /**
65
+ * Validate proposal balance conservation and amount constraints.
66
+ * Called by acceptSplice before signing to independently verify inbound params.
67
+ */
68
+ function validateProposalParams(channel, params) {
69
+ const balanceSum = Object.values(params.newBalances).reduce((a, b) => a + b, 0n);
70
+ if (balanceSum !== params.newTotalValue) {
71
+ throw new Error(`Proposal integrity check failed: newBalances sum (${balanceSum}) !== newTotalValue (${params.newTotalValue})`);
72
+ }
73
+ if (params.type === 'splice_out' && (params.withdrawAmount ?? 0n) > channel.totalValue) {
74
+ throw new Error(`Proposal integrity check failed: withdrawAmount (${params.withdrawAmount}) exceeds channel totalValue (${channel.totalValue})`);
75
+ }
76
+ const channelOutput = params.newTotalValue;
77
+ const withdrawSum = params.withdrawAmount ?? 0n;
78
+ const extraSum = (params.extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
79
+ if (params.type === 'splice_in') {
80
+ const expectedExistingInput = channelOutput + withdrawSum + extraSum - (params.additionalAmount ?? 0n);
81
+ if (expectedExistingInput !== channel.totalValue) {
82
+ throw new Error(`Proposal integrity check failed: splice-in amounts inconsistent ` +
83
+ `(expected existing channel input ${channel.totalValue}, derived ${expectedExistingInput})`);
84
+ }
85
+ }
86
+ else {
87
+ if (channelOutput + withdrawSum + extraSum !== channel.totalValue) {
88
+ throw new Error(`Proposal integrity check failed: splice-out amounts do not sum to channel total ` +
89
+ `(${channelOutput} + ${withdrawSum} + ${extraSum} !== ${channel.totalValue})`);
90
+ }
91
+ }
92
+ }
93
+ /**
94
+ * Verify that `spliceTxDraft` is exactly what the params would produce by
95
+ * rebuilding the draft deterministically and comparing digests.
96
+ *
97
+ * Prevents a tampered proposal where params.newBalances is modified but
98
+ * spliceTxDraft is left unchanged (or vice versa), causing channel state
99
+ * to diverge from the actual on-chain TX outputs.
100
+ */
101
+ function bindDraftToParams(channel, proposal) {
102
+ const recomputed = (0, splice_tx_js_1.buildSpliceTx)(channel, proposal.params);
103
+ const expected = (0, splice_tx_js_1.computeSpliceTxDigest)(recomputed);
104
+ const actual = (0, splice_tx_js_1.computeSpliceTxDigest)(proposal.spliceTxDraft);
105
+ if (!expected.every((b, i) => b === actual[i])) {
106
+ throw new Error('Proposal spliceTxDraft is inconsistent with proposal.params — ' +
107
+ 'the TX draft may have been tampered with');
108
+ }
109
+ }
110
+ /**
111
+ * Build the deterministic splice draft/digest without signing. Used by the
112
+ * wallet/coordinator flow: the caller signs `digest` and attaches the
113
+ * signature before finalization.
114
+ */
115
+ function buildSpliceProposal(channel, params, proposerPublicKeyDigest) {
116
+ validateChannelQuiesced(channel);
117
+ validateProposalParams(channel, params);
118
+ const proposerInChannel = channel.parties.find(p => p.publicKeyDigest === proposerPublicKeyDigest);
119
+ if (!proposerInChannel)
120
+ throw new errors_js_1.SpliceMissingPartyError(proposerPublicKeyDigest);
121
+ const draft = (0, splice_tx_js_1.buildSpliceTx)(channel, params);
122
+ return {
123
+ spliceId: generateSpliceId(),
124
+ channelId: channel.channelId,
125
+ params,
126
+ spliceTxHex: Buffer.from((0, splice_tx_js_1.spliceDraftToMinimaBytes)(draft)).toString('hex'),
127
+ spliceTxDraft: draft,
128
+ proposerPublicKeyDigest,
129
+ digest: (0, splice_tx_js_1.computeSpliceTxDigest)(draft),
130
+ };
131
+ }
132
+ /** Build an unsigned splice-in proposal (see `buildSpliceProposal`). */
133
+ function buildSpliceInProposal(channel, additionalCoinId, additionalAmount, proposerPublicKeyDigest, newBalances) {
134
+ validateChannelQuiesced(channel);
135
+ const newTotal = channel.totalValue + additionalAmount;
136
+ const effectiveNewBalances = newBalances ?? scaleBalances(channel.balances, channel.totalValue, newTotal);
137
+ return buildSpliceProposal(channel, {
138
+ type: 'splice_in',
139
+ newTotalValue: newTotal,
140
+ newBalances: effectiveNewBalances,
141
+ additionalCoinId,
142
+ additionalAmount,
143
+ }, proposerPublicKeyDigest);
144
+ }
145
+ /** Build an unsigned splice-out proposal (see `buildSpliceProposal`). */
146
+ function buildSpliceOutProposal(channel, withdrawAmount, withdrawAddress, proposerPublicKeyDigest, newBalances, extraOutputs) {
147
+ validateChannelQuiesced(channel);
148
+ const extraSum = (extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
149
+ const totalOutflow = withdrawAmount + extraSum;
150
+ if (totalOutflow > channel.totalValue) {
151
+ throw new Error(`buildSpliceOutProposal: total outflow (withdraw ${withdrawAmount} + extra outputs ${extraSum} = ${totalOutflow}) ` +
152
+ `exceeds channel totalValue (${channel.totalValue})`);
153
+ }
154
+ const remainingTotal = channel.totalValue - totalOutflow;
155
+ const effectiveNewBalances = newBalances ?? (() => {
156
+ const ratio = channel.totalValue > 0n ? remainingTotal * 1000n / channel.totalValue : 0n;
157
+ const adjusted = {};
158
+ let assigned = 0n;
159
+ const partyIds = Object.keys(channel.balances);
160
+ for (let i = 0; i < partyIds.length - 1; i++) {
161
+ const pid = partyIds[i];
162
+ const prev = channel.balances[pid] ?? 0n;
163
+ const scaled = (prev * ratio) / 1000n;
164
+ adjusted[pid] = scaled;
165
+ assigned += scaled;
166
+ }
167
+ const lastId = partyIds[partyIds.length - 1];
168
+ if (lastId)
169
+ adjusted[lastId] = remainingTotal - assigned;
170
+ return adjusted;
171
+ })();
172
+ return buildSpliceProposal(channel, {
173
+ type: 'splice_out',
174
+ newTotalValue: remainingTotal,
175
+ newBalances: effectiveNewBalances,
176
+ withdrawAmount,
177
+ withdrawAddress,
178
+ extraOutputs,
179
+ }, proposerPublicKeyDigest);
180
+ }
181
+ /**
182
+ * Initiating party proposes a splice-in: add external funds to the channel.
183
+ *
184
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
185
+ *
186
+ * WOTS lease safety: a key slot is reserved via `leaseProvider.wotsLease`
187
+ * before signing. The returned `proposerReservationId` and
188
+ * `proposerSigningIndices` must be passed through to `finalizeSplice`
189
+ * (embedded in the `SpliceProposal`) so the reservation is committed on
190
+ * success or burned on failure, preventing one-time-key reuse.
191
+ *
192
+ * @param channel - Quiesced channel to splice.
193
+ * @param additionalCoinId - CoinId of the external coin being spliced in.
194
+ * @param additionalAmount - Amount of the additional coin.
195
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
196
+ * @param newBalances - How the new total should be split after splice.
197
+ * When omitted, existing balances are scaled
198
+ * proportionally to the new total value so that
199
+ * `sum(newBalances) === newTotalValue` is preserved.
200
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
201
+ */
202
+ async function proposeSpliceIn(channel, additionalCoinId, additionalAmount, leaseProvider, newBalances) {
203
+ validateChannelQuiesced(channel);
204
+ const newTotal = channel.totalValue + additionalAmount;
205
+ const effectiveNewBalances = newBalances ?? scaleBalances(channel.balances, channel.totalValue, newTotal);
206
+ const params = {
207
+ type: 'splice_in',
208
+ newTotalValue: newTotal,
209
+ newBalances: effectiveNewBalances,
210
+ additionalCoinId,
211
+ additionalAmount,
212
+ };
213
+ const draft = (0, splice_tx_js_1.buildSpliceTx)(channel, params);
214
+ const digest = (0, splice_tx_js_1.computeSpliceTxDigest)(draft);
215
+ const spliceTxHex = Buffer.from((0, splice_tx_js_1.spliceDraftToMinimaBytes)(draft)).toString('hex');
216
+ const { signer, wotsLease } = leaseProvider;
217
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
218
+ if (!partyInChannel) {
219
+ throw new errors_js_1.SpliceMissingPartyError(signer.publicKeyDigest);
220
+ }
221
+ const reservation = await wotsLease.reserveKeyUse({
222
+ treeId: signer.publicKeyDigest,
223
+ purpose: 'omnia-splice-propose',
224
+ payloadHash: Buffer.from(digest).toString('hex'),
225
+ });
226
+ const signature = await signer.sign(digest, reservation.indices);
227
+ return {
228
+ spliceId: generateSpliceId(),
229
+ channelId: channel.channelId,
230
+ params,
231
+ spliceTxHex,
232
+ spliceTxDraft: draft,
233
+ proposerPublicKeyDigest: signer.publicKeyDigest,
234
+ proposerSignature: signature,
235
+ proposerReservationId: reservation.reservationId,
236
+ proposerSigningIndices: reservation.indices,
237
+ proposedAt: Date.now(),
238
+ };
239
+ }
240
+ /**
241
+ * Initiating party proposes a splice-out: withdraw funds from the channel on-chain.
242
+ *
243
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
244
+ *
245
+ * WOTS lease safety: reserves a key slot before signing (same semantics as
246
+ * proposeSpliceIn). The `proposerReservationId` in the returned `SpliceProposal`
247
+ * must be committed/burned by `finalizeSplice`.
248
+ *
249
+ * @param channel - Quiesced channel.
250
+ * @param withdrawAmount - Amount to remove from the channel.
251
+ * @param withdrawAddress - On-chain destination for the withdrawn funds.
252
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
253
+ * @param newBalances - How the remaining total should be split after splice.
254
+ * @param extraOutputs - Optional additional on-chain outputs (third-party payments).
255
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
256
+ */
257
+ async function proposeSpliceOut(channel, withdrawAmount, withdrawAddress, leaseProvider, newBalances, extraOutputs) {
258
+ validateChannelQuiesced(channel);
259
+ const extraSum = (extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
260
+ const totalOutflow = withdrawAmount + extraSum;
261
+ if (totalOutflow > channel.totalValue) {
262
+ throw new Error(`proposeSpliceOut: total outflow (withdraw ${withdrawAmount} + extra outputs ${extraSum} = ${totalOutflow}) ` +
263
+ `exceeds channel totalValue (${channel.totalValue})`);
264
+ }
265
+ const remainingTotal = channel.totalValue - totalOutflow;
266
+ const effectiveNewBalances = newBalances ?? (() => {
267
+ const ratio = channel.totalValue > 0n ? remainingTotal * 1000n / channel.totalValue : 0n;
268
+ const adjusted = {};
269
+ let assigned = 0n;
270
+ const partyIds = Object.keys(channel.balances);
271
+ for (let i = 0; i < partyIds.length - 1; i++) {
272
+ const pid = partyIds[i];
273
+ const prev = channel.balances[pid] ?? 0n;
274
+ const scaled = (prev * ratio) / 1000n;
275
+ adjusted[pid] = scaled;
276
+ assigned += scaled;
277
+ }
278
+ const lastId = partyIds[partyIds.length - 1];
279
+ if (lastId)
280
+ adjusted[lastId] = remainingTotal - assigned;
281
+ return adjusted;
282
+ })();
283
+ const params = {
284
+ type: 'splice_out',
285
+ newTotalValue: remainingTotal,
286
+ newBalances: effectiveNewBalances,
287
+ withdrawAmount,
288
+ withdrawAddress,
289
+ extraOutputs,
290
+ };
291
+ const draft = (0, splice_tx_js_1.buildSpliceTx)(channel, params);
292
+ const digest = (0, splice_tx_js_1.computeSpliceTxDigest)(draft);
293
+ const spliceTxHex = Buffer.from((0, splice_tx_js_1.spliceDraftToMinimaBytes)(draft)).toString('hex');
294
+ const { signer, wotsLease } = leaseProvider;
295
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
296
+ if (!partyInChannel) {
297
+ throw new errors_js_1.SpliceMissingPartyError(signer.publicKeyDigest);
298
+ }
299
+ const reservation = await wotsLease.reserveKeyUse({
300
+ treeId: signer.publicKeyDigest,
301
+ purpose: 'omnia-splice-propose',
302
+ payloadHash: Buffer.from(digest).toString('hex'),
303
+ });
304
+ const signature = await signer.sign(digest, reservation.indices);
305
+ return {
306
+ spliceId: generateSpliceId(),
307
+ channelId: channel.channelId,
308
+ params,
309
+ spliceTxHex,
310
+ spliceTxDraft: draft,
311
+ proposerPublicKeyDigest: signer.publicKeyDigest,
312
+ proposerSignature: signature,
313
+ proposerReservationId: reservation.reservationId,
314
+ proposerSigningIndices: reservation.indices,
315
+ proposedAt: Date.now(),
316
+ };
317
+ }
318
+ /**
319
+ * Counterparty accepts a splice proposal by co-signing the splice TX digest.
320
+ *
321
+ * Requires the channel to be in 'quiesced' state.
322
+ *
323
+ * WOTS lease safety: reserves a key slot before signing. The returned
324
+ * `acceptorReservationId` and `acceptorSigningIndices` are embedded in the
325
+ * `SpliceAcceptance` and consumed by `finalizeSplice` to commit or burn the
326
+ * acceptor's key-slot reservation.
327
+ *
328
+ * The acceptor independently:
329
+ * 1. Validates party membership (proposer and acceptor both in channel).
330
+ * 2. Validates proposal balance conservation and amount constraints.
331
+ * 3. Cryptographically binds the signed draft to the proposal params by
332
+ * recomputing the expected draft from `params + channel` and comparing
333
+ * digests — rejects if they differ (tamper detection).
334
+ * 4. Reserves a WOTS key slot via `leaseProvider.wotsLease`.
335
+ * 5. Signs the splice TX digest with reserved indices.
336
+ *
337
+ * @param channel - Quiesced channel.
338
+ * @param proposal - Splice proposal from the initiating party.
339
+ * @param leaseProvider - Provides the acceptor signer and WOTS lease.
340
+ * @returns SpliceAcceptance containing acceptor co-signature and lease data.
341
+ */
342
+ async function acceptSplice(channel, proposal, leaseProvider) {
343
+ validateChannelQuiesced(channel);
344
+ if (proposal.channelId !== channel.channelId) {
345
+ throw new Error(`Proposal channelId '${proposal.channelId}' does not match channel '${channel.channelId}'`);
346
+ }
347
+ const proposerInChannel = channel.parties.find(p => p.publicKeyDigest === proposal.proposerPublicKeyDigest);
348
+ if (!proposerInChannel) {
349
+ throw new errors_js_1.SpliceMissingPartyError(proposal.proposerPublicKeyDigest);
350
+ }
351
+ const { signer, wotsLease } = leaseProvider;
352
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
353
+ if (!partyInChannel) {
354
+ throw new errors_js_1.SpliceMissingPartyError(signer.publicKeyDigest);
355
+ }
356
+ if (signer.publicKeyDigest === proposal.proposerPublicKeyDigest) {
357
+ throw new Error('Acceptor and proposer cannot be the same party');
358
+ }
359
+ validateProposalParams(channel, proposal.params);
360
+ bindDraftToParams(channel, proposal);
361
+ const digest = (0, splice_tx_js_1.computeSpliceTxDigest)(proposal.spliceTxDraft);
362
+ const reservation = await wotsLease.reserveKeyUse({
363
+ treeId: signer.publicKeyDigest,
364
+ purpose: 'omnia-splice-accept',
365
+ payloadHash: Buffer.from(digest).toString('hex'),
366
+ });
367
+ const signature = await signer.sign(digest, reservation.indices);
368
+ return {
369
+ spliceId: proposal.spliceId,
370
+ channelId: channel.channelId,
371
+ acceptorPublicKeyDigest: signer.publicKeyDigest,
372
+ acceptorSignature: signature,
373
+ acceptorReservationId: reservation.reservationId,
374
+ acceptorSigningIndices: reservation.indices,
375
+ acceptedAt: Date.now(),
376
+ };
377
+ }