@totemsdk/omnia-factory 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,16 @@
1
+ /**
2
+ * Compute the canonical 32-byte state commitment for N-of-N factory signing.
3
+ *
4
+ * Covers:
5
+ * - factoryId (factory context isolation)
6
+ * - sequence (monotonicity; prevents replay of old state)
7
+ * - pendingAllocations (the proposed allocation split being signed)
8
+ * - virtualChannelIds (list of currently open VCs; prevents forgery of VC state)
9
+ *
10
+ * All fields are sorted lexicographically for determinism regardless of the
11
+ * order in which keys appear in the caller's objects.
12
+ *
13
+ * This commitment is what every party signs via `FactorySignerOps.sign`, and
14
+ * what `FactorySignerOps.verify` checks against each stored signature.
15
+ */
16
+ export declare function computeFactoryStateCommitment(factoryId: string, sequence: number, pendingAllocations: Record<string, bigint>, virtualChannelIds: string[]): Uint8Array;
@@ -0,0 +1,27 @@
1
+ import { sha3_256 } from '@noble/hashes/sha3';
2
+ /**
3
+ * Compute the canonical 32-byte state commitment for N-of-N factory signing.
4
+ *
5
+ * Covers:
6
+ * - factoryId (factory context isolation)
7
+ * - sequence (monotonicity; prevents replay of old state)
8
+ * - pendingAllocations (the proposed allocation split being signed)
9
+ * - virtualChannelIds (list of currently open VCs; prevents forgery of VC state)
10
+ *
11
+ * All fields are sorted lexicographically for determinism regardless of the
12
+ * order in which keys appear in the caller's objects.
13
+ *
14
+ * This commitment is what every party signs via `FactorySignerOps.sign`, and
15
+ * what `FactorySignerOps.verify` checks against each stored signature.
16
+ */
17
+ export function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
18
+ const canonical = {
19
+ factoryId,
20
+ sequence,
21
+ allocations: Object.fromEntries(Object.entries(pendingAllocations)
22
+ .sort(([a], [b]) => a.localeCompare(b))
23
+ .map(([k, v]) => [k, v.toString()])),
24
+ virtualChannelIds: [...virtualChannelIds].sort(),
25
+ };
26
+ return sha3_256(new TextEncoder().encode(JSON.stringify(canonical)));
27
+ }
@@ -0,0 +1,67 @@
1
+ import type { ChainStateProvider } from '@totemsdk/chain-provider';
2
+ import type { ChannelFactory, FactoryParticipant, WotsLeaseBundle } from './types.js';
3
+ /**
4
+ * Enforce the factory's balance conservation invariant:
5
+ * sum(allocations) + sum(virtualChannel.totalValue) === totalValue
6
+ *
7
+ * Throws on violation. Called after every committed state transition.
8
+ */
9
+ export declare function enforceConservation(factory: ChannelFactory): void;
10
+ /**
11
+ * Create a factory proposal (proposer step).
12
+ *
13
+ * The calling party (`signer.publicKeyDigest` matches one of `participants`)
14
+ * signs the factory opening commitment via `leaseProvider`, performing the full
15
+ * WOTS reserve → sign → verify → commit cycle.
16
+ *
17
+ * When ALL participants supply `fundingCoinId` and `chainProvider` is given,
18
+ * the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
19
+ * `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
20
+ * The TX draft digest is used as the factory opening commitment so that all
21
+ * parties are co-signing the EXACT on-chain TX structure.
22
+ *
23
+ * Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
24
+ * (useful for testing and off-chain simulation); the commitment falls back to
25
+ * the factory state commitment hash.
26
+ *
27
+ * The returned factory is in `'opening'` status. Every other participant must
28
+ * call `acceptFactory(factory, leaseProvider, signer)` before the factory
29
+ * transitions to `'active'`.
30
+ *
31
+ * @param participants - All N factory participants with their contribution amounts.
32
+ * @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
33
+ * @param leaseProvider - WOTS lease provider for the proposer's key slot.
34
+ * @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
35
+ * one of the registered participants).
36
+ * @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
37
+ */
38
+ export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider): Promise<ChannelFactory>;
39
+ /**
40
+ * Counterparty co-signs the factory proposal.
41
+ *
42
+ * Each non-proposing participant calls this once. When ALL N parties have
43
+ * signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
44
+ * the factory transitions from `'opening'` to `'active'`.
45
+ *
46
+ * Uses the full WOTS lease cycle: reserve → sign → verify → commit.
47
+ *
48
+ * @param factory - Factory in `'opening'` status returned by `createFactory`.
49
+ * @param leaseProvider - This counterparty's WOTS lease provider.
50
+ * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
51
+ * must match a registered participant not yet signed).
52
+ */
53
+ export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
54
+ /**
55
+ * Move factory allocation between two participants (atomic N-of-N).
56
+ *
57
+ * All N leaseProviders must be supplied; each party signs the new state
58
+ * commitment in turn. The state commits atomically — no intermediate "pending"
59
+ * object is returned.
60
+ *
61
+ * @param factory - Active factory.
62
+ * @param fromPartyId - Party giving up allocation.
63
+ * @param toPartyId - Party receiving allocation.
64
+ * @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
65
+ * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
66
+ */
67
+ export declare function reallocate(factory: ChannelFactory, fromPartyId: string, toPartyId: string, amount: bigint, leaseProviders: Record<string, WotsLeaseBundle>): Promise<ChannelFactory>;
@@ -0,0 +1,289 @@
1
+ import { sha3_256 } from '@noble/hashes/sha3';
2
+ import { concatBytes, wotsVerifyDigest, fromHex } from '@totemsdk/core';
3
+ import { buildFundingTx, omniaDraftToMinimaBytes, computeTxDraftDigest, } from '@totemsdk/omnia';
4
+ import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
5
+ import { buildAndHashFactoryScript } from './script.js';
6
+ import { computeFactoryStateCommitment } from './commitment.js';
7
+ // ─── Balance conservation ────────────────────────────────────────────────────
8
+ /**
9
+ * Enforce the factory's balance conservation invariant:
10
+ * sum(allocations) + sum(virtualChannel.totalValue) === totalValue
11
+ *
12
+ * Throws on violation. Called after every committed state transition.
13
+ */
14
+ export function enforceConservation(factory) {
15
+ const allocSum = Object.values(factory.allocations).reduce((a, b) => a + b, 0n);
16
+ const vcSum = factory.virtualChannels.reduce((acc, vc) => acc + vc.totalValue, 0n);
17
+ if (allocSum + vcSum !== factory.totalValue) {
18
+ throw new Error(`Balance conservation violated: allocations(${allocSum}) + virtualChannels(${vcSum}) ` +
19
+ `!== totalValue(${factory.totalValue})`);
20
+ }
21
+ }
22
+ // ─── Internal signing helpers ─────────────────────────────────────────────────
23
+ /**
24
+ * Execute the full WOTS lease cycle for one party (reserve → sign → verify → commit).
25
+ *
26
+ * Verification uses the optional `bundle.verify` override first; falls back to
27
+ * `wotsVerifyDigest` from `@totemsdk/core`. If verification fails, the reservation
28
+ * is burned and an error is thrown.
29
+ */
30
+ async function leaseSign(factoryId, commitment, purpose, participant, bundle) {
31
+ const reservation = await bundle.leaseProvider.reserveKeyUse({
32
+ treeId: `omnia-factory-${factoryId}`,
33
+ purpose,
34
+ payloadHash: Buffer.from(commitment).toString('hex'),
35
+ });
36
+ let sig;
37
+ try {
38
+ sig = await bundle.signer.sign(commitment, reservation.indices);
39
+ }
40
+ catch (err) {
41
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
42
+ throw err;
43
+ }
44
+ // Verify the signature against the REGISTERED participant public key digest —
45
+ // not self-reported from the signer, ensuring the signer matches the factory record.
46
+ const verifyFn = bundle.verify
47
+ ?? ((s, c, pkd) => wotsVerifyDigest(s, c, fromHex(pkd)));
48
+ if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
49
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
50
+ throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
51
+ }
52
+ await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-${factoryId}`);
53
+ return sig;
54
+ }
55
+ /**
56
+ * Collect N-of-N signatures for a given commitment from ALL factory participants.
57
+ * Throws if any participant's bundle is missing or if any signature fails verification.
58
+ */
59
+ async function collectNofN(factoryId, commitment, purpose, participants, leaseProviders) {
60
+ for (const p of participants) {
61
+ if (!leaseProviders[p.partyId]) {
62
+ throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`);
63
+ }
64
+ }
65
+ for (const p of participants) {
66
+ await leaseSign(factoryId, commitment, purpose, p, leaseProviders[p.partyId]);
67
+ }
68
+ }
69
+ // ─── Factory ID ───────────────────────────────────────────────────────────────
70
+ function generateFactoryId(participants, tokenId) {
71
+ const sorted = [...participants].sort((a, b) => a.partyId.localeCompare(b.partyId));
72
+ const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
73
+ const input = JSON.stringify({
74
+ participants: sorted.map(p => ({ partyId: p.partyId, pkd: p.publicKeyDigest })),
75
+ tokenId,
76
+ nonce,
77
+ });
78
+ return Buffer.from(sha3_256(new TextEncoder().encode(input))).toString('hex');
79
+ }
80
+ // ─── createFactory ────────────────────────────────────────────────────────────
81
+ /**
82
+ * Create a factory proposal (proposer step).
83
+ *
84
+ * The calling party (`signer.publicKeyDigest` matches one of `participants`)
85
+ * signs the factory opening commitment via `leaseProvider`, performing the full
86
+ * WOTS reserve → sign → verify → commit cycle.
87
+ *
88
+ * When ALL participants supply `fundingCoinId` and `chainProvider` is given,
89
+ * the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
90
+ * `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
91
+ * The TX draft digest is used as the factory opening commitment so that all
92
+ * parties are co-signing the EXACT on-chain TX structure.
93
+ *
94
+ * Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
95
+ * (useful for testing and off-chain simulation); the commitment falls back to
96
+ * the factory state commitment hash.
97
+ *
98
+ * The returned factory is in `'opening'` status. Every other participant must
99
+ * call `acceptFactory(factory, leaseProvider, signer)` before the factory
100
+ * transitions to `'active'`.
101
+ *
102
+ * @param participants - All N factory participants with their contribution amounts.
103
+ * @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
104
+ * @param leaseProvider - WOTS lease provider for the proposer's key slot.
105
+ * @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
106
+ * one of the registered participants).
107
+ * @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
108
+ */
109
+ export async function createFactory(participants, tokenId, bundle, chainProvider) {
110
+ if (participants.length < 2) {
111
+ throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
112
+ }
113
+ // Identify the proposer by public key digest.
114
+ const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
115
+ if (!proposer) {
116
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
117
+ }
118
+ const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
119
+ const allocations = {};
120
+ for (const p of participants) {
121
+ allocations[p.partyId] = p.contributionAmount;
122
+ }
123
+ const { script, address } = buildAndHashFactoryScript(participants);
124
+ const factoryId = generateFactoryId(participants, tokenId);
125
+ // ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
126
+ let fundingTxId;
127
+ let fundingCoinId;
128
+ let pendingCommitment;
129
+ const allHaveCoinId = participants.every(p => p.fundingCoinId);
130
+ if (allHaveCoinId && chainProvider) {
131
+ const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, 0, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), participants.map(p => p.settlementAddress ?? p.publicKeyDigest));
132
+ // All parties co-sign the TX digest — the exact on-chain TX structure.
133
+ pendingCommitment = computeTxDraftDigest(fundingDraft);
134
+ const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
135
+ const txBody = serializeTxBody(draftBytes, new Uint8Array(0));
136
+ const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
137
+ const fullTxPoW = concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01]), txBody);
138
+ await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
139
+ fundingTxId = Buffer.from(mined.txpowId).toString('hex');
140
+ fundingCoinId = `${fundingTxId}-0`;
141
+ }
142
+ else {
143
+ // In-memory / test path: sign the factory state commitment instead.
144
+ pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
145
+ }
146
+ // Sign with the proposer's lease (full bundle preserved so verify override is available).
147
+ const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
148
+ const initialEntry = {
149
+ sequence: 0,
150
+ timestamp: Date.now(),
151
+ event: 'create',
152
+ allocations: { ...allocations },
153
+ virtualChannelIds: [],
154
+ };
155
+ const factory = {
156
+ factoryId,
157
+ participants,
158
+ totalValue,
159
+ tokenId,
160
+ allocations: { ...allocations },
161
+ virtualChannels: [],
162
+ currentSequence: 0,
163
+ status: 'opening',
164
+ stateLog: [initialEntry],
165
+ fundingScript: script,
166
+ fundingAddress: address,
167
+ fundingTxId,
168
+ fundingCoinId,
169
+ pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
170
+ pendingSignatures: { [proposer.partyId]: proposerSig },
171
+ };
172
+ // If proposer is the only participant (edge case), activate immediately.
173
+ if (participants.length === 1) {
174
+ return commitOpening(factory);
175
+ }
176
+ return factory;
177
+ }
178
+ // ─── acceptFactory ────────────────────────────────────────────────────────────
179
+ /**
180
+ * Counterparty co-signs the factory proposal.
181
+ *
182
+ * Each non-proposing participant calls this once. When ALL N parties have
183
+ * signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
184
+ * the factory transitions from `'opening'` to `'active'`.
185
+ *
186
+ * Uses the full WOTS lease cycle: reserve → sign → verify → commit.
187
+ *
188
+ * @param factory - Factory in `'opening'` status returned by `createFactory`.
189
+ * @param leaseProvider - This counterparty's WOTS lease provider.
190
+ * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
191
+ * must match a registered participant not yet signed).
192
+ */
193
+ export async function acceptFactory(factory, bundle) {
194
+ if (factory.status !== 'opening') {
195
+ throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
196
+ }
197
+ if (!factory.pendingCommitment) {
198
+ throw new Error('Factory has no pending commitment — internal state error');
199
+ }
200
+ const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
201
+ if (!participant) {
202
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
203
+ }
204
+ if (factory.pendingSignatures[participant.partyId]) {
205
+ throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
206
+ }
207
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
208
+ const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
209
+ const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
210
+ const updatedFactory = { ...factory, pendingSignatures: newSigs };
211
+ // When all N parties have signed, commit the opening.
212
+ const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
213
+ if (allSigned) {
214
+ return commitOpening(updatedFactory);
215
+ }
216
+ return updatedFactory;
217
+ }
218
+ function commitOpening(factory) {
219
+ const logEntry = {
220
+ sequence: 1,
221
+ timestamp: Date.now(),
222
+ event: 'accept',
223
+ allocations: { ...factory.allocations },
224
+ virtualChannelIds: [],
225
+ };
226
+ const committed = {
227
+ ...factory,
228
+ currentSequence: 1,
229
+ status: 'active',
230
+ pendingCommitment: undefined,
231
+ pendingSignatures: {},
232
+ stateLog: [...factory.stateLog, logEntry],
233
+ };
234
+ enforceConservation(committed);
235
+ return committed;
236
+ }
237
+ // ─── reallocate ───────────────────────────────────────────────────────────────
238
+ /**
239
+ * Move factory allocation between two participants (atomic N-of-N).
240
+ *
241
+ * All N leaseProviders must be supplied; each party signs the new state
242
+ * commitment in turn. The state commits atomically — no intermediate "pending"
243
+ * object is returned.
244
+ *
245
+ * @param factory - Active factory.
246
+ * @param fromPartyId - Party giving up allocation.
247
+ * @param toPartyId - Party receiving allocation.
248
+ * @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
249
+ * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
250
+ */
251
+ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
252
+ if (factory.status !== 'active') {
253
+ throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
254
+ }
255
+ if (amount <= 0n) {
256
+ throw new Error(`Reallocation amount must be positive, got ${amount}`);
257
+ }
258
+ const fromAlloc = factory.allocations[fromPartyId] ?? 0n;
259
+ if (fromAlloc < amount) {
260
+ throw new Error(`Insufficient allocation for '${fromPartyId}': has ${fromAlloc}, needs ${amount}`);
261
+ }
262
+ if (!factory.participants.find(p => p.partyId === toPartyId)) {
263
+ throw new Error(`'${toPartyId}' is not a registered factory participant`);
264
+ }
265
+ const newAllocations = {
266
+ ...factory.allocations,
267
+ [fromPartyId]: fromAlloc - amount,
268
+ [toPartyId]: (factory.allocations[toPartyId] ?? 0n) + amount,
269
+ };
270
+ const newSequence = factory.currentSequence + 1;
271
+ const vcIds = factory.virtualChannels.map(vc => vc.channelId);
272
+ const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, vcIds);
273
+ await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
274
+ const logEntry = {
275
+ sequence: newSequence,
276
+ timestamp: Date.now(),
277
+ event: 'reallocate',
278
+ allocations: newAllocations,
279
+ virtualChannelIds: vcIds,
280
+ };
281
+ const updated = {
282
+ ...factory,
283
+ allocations: newAllocations,
284
+ currentSequence: newSequence,
285
+ stateLog: [...factory.stateLog, logEntry],
286
+ };
287
+ enforceConservation(updated);
288
+ return updated;
289
+ }
@@ -0,0 +1,6 @@
1
+ export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
+ export { buildFactoryScript, buildAndHashFactoryScript, scriptAddress, normalizeScript, } from './script.js';
3
+ export { computeFactoryStateCommitment } from './commitment.js';
4
+ export { createFactory, acceptFactory, reallocate, enforceConservation, } from './factory.js';
5
+ export { openVirtualChannel, closeVirtualChannel, } from './virtual.js';
6
+ export { closeFactory, buildDisputePayload, } from './settlement.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { buildFactoryScript, buildAndHashFactoryScript, scriptAddress, normalizeScript, } from './script.js';
2
+ export { computeFactoryStateCommitment } from './commitment.js';
3
+ export { createFactory, acceptFactory, reallocate, enforceConservation, } from './factory.js';
4
+ export { openVirtualChannel, closeVirtualChannel, } from './virtual.js';
5
+ export { closeFactory, buildDisputePayload, } from './settlement.js';
@@ -0,0 +1,29 @@
1
+ import type { FactoryParticipant } from './types.js';
2
+ /**
3
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory.
4
+ *
5
+ * Spending rules:
6
+ * - Any cooperative close (SETTLEMENT=true): all N parties sign, spend after
7
+ * minimal coinage (1 block) so the factory can be closed immediately after
8
+ * a confirmed update.
9
+ * - Non-settlement path: all N parties must still sign (ASSERT MULTISIG(N ...))
10
+ * but can spend in the same block (no coinage requirement) — used for future
11
+ * optimistic factory updates if desired.
12
+ *
13
+ * `storestate=true` is achieved by encoding STATE(100) in the output state
14
+ * variables of every factory TX.
15
+ *
16
+ * Minimum 2 participants required.
17
+ */
18
+ export declare function buildFactoryScript(participants: FactoryParticipant[]): string;
19
+ export declare function normalizeScript(script: string): string;
20
+ /** Compute the SHA3-256 script-hash address for a factory script. */
21
+ export declare function scriptAddress(script: string): string;
22
+ /**
23
+ * Build the factory script and compute its canonical address in one step.
24
+ * The address is used as the output address of the factory funding TX.
25
+ */
26
+ export declare function buildAndHashFactoryScript(participants: FactoryParticipant[]): {
27
+ script: string;
28
+ address: string;
29
+ };
package/dist/script.js ADDED
@@ -0,0 +1,57 @@
1
+ import { computeScriptAddress } from '@totemsdk/core';
2
+ /**
3
+ * Normalize a hex public key digest to the KISSVM-compatible format:
4
+ * strip leading 0x/0X and render as upper-case hex with leading '0X'.
5
+ */
6
+ function kissHex(hex) {
7
+ const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
8
+ return '0X' + raw.toUpperCase();
9
+ }
10
+ /**
11
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory.
12
+ *
13
+ * Spending rules:
14
+ * - Any cooperative close (SETTLEMENT=true): all N parties sign, spend after
15
+ * minimal coinage (1 block) so the factory can be closed immediately after
16
+ * a confirmed update.
17
+ * - Non-settlement path: all N parties must still sign (ASSERT MULTISIG(N ...))
18
+ * but can spend in the same block (no coinage requirement) — used for future
19
+ * optimistic factory updates if desired.
20
+ *
21
+ * `storestate=true` is achieved by encoding STATE(100) in the output state
22
+ * variables of every factory TX.
23
+ *
24
+ * Minimum 2 participants required.
25
+ */
26
+ export function buildFactoryScript(participants) {
27
+ if (participants.length < 2) {
28
+ throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
29
+ }
30
+ const n = participants.length;
31
+ const pks = participants.map(p => kissHex(p.publicKeyDigest)).join(' ');
32
+ return [
33
+ 'LET SETTLEMENT=STATE(100)',
34
+ `ASSERT MULTISIG(${n} ${pks})`,
35
+ 'IF SETTLEMENT THEN',
36
+ ' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF',
37
+ 'ELSE',
38
+ ' RETURN TRUE',
39
+ 'ENDIF',
40
+ ].join('\n');
41
+ }
42
+ export function normalizeScript(script) {
43
+ return script.trim().toUpperCase();
44
+ }
45
+ /** Compute the SHA3-256 script-hash address for a factory script. */
46
+ export function scriptAddress(script) {
47
+ return computeScriptAddress(script);
48
+ }
49
+ /**
50
+ * Build the factory script and compute its canonical address in one step.
51
+ * The address is used as the output address of the factory funding TX.
52
+ */
53
+ export function buildAndHashFactoryScript(participants) {
54
+ const script = buildFactoryScript(participants);
55
+ const address = scriptAddress(script);
56
+ return { script, address };
57
+ }
@@ -0,0 +1,31 @@
1
+ import type { ChainStateProvider } from '@totemsdk/chain-provider';
2
+ import type { ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, WotsLeaseBundle } from './types.js';
3
+ /**
4
+ * Cooperative N-of-N factory close.
5
+ *
6
+ * Flow:
7
+ * 1. Fail fast if `factory.fundingCoinId` is not set — settlement TX requires
8
+ * a concrete input coin.
9
+ * 2. Build the settlement OmniaTxDraft (N outputs, one per participant with a
10
+ * positive allocation) spending the factory's N-of-N MULTISIG input.
11
+ * 3. Compute the TX draft digest via `computeTxDraftDigest` from `@totemsdk/omnia`.
12
+ * 4. Collect N-of-N signatures — all participants sign + verify the TX digest
13
+ * via the full WOTS lease cycle (reserve → sign → verify → commit).
14
+ * 5. Encode the concatenated WOTS signatures as the settlement TX witness.
15
+ * 6. When `chainProvider` is supplied: mine via `@totemsdk/txpow`'s `mineTxPoW`,
16
+ * assemble the full TxPoW blob, and broadcast.
17
+ *
18
+ * @param factory - Active factory with no open virtual channels.
19
+ * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
20
+ * @param chainProvider - Optional: mine + broadcast the settlement TX.
21
+ */
22
+ export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider): Promise<FactorySettlementPayload>;
23
+ /**
24
+ * Build a unilateral factory close (dispute) payload.
25
+ *
26
+ * Includes the full `stateLog` (with monotonically increasing `sequence` entries)
27
+ * for on-chain or arbitration verification. Virtual channels still open at
28
+ * dispute time are included by ID so the dispute resolver can adjudicate their
29
+ * balances independently.
30
+ */
31
+ export declare function buildDisputePayload(factory: ChannelFactory, evidence: string): FactoryDisputePayload;