@totemsdk/omnia-splice 0.1.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.
@@ -0,0 +1,22 @@
1
+ export declare class SpliceError extends Error {
2
+ readonly code: string;
3
+ constructor(code: string, message: string);
4
+ }
5
+ export declare class PendingHTLCError extends SpliceError {
6
+ constructor(pendingCount: number);
7
+ }
8
+ export declare class SpliceChannelStatusError extends SpliceError {
9
+ constructor(required: string, actual: string);
10
+ }
11
+ export declare class SpliceBalanceConservationError extends SpliceError {
12
+ constructor(expected: bigint, actual: bigint);
13
+ }
14
+ export declare class SpliceSignatureMismatchError extends SpliceError {
15
+ constructor(detail: string);
16
+ }
17
+ export declare class SpliceMissingPartyError extends SpliceError {
18
+ constructor(partyId: string);
19
+ }
20
+ export declare class SpliceInsufficientFundsError extends SpliceError {
21
+ constructor(available: bigint, requested: bigint);
22
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,44 @@
1
+ export class SpliceError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.name = 'SpliceError';
5
+ this.code = code;
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ }
9
+ export class PendingHTLCError extends SpliceError {
10
+ constructor(pendingCount) {
11
+ super('PENDING_HTLC', `Cannot splice: ${pendingCount} HTLC(s) still pending. Fulfill or timeout all HTLCs before splicing.`);
12
+ this.name = 'PendingHTLCError';
13
+ }
14
+ }
15
+ export class SpliceChannelStatusError extends SpliceError {
16
+ constructor(required, actual) {
17
+ super('INVALID_CHANNEL_STATUS', `Splice requires channel status '${required}', got '${actual}'.`);
18
+ this.name = 'SpliceChannelStatusError';
19
+ }
20
+ }
21
+ export class SpliceBalanceConservationError extends SpliceError {
22
+ constructor(expected, actual) {
23
+ super('BALANCE_CONSERVATION', `Splice balance conservation failed: expected ${expected}, got ${actual}.`);
24
+ this.name = 'SpliceBalanceConservationError';
25
+ }
26
+ }
27
+ export class SpliceSignatureMismatchError extends SpliceError {
28
+ constructor(detail) {
29
+ super('SIGNATURE_MISMATCH', `Splice signature mismatch: ${detail}`);
30
+ this.name = 'SpliceSignatureMismatchError';
31
+ }
32
+ }
33
+ export class SpliceMissingPartyError extends SpliceError {
34
+ constructor(partyId) {
35
+ super('MISSING_PARTY', `Party '${partyId}' not found in channel.`);
36
+ this.name = 'SpliceMissingPartyError';
37
+ }
38
+ }
39
+ export class SpliceInsufficientFundsError extends SpliceError {
40
+ constructor(available, requested) {
41
+ super('INSUFFICIENT_FUNDS', `Splice-out withdraws ${requested} but channel only holds ${available}.`);
42
+ this.name = 'SpliceInsufficientFundsError';
43
+ }
44
+ }
@@ -0,0 +1,92 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { WotsLeaseProvider } from '@totemsdk/wots-lease';
3
+ import type { SpliceProposal, SpliceAcceptance, SplicedChannel, QuiescedChannel } from './types.js';
4
+ /**
5
+ * Options for `finalizeSplice`.
6
+ *
7
+ * @property broadcast - Broadcast the mined TxPoW hex to the network.
8
+ * `finalizeSplice` throws if `broadcast` returns
9
+ * `{ success: false }` without a `txpowid`.
10
+ * @property mineDifficulty - Override PoW difficulty (pass `MAX_HASH` in tests).
11
+ * @property verifySignature - Custom signature verifier called for both the
12
+ * proposer and acceptor signatures before state
13
+ * transition. Defaults to `wotsVerifyDigest`.
14
+ * **Override in test environments** that use mock
15
+ * signers (mock signatures are not real WOTS sigs
16
+ * and will not pass the default verifier).
17
+ *
18
+ * ```ts
19
+ * // Example test helper:
20
+ * verifySignature: (sig, digest, pkd) => {
21
+ * const expected = sha3_256(concatBytes(fromHex(pkd), digest));
22
+ * return expected.length === sig.length
23
+ * && expected.every((b, i) => b === sig[i]);
24
+ * }
25
+ * ```
26
+ *
27
+ * @property proposerLeaseProvider - Proposer's WOTS lease provider. If supplied,
28
+ * `finalizeSplice` will call `commitKeyUse` on the
29
+ * proposer's reservation after a confirmed splice TX,
30
+ * or `burnReservation` if finalization fails after
31
+ * security checks pass. Prevents one-time-key reuse.
32
+ *
33
+ * @property acceptorLeaseProvider - Acceptor's WOTS lease provider. Same commit/burn
34
+ * semantics as `proposerLeaseProvider`.
35
+ */
36
+ export interface FinalizeSpliceOptions {
37
+ broadcast?: (txHex: string) => Promise<{
38
+ txpowid?: string;
39
+ success?: boolean;
40
+ }>;
41
+ mineDifficulty?: Uint8Array;
42
+ verifySignature?: (signature: Uint8Array, digest: Uint8Array, publicKeyDigest: string) => boolean;
43
+ proposerLeaseProvider?: WotsLeaseProvider;
44
+ acceptorLeaseProvider?: WotsLeaseProvider;
45
+ }
46
+ /**
47
+ * Finalize a splice by assembling both parties' signatures, mining PoW,
48
+ * optionally broadcasting the TX, and returning the new active channel.
49
+ *
50
+ * **Quiesce gate**: the channel must be in `'quiesced'` state. Call
51
+ * `quiesceChannel` first to settle all HTLCs and sign the pre-splice state.
52
+ *
53
+ * **Security checks** (all verified before mining):
54
+ * 1. `channel.status === 'quiesced'`
55
+ * 2. `proposal.spliceId === acceptance.spliceId`
56
+ * 3. `proposal.channelId` and `acceptance.channelId` match `channel.channelId`
57
+ * 4. Proposer and acceptor are distinct, non-empty-keyed channel parties
58
+ * 5. Both signatures are non-empty byte arrays
59
+ * 6. Both signatures pass cryptographic verification against the splice TX
60
+ * digest (WOTS by default; override with `options.verifySignature` in tests)
61
+ * 7. `spliceTxDraft` digest matches what `buildSpliceTx(channel, params)` produces
62
+ *
63
+ * **WOTS lease lifecycle**:
64
+ * - If `options.proposerLeaseProvider` is supplied: `commitKeyUse` is called
65
+ * after a confirmed splice TX, or `burnReservation` on failure.
66
+ * - Same for `options.acceptorLeaseProvider`.
67
+ * - Reservations are tracked independently; only uncommitted ones are burned.
68
+ *
69
+ * **Broadcast failure**: if `broadcast()` returns `{ success: false }` without
70
+ * a `txpowid`, `finalizeSplice` throws and burns any open reservations.
71
+ *
72
+ * **Side effect**: the `channel` object passed in is mutated to
73
+ * `status: 'spliced'` after a successful finalize. This marks the old
74
+ * quiesced channel as invalid; only the returned `SplicedChannel` is live.
75
+ *
76
+ * **Returned SplicedChannel**:
77
+ * - `status: 'active'` — ready for new payments immediately
78
+ * - `totalValue` — updated to `proposal.params.newTotalValue`
79
+ * - `balances` — updated to `proposal.params.newBalances`
80
+ * - `currentSequence: 0` — fresh WOTS budget
81
+ * - `latestState: null` — no cosigned state yet
82
+ * - `splicedFrom` — old channel's `channelId`
83
+ * - `spliceFundingTxId` — mined (or broadcast) TX ID
84
+ * - `spliceFundingCoinId` — `<txId>-0`
85
+ *
86
+ * @param channel - Quiesced channel (mutated to 'spliced' on success).
87
+ * @param proposal - Splice proposal from the initiating party.
88
+ * @param acceptance - Co-signature from the accepting party.
89
+ * @param options - Broadcast, difficulty, verifier, and lease providers.
90
+ * @returns SplicedChannel (`status: 'active'`) with updated value and provenance.
91
+ */
92
+ export declare function finalizeSplice(channel: OmniaChannel | QuiescedChannel, proposal: SpliceProposal, acceptance: SpliceAcceptance, options?: FinalizeSpliceOptions): Promise<SplicedChannel>;
@@ -0,0 +1,224 @@
1
+ import { wotsVerifyDigest, fromHex } from '@totemsdk/core';
2
+ import { serializeTxBody, mineTxPoW, TX_POW_MIN_DIFFICULTY } from '@totemsdk/txpow';
3
+ import { concatBytes } from '@totemsdk/core';
4
+ import { buildSpliceTx, computeSpliceTxDigest, spliceDraftToMinimaBytes } from './splice-tx.js';
5
+ import { SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceChannelStatusError, } from './errors.js';
6
+ function defaultWotsVerify(sig, digest, pkd) {
7
+ try {
8
+ return wotsVerifyDigest(sig, digest, fromHex(pkd));
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+ function assembleSpliceWitness(sig1, sig2) {
15
+ const encodeMiniNumber = (n) => {
16
+ const buf = new Uint8Array(4);
17
+ new DataView(buf.buffer).setInt32(0, n, false);
18
+ return buf;
19
+ };
20
+ const encodeVarBytes = (b) => {
21
+ const lenBuf = new Uint8Array(4);
22
+ new DataView(lenBuf.buffer).setInt32(0, b.length, false);
23
+ return concatBytes(lenBuf, b);
24
+ };
25
+ return concatBytes(encodeMiniNumber(2), encodeVarBytes(sig1), encodeVarBytes(sig2), encodeMiniNumber(0), encodeMiniNumber(0));
26
+ }
27
+ /**
28
+ * Structural authorization checks: both parties must be distinct channel
29
+ * members and both signatures must be non-empty Uint8Arrays.
30
+ * Cryptographic WOTS verification is performed separately by
31
+ * `verifySpliceSignatures`.
32
+ */
33
+ function validateSpliceAuthorization(channel, proposal, acceptance) {
34
+ const proposerParty = channel.parties.find(p => p.publicKeyDigest === proposal.proposerPublicKeyDigest);
35
+ if (!proposerParty)
36
+ throw new SpliceMissingPartyError(proposal.proposerPublicKeyDigest);
37
+ const acceptorParty = channel.parties.find(p => p.publicKeyDigest === acceptance.acceptorPublicKeyDigest);
38
+ if (!acceptorParty)
39
+ throw new SpliceMissingPartyError(acceptance.acceptorPublicKeyDigest);
40
+ if (proposal.proposerPublicKeyDigest === acceptance.acceptorPublicKeyDigest) {
41
+ throw new Error('Proposer and acceptor must be different channel parties');
42
+ }
43
+ if (!proposal.proposerSignature || proposal.proposerSignature.length === 0) {
44
+ throw new SpliceSignatureMismatchError('Proposer signature is empty');
45
+ }
46
+ if (!acceptance.acceptorSignature || acceptance.acceptorSignature.length === 0) {
47
+ throw new SpliceSignatureMismatchError('Acceptor signature is empty');
48
+ }
49
+ }
50
+ /**
51
+ * Cryptographically verify both parties' signatures against the splice TX
52
+ * digest. Called after structural checks; fails closed — throws on any
53
+ * invalid signature.
54
+ *
55
+ * The digest covers the full canonical TX structure AND `newBalances` (sorted
56
+ * by partyId), so signatures are bound to the exact per-party balance split.
57
+ */
58
+ function verifySpliceSignatures(proposal, acceptance, verifier) {
59
+ const digest = computeSpliceTxDigest(proposal.spliceTxDraft);
60
+ if (!verifier(proposal.proposerSignature, digest, proposal.proposerPublicKeyDigest)) {
61
+ throw new SpliceSignatureMismatchError('Proposer signature failed cryptographic verification — digest or key mismatch');
62
+ }
63
+ if (!verifier(acceptance.acceptorSignature, digest, acceptance.acceptorPublicKeyDigest)) {
64
+ throw new SpliceSignatureMismatchError('Acceptor signature failed cryptographic verification — digest or key mismatch');
65
+ }
66
+ }
67
+ /**
68
+ * Cryptographically bind the proposal's spliceTxDraft to its params by
69
+ * recomputing the draft deterministically and comparing digests.
70
+ *
71
+ * Prevents state divergence: finalizeSplice uses spliceTxDraft for the
72
+ * on-chain TX but applies channel state changes from params. If they are
73
+ * inconsistent, the new channel state would not match what was actually mined.
74
+ */
75
+ function bindFinalizeParamsToDraft(channel, proposal) {
76
+ const recomputed = buildSpliceTx(channel, proposal.params);
77
+ const expected = computeSpliceTxDigest(recomputed);
78
+ const actual = computeSpliceTxDigest(proposal.spliceTxDraft);
79
+ if (!expected.every((b, i) => b === actual[i])) {
80
+ throw new Error('finalizeSplice: proposal.spliceTxDraft is inconsistent with proposal.params — ' +
81
+ 'rejecting to prevent on-chain/off-chain state divergence');
82
+ }
83
+ }
84
+ /**
85
+ * Finalize a splice by assembling both parties' signatures, mining PoW,
86
+ * optionally broadcasting the TX, and returning the new active channel.
87
+ *
88
+ * **Quiesce gate**: the channel must be in `'quiesced'` state. Call
89
+ * `quiesceChannel` first to settle all HTLCs and sign the pre-splice state.
90
+ *
91
+ * **Security checks** (all verified before mining):
92
+ * 1. `channel.status === 'quiesced'`
93
+ * 2. `proposal.spliceId === acceptance.spliceId`
94
+ * 3. `proposal.channelId` and `acceptance.channelId` match `channel.channelId`
95
+ * 4. Proposer and acceptor are distinct, non-empty-keyed channel parties
96
+ * 5. Both signatures are non-empty byte arrays
97
+ * 6. Both signatures pass cryptographic verification against the splice TX
98
+ * digest (WOTS by default; override with `options.verifySignature` in tests)
99
+ * 7. `spliceTxDraft` digest matches what `buildSpliceTx(channel, params)` produces
100
+ *
101
+ * **WOTS lease lifecycle**:
102
+ * - If `options.proposerLeaseProvider` is supplied: `commitKeyUse` is called
103
+ * after a confirmed splice TX, or `burnReservation` on failure.
104
+ * - Same for `options.acceptorLeaseProvider`.
105
+ * - Reservations are tracked independently; only uncommitted ones are burned.
106
+ *
107
+ * **Broadcast failure**: if `broadcast()` returns `{ success: false }` without
108
+ * a `txpowid`, `finalizeSplice` throws and burns any open reservations.
109
+ *
110
+ * **Side effect**: the `channel` object passed in is mutated to
111
+ * `status: 'spliced'` after a successful finalize. This marks the old
112
+ * quiesced channel as invalid; only the returned `SplicedChannel` is live.
113
+ *
114
+ * **Returned SplicedChannel**:
115
+ * - `status: 'active'` — ready for new payments immediately
116
+ * - `totalValue` — updated to `proposal.params.newTotalValue`
117
+ * - `balances` — updated to `proposal.params.newBalances`
118
+ * - `currentSequence: 0` — fresh WOTS budget
119
+ * - `latestState: null` — no cosigned state yet
120
+ * - `splicedFrom` — old channel's `channelId`
121
+ * - `spliceFundingTxId` — mined (or broadcast) TX ID
122
+ * - `spliceFundingCoinId` — `<txId>-0`
123
+ *
124
+ * @param channel - Quiesced channel (mutated to 'spliced' on success).
125
+ * @param proposal - Splice proposal from the initiating party.
126
+ * @param acceptance - Co-signature from the accepting party.
127
+ * @param options - Broadcast, difficulty, verifier, and lease providers.
128
+ * @returns SplicedChannel (`status: 'active'`) with updated value and provenance.
129
+ */
130
+ export async function finalizeSplice(channel, proposal, acceptance, options) {
131
+ if (channel.status !== 'quiesced') {
132
+ throw new SpliceChannelStatusError('quiesced', channel.status);
133
+ }
134
+ if (proposal.spliceId !== acceptance.spliceId) {
135
+ throw new SpliceSignatureMismatchError(`proposal spliceId '${proposal.spliceId}' !== acceptance spliceId '${acceptance.spliceId}'`);
136
+ }
137
+ if (proposal.channelId !== channel.channelId) {
138
+ throw new Error(`proposal.channelId '${proposal.channelId}' does not match channel '${channel.channelId}'`);
139
+ }
140
+ if (acceptance.channelId !== channel.channelId) {
141
+ throw new Error(`acceptance.channelId '${acceptance.channelId}' does not match channel '${channel.channelId}'`);
142
+ }
143
+ validateSpliceAuthorization(channel, proposal, acceptance);
144
+ const verifier = options?.verifySignature ?? defaultWotsVerify;
145
+ verifySpliceSignatures(proposal, acceptance, verifier);
146
+ bindFinalizeParamsToDraft(channel, proposal);
147
+ const proposerLease = options?.proposerLeaseProvider;
148
+ const acceptorLease = options?.acceptorLeaseProvider;
149
+ // Track which reservations have been committed so we know which to burn on failure.
150
+ const committed = new Set();
151
+ const txBytes = spliceDraftToMinimaBytes(proposal.spliceTxDraft);
152
+ const witnessBytes = assembleSpliceWitness(proposal.proposerSignature, acceptance.acceptorSignature);
153
+ let spliceFundingTxId;
154
+ try {
155
+ const difficulty = options?.mineDifficulty ?? TX_POW_MIN_DIFFICULTY;
156
+ const txBody = serializeTxBody(txBytes, witnessBytes);
157
+ const mined = await mineTxPoW(txBody, difficulty);
158
+ const fullTxPoW = concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01]), txBody);
159
+ const txHex = Buffer.from(fullTxPoW).toString('hex');
160
+ spliceFundingTxId = Buffer.from(mined.txpowId).toString('hex');
161
+ if (options?.broadcast) {
162
+ const result = await options.broadcast(txHex);
163
+ if (result.txpowid) {
164
+ spliceFundingTxId = result.txpowid;
165
+ }
166
+ else if (result.success === false) {
167
+ throw new Error('Splice TX broadcast rejected by the network — channel state not advanced');
168
+ }
169
+ }
170
+ // Commit leases on confirmed splice TX
171
+ if (proposerLease) {
172
+ await proposerLease.commitKeyUse(proposal.proposerReservationId, spliceFundingTxId);
173
+ committed.add(proposal.proposerReservationId);
174
+ }
175
+ if (acceptorLease) {
176
+ await acceptorLease.commitKeyUse(acceptance.acceptorReservationId, spliceFundingTxId);
177
+ committed.add(acceptance.acceptorReservationId);
178
+ }
179
+ }
180
+ catch (err) {
181
+ // Burn any reservations that were not yet committed (fail-close lease accounting)
182
+ await Promise.allSettled([
183
+ proposerLease && !committed.has(proposal.proposerReservationId)
184
+ ? proposerLease.burnReservation(proposal.proposerReservationId, 'finalize-failed')
185
+ : undefined,
186
+ acceptorLease && !committed.has(acceptance.acceptorReservationId)
187
+ ? acceptorLease.burnReservation(acceptance.acceptorReservationId, 'finalize-failed')
188
+ : undefined,
189
+ ].filter((x) => x !== undefined));
190
+ throw err;
191
+ }
192
+ const spliceFundingCoinId = `${spliceFundingTxId}-0`;
193
+ const params = proposal.params;
194
+ const splicedChannel = {
195
+ ...channel,
196
+ status: 'active',
197
+ splicedFrom: channel.channelId,
198
+ spliceType: params.type,
199
+ spliceFundingTxId,
200
+ spliceFundingCoinId,
201
+ fundingTxId: spliceFundingTxId,
202
+ fundingCoinId: spliceFundingCoinId,
203
+ totalValue: params.newTotalValue,
204
+ balances: params.newBalances,
205
+ currentSequence: 0,
206
+ latestState: null,
207
+ pendingHTLCs: [],
208
+ stateLog: [
209
+ ...channel.stateLog,
210
+ {
211
+ sequence: 0,
212
+ timestamp: Date.now(),
213
+ balances: { ...params.newBalances },
214
+ htlcCount: 0,
215
+ event: 'update',
216
+ },
217
+ ],
218
+ updatedAt: Date.now(),
219
+ };
220
+ // Mark the old (quiesced) channel as spliced — it is now invalidated.
221
+ // Any further operations on `channel` should be rejected by status checks.
222
+ channel.status = 'spliced';
223
+ return splicedChannel;
224
+ }
@@ -0,0 +1,6 @@
1
+ export { quiesceChannel, type QuiesceOptions } from './quiesce.js';
2
+ export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
3
+ export { proposeSpliceIn, proposeSpliceOut, acceptSplice } from './splice.js';
4
+ export { finalizeSplice, type FinalizeSpliceOptions } from './finalize.js';
5
+ export type { SpliceType, SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput, SpliceProposal, SpliceAcceptance, QuiescedChannel, SplicedChannel, SpliceLeaseProvider, SpliceSigningIndices, WotsSignature, } from './types.js';
6
+ export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { quiesceChannel } from './quiesce.js';
2
+ export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
3
+ export { proposeSpliceIn, proposeSpliceOut, acceptSplice } from './splice.js';
4
+ export { finalizeSplice } from './finalize.js';
5
+ export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
@@ -0,0 +1,57 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { QuiescedChannel, SpliceLeaseProvider } from './types.js';
3
+ /**
4
+ * Options for `quiesceChannel`.
5
+ */
6
+ export interface QuiesceOptions {
7
+ /**
8
+ * Called when the channel has pending HTLCs that have not yet reached a
9
+ * terminal state (`fulfilled` or `timed_out`). If provided, `quiesceChannel`
10
+ * invokes this callback with the still-pending HTLCs, giving the caller an
11
+ * opportunity to drive resolution — e.g. submit preimage reveals, wait for
12
+ * timeout blocks, or poll a Minima node — before the quiesce is retried.
13
+ *
14
+ * After the callback resolves, `channel.pendingHTLCs` is re-inspected. If
15
+ * all HTLCs have moved to a terminal state the quiesce proceeds; if any are
16
+ * still pending, `PendingHTLCError` is thrown.
17
+ *
18
+ * If this option is not provided, `PendingHTLCError` is thrown immediately
19
+ * when pending HTLCs are found.
20
+ *
21
+ * @param pending - The HTLCs that still need resolution.
22
+ */
23
+ awaitResolution?: (pending: OmniaChannel['pendingHTLCs']) => Promise<void>;
24
+ }
25
+ /**
26
+ * Quiesce a channel before splicing.
27
+ *
28
+ * Quiescing is mandatory before a splice can be proposed or accepted. It:
29
+ * 1. Validates the channel is `'active'`.
30
+ * 2. Ensures all in-flight HTLCs have reached a terminal state
31
+ * (`fulfilled` or `timed_out`). If pending HTLCs exist and
32
+ * `options.awaitResolution` is provided, the callback is invoked so the
33
+ * caller can drive/await resolution (submit preimages, wait for timeouts,
34
+ * poll a node). After the callback the channel is re-checked. If HTLCs
35
+ * remain pending, `PendingHTLCError` is thrown. If the option is absent
36
+ * and pending HTLCs exist, `PendingHTLCError` is thrown immediately.
37
+ * 3. Signs a final state update (via `updateState`) that captures the settled
38
+ * balance split at `currentSequence + 1`. This produces a WOTS-signed
39
+ * `Partial<SignedChannelState>` binding both parties to the pre-splice
40
+ * balance before the splice TX resets the sequence to 0.
41
+ * 4. Returns a `QuiescedChannel` with `status: 'quiesced'`, `pendingHTLCs: []`
42
+ * (all resolved HTLCs cleared), and `quiesceSignedState` containing the
43
+ * local party's partial signature over the final balance state.
44
+ *
45
+ * The caller must exchange `quiesceSignedState` with the counterparty to obtain
46
+ * their co-signature, providing a fully signed record of the last pre-splice
47
+ * balance for any future dispute resolution.
48
+ *
49
+ * @param channel - The active channel to quiesce.
50
+ * @param leaseProvider - Provides the local party's signer and WOTS lease.
51
+ * @param options - Optional: `awaitResolution` callback for HTLC settlement.
52
+ * @returns A QuiescedChannel with `status: 'quiesced'`, cleared `pendingHTLCs`,
53
+ * and the local party's partial signature over the final balance state.
54
+ * @throws {SpliceChannelStatusError} If channel is not active.
55
+ * @throws {PendingHTLCError} If HTLCs remain pending after resolution.
56
+ */
57
+ export declare function quiesceChannel(channel: OmniaChannel, leaseProvider: SpliceLeaseProvider, options?: QuiesceOptions): Promise<QuiescedChannel>;
@@ -0,0 +1,64 @@
1
+ import { updateState } from '@totemsdk/omnia';
2
+ import { PendingHTLCError, SpliceChannelStatusError } from './errors.js';
3
+ /**
4
+ * Quiesce a channel before splicing.
5
+ *
6
+ * Quiescing is mandatory before a splice can be proposed or accepted. It:
7
+ * 1. Validates the channel is `'active'`.
8
+ * 2. Ensures all in-flight HTLCs have reached a terminal state
9
+ * (`fulfilled` or `timed_out`). If pending HTLCs exist and
10
+ * `options.awaitResolution` is provided, the callback is invoked so the
11
+ * caller can drive/await resolution (submit preimages, wait for timeouts,
12
+ * poll a node). After the callback the channel is re-checked. If HTLCs
13
+ * remain pending, `PendingHTLCError` is thrown. If the option is absent
14
+ * and pending HTLCs exist, `PendingHTLCError` is thrown immediately.
15
+ * 3. Signs a final state update (via `updateState`) that captures the settled
16
+ * balance split at `currentSequence + 1`. This produces a WOTS-signed
17
+ * `Partial<SignedChannelState>` binding both parties to the pre-splice
18
+ * balance before the splice TX resets the sequence to 0.
19
+ * 4. Returns a `QuiescedChannel` with `status: 'quiesced'`, `pendingHTLCs: []`
20
+ * (all resolved HTLCs cleared), and `quiesceSignedState` containing the
21
+ * local party's partial signature over the final balance state.
22
+ *
23
+ * The caller must exchange `quiesceSignedState` with the counterparty to obtain
24
+ * their co-signature, providing a fully signed record of the last pre-splice
25
+ * balance for any future dispute resolution.
26
+ *
27
+ * @param channel - The active channel to quiesce.
28
+ * @param leaseProvider - Provides the local party's signer and WOTS lease.
29
+ * @param options - Optional: `awaitResolution` callback for HTLC settlement.
30
+ * @returns A QuiescedChannel with `status: 'quiesced'`, cleared `pendingHTLCs`,
31
+ * and the local party's partial signature over the final balance state.
32
+ * @throws {SpliceChannelStatusError} If channel is not active.
33
+ * @throws {PendingHTLCError} If HTLCs remain pending after resolution.
34
+ */
35
+ export async function quiesceChannel(channel, leaseProvider, options) {
36
+ if (channel.status !== 'active') {
37
+ throw new SpliceChannelStatusError('active', channel.status);
38
+ }
39
+ const pendingHTLCs = channel.pendingHTLCs.filter(h => h.status === 'pending');
40
+ if (pendingHTLCs.length > 0) {
41
+ if (options?.awaitResolution) {
42
+ await options.awaitResolution(pendingHTLCs);
43
+ const stillPending = channel.pendingHTLCs.filter(h => h.status === 'pending').length;
44
+ if (stillPending > 0) {
45
+ throw new PendingHTLCError(stillPending);
46
+ }
47
+ }
48
+ else {
49
+ throw new PendingHTLCError(pendingHTLCs.length);
50
+ }
51
+ }
52
+ const { channel: updatedChannel, signedState, error } = await updateState(channel, { newBalances: channel.balances }, leaseProvider.wotsLease, leaseProvider.signer);
53
+ if (error) {
54
+ throw new Error(`quiesceChannel: updateState blocked — ${error}. Splice cannot proceed.`);
55
+ }
56
+ const quiesced = {
57
+ ...updatedChannel,
58
+ status: 'quiesced',
59
+ pendingHTLCs: [],
60
+ quiesceSignedState: signedState,
61
+ updatedAt: Date.now(),
62
+ };
63
+ return quiesced;
64
+ }
@@ -0,0 +1,38 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { SpliceParams, SpliceTxDraft } from './types.js';
3
+ /**
4
+ * Build a validated SpliceTxDraft from channel + splice params.
5
+ *
6
+ * For splice-in:
7
+ * inputs = [channel coin (latestCoinId), additional coin]
8
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
9
+ *
10
+ * For splice-out:
11
+ * inputs = [channel coin (latestCoinId)]
12
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
13
+ * [withdrawal coin at withdrawAddress]
14
+ * [any extra outputs]
15
+ *
16
+ * The output channel coin always resets STATE(101)=0 so the new channel starts
17
+ * from sequence 0 with a full WOTS signing budget.
18
+ *
19
+ * @param channel - Quiesced or active channel to splice.
20
+ * @param params - Splice parameters (type, amounts, addresses).
21
+ * @returns Validated SpliceTxDraft.
22
+ * @throws {SpliceBalanceConservationError} If output amounts do not sum to newTotalValue.
23
+ * @throws {SpliceInsufficientFundsError} If splice-out exceeds channel holdings.
24
+ */
25
+ export declare function buildSpliceTx(channel: OmniaChannel, params: SpliceParams): SpliceTxDraft;
26
+ /**
27
+ * Convert a SpliceTxDraft to canonical Minima binary TX bytes.
28
+ *
29
+ * The resulting bytes cover inputs, outputs, and state variables and are
30
+ * suitable for WOTS signing. Both parties sign the same bytes independently;
31
+ * the final splice TX assembles both signatures into the witness.
32
+ */
33
+ export declare function spliceDraftToMinimaBytes(draft: SpliceTxDraft): Uint8Array;
34
+ /**
35
+ * Compute a 32-byte digest over the splice TX draft for WOTS signing.
36
+ * This is the canonical message both parties sign to authorize the splice.
37
+ */
38
+ export declare function computeSpliceTxDigest(draft: SpliceTxDraft): Uint8Array;