@totemsdk/omnia-factory 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/cjs/commitment.d.ts +16 -0
  2. package/dist/cjs/commitment.js +30 -0
  3. package/dist/cjs/coordination.d.ts +52 -0
  4. package/dist/cjs/coordination.js +319 -0
  5. package/dist/cjs/durable-factory-store.d.ts +42 -0
  6. package/dist/cjs/durable-factory-store.js +59 -0
  7. package/dist/cjs/factory.d.ts +91 -0
  8. package/dist/cjs/factory.js +380 -0
  9. package/dist/cjs/index.d.ts +12 -0
  10. package/dist/cjs/index.js +38 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/script.d.ts +47 -0
  13. package/dist/cjs/script.js +105 -0
  14. package/dist/cjs/settlement.d.ts +55 -0
  15. package/dist/cjs/settlement.js +193 -0
  16. package/dist/cjs/types.d.ts +131 -0
  17. package/dist/cjs/types.js +2 -0
  18. package/dist/cjs/virtual.d.ts +75 -0
  19. package/dist/cjs/virtual.js +277 -0
  20. package/dist/commitment.js +3 -6
  21. package/dist/coordination.d.ts +52 -0
  22. package/dist/coordination.js +316 -0
  23. package/dist/durable-factory-store.d.ts +42 -0
  24. package/dist/durable-factory-store.js +56 -0
  25. package/dist/factory.d.ts +21 -0
  26. package/dist/factory.js +101 -30
  27. package/dist/index.d.ts +10 -4
  28. package/dist/index.js +8 -21
  29. package/dist/script.d.ts +31 -13
  30. package/dist/script.js +68 -34
  31. package/dist/settlement.d.ts +36 -12
  32. package/dist/settlement.js +108 -70
  33. package/dist/types.js +1 -2
  34. package/dist/virtual.d.ts +31 -0
  35. package/dist/virtual.js +110 -59
  36. package/package.json +20 -13
  37. package/rust/pkg/omnia_factory_wasm_bg.wasm +0 -0
  38. package/rust/pkg/package.json +1 -1
  39. package/rust/pkg-node/omnia_factory_wasm_bg.wasm +0 -0
  40. package/rust/pkg-node/package.json +1 -1
@@ -0,0 +1,380 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enforceConservation = enforceConservation;
4
+ exports.createFactory = createFactory;
5
+ exports.acceptFactory = acceptFactory;
6
+ exports.signFactoryOpening = signFactoryOpening;
7
+ exports.verifyFactorySignature = verifyFactorySignature;
8
+ exports.applyFactorySignature = applyFactorySignature;
9
+ exports.reallocate = reallocate;
10
+ const wasm_1 = require("@totemsdk/core/wasm");
11
+ const wasm_2 = require("@totemsdk/core/wasm");
12
+ const omnia_1 = require("@totemsdk/omnia");
13
+ const txpow_1 = require("@totemsdk/txpow");
14
+ const script_js_1 = require("./script.js");
15
+ const commitment_js_1 = require("./commitment.js");
16
+ // ─── Balance conservation ────────────────────────────────────────────────────
17
+ /**
18
+ * Enforce the factory's balance conservation invariant:
19
+ * sum(allocations) + sum(virtualChannel.totalValue) === totalValue
20
+ *
21
+ * Throws on violation. Called after every committed state transition.
22
+ */
23
+ function enforceConservation(factory) {
24
+ const allocSum = Object.values(factory.allocations).reduce((a, b) => a + b, 0n);
25
+ const vcSum = factory.virtualChannels.reduce((acc, vc) => acc + vc.totalValue, 0n);
26
+ if (allocSum + vcSum !== factory.totalValue) {
27
+ throw new Error(`Balance conservation violated: allocations(${allocSum}) + virtualChannels(${vcSum}) ` +
28
+ `!== totalValue(${factory.totalValue})`);
29
+ }
30
+ }
31
+ // ─── Internal signing helpers ─────────────────────────────────────────────────
32
+ /**
33
+ * Execute the full WOTS lease cycle for one party (reserve → sign → verify → commit).
34
+ *
35
+ * Verification uses the optional `bundle.verify` override first; falls back to
36
+ * `verifyChannelSignature` from `@totemsdk/omnia` (RFC-037: the wallet's unified
37
+ * WOTS scheme). If verification fails, the reservation is burned and an error is thrown.
38
+ */
39
+ async function leaseSign(factoryId, commitment, purpose, participant, bundle) {
40
+ const reservation = await bundle.leaseProvider.reserveKeyUse({
41
+ treeId: `omnia-factory-${factoryId}`,
42
+ purpose,
43
+ payloadHash: Buffer.from(commitment).toString('hex'),
44
+ });
45
+ let sig;
46
+ try {
47
+ sig = await bundle.signer.sign(commitment, reservation.indices);
48
+ }
49
+ catch (err) {
50
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
51
+ throw err;
52
+ }
53
+ // Verify the signature against the REGISTERED participant public key digest —
54
+ // not self-reported from the signer, ensuring the signer matches the factory record.
55
+ const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
56
+ if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
57
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
58
+ throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
59
+ }
60
+ await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-${factoryId}`);
61
+ return sig;
62
+ }
63
+ /**
64
+ * Collect N-of-N signatures for a given commitment from ALL factory participants.
65
+ * Throws if any participant's bundle is missing or if any signature fails verification.
66
+ */
67
+ async function collectNofN(factoryId, commitment, purpose, participants, leaseProviders) {
68
+ for (const p of participants) {
69
+ if (!leaseProviders[p.partyId]) {
70
+ throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`);
71
+ }
72
+ }
73
+ for (const p of participants) {
74
+ await leaseSign(factoryId, commitment, purpose, p, leaseProviders[p.partyId]);
75
+ }
76
+ }
77
+ // ─── Factory ID ───────────────────────────────────────────────────────────────
78
+ function generateFactoryId(participants, tokenId, tokenScale) {
79
+ const sorted = [...participants].sort((a, b) => a.partyId.localeCompare(b.partyId));
80
+ const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
81
+ const input = JSON.stringify({
82
+ participants: sorted.map(p => ({ partyId: p.partyId, pkd: p.publicKeyDigest })),
83
+ tokenId,
84
+ tokenScale,
85
+ nonce,
86
+ });
87
+ return Buffer.from((0, wasm_1.sha3_256)(new TextEncoder().encode(input))).toString('hex');
88
+ }
89
+ // ─── createFactory ────────────────────────────────────────────────────────────
90
+ /**
91
+ * Create a factory proposal (proposer step).
92
+ *
93
+ * The calling party (`signer.publicKeyDigest` matches one of `participants`)
94
+ * signs the factory opening commitment via `leaseProvider`, performing the full
95
+ * WOTS reserve → sign → verify → commit cycle.
96
+ *
97
+ * When ALL participants supply `fundingCoinId` and `chainProvider` is given,
98
+ * the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
99
+ * `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
100
+ * The TX draft digest is used as the factory opening commitment so that all
101
+ * parties are co-signing the EXACT on-chain TX structure.
102
+ *
103
+ * Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
104
+ * (useful for testing and off-chain simulation); the commitment falls back to
105
+ * the factory state commitment hash.
106
+ *
107
+ * The returned factory is in `'opening'` status. Every other participant must
108
+ * call `acceptFactory(factory, leaseProvider, signer)` before the factory
109
+ * transitions to `'active'`.
110
+ *
111
+ * @param participants - All N factory participants with their contribution amounts.
112
+ * @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
113
+ * @param leaseProvider - WOTS lease provider for the proposer's key slot.
114
+ * @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
115
+ * one of the registered participants).
116
+ * @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
117
+ * @param tokenScale - Token scale exponent (Minima `Token.mTokenScale`). Native Minima
118
+ * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
119
+ * Defaults to 0.
120
+ */
121
+ async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
122
+ if (participants.length < 2) {
123
+ throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
124
+ }
125
+ // Identify the proposer by public key digest.
126
+ const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
127
+ if (!proposer) {
128
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
129
+ }
130
+ const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
131
+ const allocations = {};
132
+ for (const p of participants) {
133
+ allocations[p.partyId] = p.contributionAmount;
134
+ }
135
+ const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
136
+ const factoryId = generateFactoryId(participants, tokenId, tokenScale);
137
+ // ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
138
+ let fundingTxId;
139
+ let fundingCoinId;
140
+ let pendingCommitment;
141
+ const allHaveCoinId = participants.every(p => p.fundingCoinId);
142
+ if (allHaveCoinId && chainProvider) {
143
+ const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), participants.map(p => p.settlementAddress ?? p.publicKeyDigest), (0, script_js_1.factoryBalanceStateVariables)(participants));
144
+ // All parties co-sign the TX digest — the exact on-chain TX structure.
145
+ pendingCommitment = (0, omnia_1.computeTxDraftDigest)(fundingDraft);
146
+ const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
147
+ const txBody = (0, txpow_1.serializeTxBody)(draftBytes, new Uint8Array(0));
148
+ const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
149
+ const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
150
+ await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
151
+ fundingTxId = Buffer.from(mined.txpowId).toString('hex');
152
+ fundingCoinId = `${fundingTxId}-0`;
153
+ }
154
+ else {
155
+ // In-memory / test path: sign the factory state commitment instead.
156
+ pendingCommitment = (0, commitment_js_1.computeFactoryStateCommitment)(factoryId, 1, allocations, []);
157
+ }
158
+ // Sign with the proposer's lease (full bundle preserved so verify override is available).
159
+ const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
160
+ const initialEntry = {
161
+ sequence: 0,
162
+ timestamp: Date.now(),
163
+ event: 'create',
164
+ allocations: { ...allocations },
165
+ virtualChannelIds: [],
166
+ };
167
+ const factory = {
168
+ factoryId,
169
+ participants,
170
+ totalValue,
171
+ tokenId,
172
+ tokenScale,
173
+ allocations: { ...allocations },
174
+ virtualChannels: [],
175
+ currentSequence: 0,
176
+ status: 'opening',
177
+ stateLog: [initialEntry],
178
+ fundingScript: script,
179
+ fundingAddress: address,
180
+ fundingTxId,
181
+ fundingCoinId,
182
+ pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
183
+ pendingSignatures: { [proposer.partyId]: proposerSig },
184
+ };
185
+ // If proposer is the only participant (edge case), activate immediately.
186
+ if (participants.length === 1) {
187
+ return commitOpening(factory);
188
+ }
189
+ return factory;
190
+ }
191
+ // ─── acceptFactory ────────────────────────────────────────────────────────────
192
+ /**
193
+ * Counterparty co-signs the factory proposal.
194
+ *
195
+ * Each non-proposing participant calls this once. When ALL N parties have
196
+ * signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
197
+ * the factory transitions from `'opening'` to `'active'`.
198
+ *
199
+ * Uses the full WOTS lease cycle: reserve → sign → verify → commit.
200
+ *
201
+ * @param factory - Factory in `'opening'` status returned by `createFactory`.
202
+ * @param leaseProvider - This counterparty's WOTS lease provider.
203
+ * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
204
+ * must match a registered participant not yet signed).
205
+ */
206
+ async function acceptFactory(factory, bundle) {
207
+ if (factory.status !== 'opening') {
208
+ throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
209
+ }
210
+ if (!factory.pendingCommitment) {
211
+ throw new Error('Factory has no pending commitment — internal state error');
212
+ }
213
+ const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
214
+ if (!participant) {
215
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
216
+ }
217
+ if (factory.pendingSignatures[participant.partyId]) {
218
+ throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
219
+ }
220
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
221
+ const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
222
+ const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
223
+ const updatedFactory = { ...factory, pendingSignatures: newSigs };
224
+ // When all N parties have signed, commit the opening.
225
+ const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
226
+ if (allSigned) {
227
+ return commitOpening(updatedFactory);
228
+ }
229
+ return updatedFactory;
230
+ }
231
+ /**
232
+ * Produce this party's opening signature WITHOUT committing the lease
233
+ * (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
234
+ * mirroring the splice accept round so a peer can gather N-of-N signatures
235
+ * without stranding or prematurely committing one-time keys.
236
+ */
237
+ async function signFactoryOpening(factory, bundle) {
238
+ if (factory.status !== 'opening' || !factory.pendingCommitment) {
239
+ throw new Error(`signFactoryOpening requires an 'opening' factory, got '${factory.status}'`);
240
+ }
241
+ const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
242
+ if (!participant) {
243
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
244
+ }
245
+ if (factory.pendingSignatures[participant.partyId]) {
246
+ throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
247
+ }
248
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
249
+ const reservation = await bundle.leaseProvider.reserveKeyUse({
250
+ treeId: `omnia-factory-${factory.factoryId}`,
251
+ purpose: 'factory-open',
252
+ payloadHash: Buffer.from(commitment).toString('hex'),
253
+ });
254
+ let sig;
255
+ try {
256
+ sig = await bundle.signer.sign(commitment, reservation.indices);
257
+ }
258
+ catch (err) {
259
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
260
+ throw err;
261
+ }
262
+ const verifyFn = bundle.verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
263
+ if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
264
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
265
+ throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
266
+ }
267
+ return {
268
+ factoryId: factory.factoryId,
269
+ partyId: participant.partyId,
270
+ signature: sig,
271
+ reservationId: reservation.reservationId,
272
+ };
273
+ }
274
+ /** Verify a remote opening signature against a factory participant. */
275
+ function verifyFactorySignature(factory, partyId, signature, verify) {
276
+ if (!factory.pendingCommitment)
277
+ return false;
278
+ const participant = factory.participants.find(p => p.partyId === partyId);
279
+ if (!participant)
280
+ return false;
281
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
282
+ const verifyFn = verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
283
+ try {
284
+ return verifyFn(signature, commitment, participant.publicKeyDigest);
285
+ }
286
+ catch {
287
+ return false;
288
+ }
289
+ }
290
+ /**
291
+ * Merge a co-signer's opening signature (RFC-035 B2). When all N participants
292
+ * have signed, the opening commits (`'opening'` → `'active'`).
293
+ */
294
+ function applyFactorySignature(factory, partyId, signature) {
295
+ if (factory.status !== 'opening') {
296
+ throw new Error(`applyFactorySignature requires factory status 'opening', got '${factory.status}'`);
297
+ }
298
+ if (!factory.participants.find(p => p.partyId === partyId)) {
299
+ throw new Error(`'${partyId}' is not a registered factory participant`);
300
+ }
301
+ if (factory.pendingSignatures[partyId]) {
302
+ throw new Error(`Party '${partyId}' has already co-signed this factory proposal`);
303
+ }
304
+ const newSigs = { ...factory.pendingSignatures, [partyId]: signature };
305
+ const updated = { ...factory, pendingSignatures: newSigs };
306
+ const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
307
+ return allSigned ? commitOpening(updated) : updated;
308
+ }
309
+ function commitOpening(factory) {
310
+ const logEntry = {
311
+ sequence: 1,
312
+ timestamp: Date.now(),
313
+ event: 'accept',
314
+ allocations: { ...factory.allocations },
315
+ virtualChannelIds: [],
316
+ };
317
+ const committed = {
318
+ ...factory,
319
+ currentSequence: 1,
320
+ status: 'active',
321
+ pendingCommitment: undefined,
322
+ pendingSignatures: {},
323
+ stateLog: [...factory.stateLog, logEntry],
324
+ };
325
+ enforceConservation(committed);
326
+ return committed;
327
+ }
328
+ // ─── reallocate ───────────────────────────────────────────────────────────────
329
+ /**
330
+ * Move factory allocation between two participants (atomic N-of-N).
331
+ *
332
+ * All N leaseProviders must be supplied; each party signs the new state
333
+ * commitment in turn. The state commits atomically — no intermediate "pending"
334
+ * object is returned.
335
+ *
336
+ * @param factory - Active factory.
337
+ * @param fromPartyId - Party giving up allocation.
338
+ * @param toPartyId - Party receiving allocation.
339
+ * @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
340
+ * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
341
+ */
342
+ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
343
+ if (factory.status !== 'active') {
344
+ throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
345
+ }
346
+ if (amount <= 0n) {
347
+ throw new Error(`Reallocation amount must be positive, got ${amount}`);
348
+ }
349
+ const fromAlloc = factory.allocations[fromPartyId] ?? 0n;
350
+ if (fromAlloc < amount) {
351
+ throw new Error(`Insufficient allocation for '${fromPartyId}': has ${fromAlloc}, needs ${amount}`);
352
+ }
353
+ if (!factory.participants.find(p => p.partyId === toPartyId)) {
354
+ throw new Error(`'${toPartyId}' is not a registered factory participant`);
355
+ }
356
+ const newAllocations = {
357
+ ...factory.allocations,
358
+ [fromPartyId]: fromAlloc - amount,
359
+ [toPartyId]: (factory.allocations[toPartyId] ?? 0n) + amount,
360
+ };
361
+ const newSequence = factory.currentSequence + 1;
362
+ const vcIds = factory.virtualChannels.map(vc => vc.channelId);
363
+ const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, vcIds);
364
+ await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
365
+ const logEntry = {
366
+ sequence: newSequence,
367
+ timestamp: Date.now(),
368
+ event: 'reallocate',
369
+ allocations: newAllocations,
370
+ virtualChannelIds: vcIds,
371
+ };
372
+ const updated = {
373
+ ...factory,
374
+ allocations: newAllocations,
375
+ currentSequence: newSequence,
376
+ stateLog: [...factory.stateLog, logEntry],
377
+ };
378
+ enforceConservation(updated);
379
+ return updated;
380
+ }
@@ -0,0 +1,12 @@
1
+ export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, scriptAddress, normalizeScript, } from './script.js';
3
+ export { computeFactoryStateCommitment } from './commitment.js';
4
+ export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
+ export type { FactoryOpeningSignature } from './factory.js';
6
+ export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
7
+ export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
8
+ export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, } from './virtual.js';
9
+ export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
10
+ export type { FactorySettlementDraft, FactorySettlementSignature, } from './settlement.js';
11
+ export { createDurableFactoryStore, } from './durable-factory-store.js';
12
+ export type { FactoryRegistryState, DurableFactoryStore, DurableFactoryStoreOptions, } from './durable-factory-store.js';
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
4
+ var script_js_1 = require("./script.js");
5
+ Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
6
+ Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
7
+ Object.defineProperty(exports, "factoryBalanceStateVariables", { enumerable: true, get: function () { return script_js_1.factoryBalanceStateVariables; } });
8
+ Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: function () { return script_js_1.scriptAddress; } });
9
+ Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
10
+ var commitment_js_1 = require("./commitment.js");
11
+ Object.defineProperty(exports, "computeFactoryStateCommitment", { enumerable: true, get: function () { return commitment_js_1.computeFactoryStateCommitment; } });
12
+ var factory_js_1 = require("./factory.js");
13
+ Object.defineProperty(exports, "createFactory", { enumerable: true, get: function () { return factory_js_1.createFactory; } });
14
+ Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
15
+ Object.defineProperty(exports, "reallocate", { enumerable: true, get: function () { return factory_js_1.reallocate; } });
16
+ Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: function () { return factory_js_1.enforceConservation; } });
17
+ Object.defineProperty(exports, "signFactoryOpening", { enumerable: true, get: function () { return factory_js_1.signFactoryOpening; } });
18
+ Object.defineProperty(exports, "verifyFactorySignature", { enumerable: true, get: function () { return factory_js_1.verifyFactorySignature; } });
19
+ Object.defineProperty(exports, "applyFactorySignature", { enumerable: true, get: function () { return factory_js_1.applyFactorySignature; } });
20
+ // RFC-035 B2 — factory opening round-trip over the coordination transport.
21
+ var coordination_js_1 = require("./coordination.js");
22
+ Object.defineProperty(exports, "createFactoryCoordination", { enumerable: true, get: function () { return coordination_js_1.createFactoryCoordination; } });
23
+ var virtual_js_1 = require("./virtual.js");
24
+ Object.defineProperty(exports, "openVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.openVirtualChannel; } });
25
+ Object.defineProperty(exports, "closeVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.closeVirtualChannel; } });
26
+ Object.defineProperty(exports, "buildVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.buildVirtualChannelOpen; } });
27
+ Object.defineProperty(exports, "signVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.signVirtualChannelOpen; } });
28
+ Object.defineProperty(exports, "verifyVirtualChannelOpenSignature", { enumerable: true, get: function () { return virtual_js_1.verifyVirtualChannelOpenSignature; } });
29
+ Object.defineProperty(exports, "assembleVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.assembleVirtualChannelOpen; } });
30
+ var settlement_js_1 = require("./settlement.js");
31
+ Object.defineProperty(exports, "closeFactory", { enumerable: true, get: function () { return settlement_js_1.closeFactory; } });
32
+ Object.defineProperty(exports, "buildDisputePayload", { enumerable: true, get: function () { return settlement_js_1.buildDisputePayload; } });
33
+ Object.defineProperty(exports, "buildFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.buildFactorySettlement; } });
34
+ Object.defineProperty(exports, "signFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.signFactorySettlement; } });
35
+ Object.defineProperty(exports, "verifyFactorySettlementSignature", { enumerable: true, get: function () { return settlement_js_1.verifyFactorySettlementSignature; } });
36
+ Object.defineProperty(exports, "assembleFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.assembleFactorySettlement; } });
37
+ var durable_factory_store_js_1 = require("./durable-factory-store.js");
38
+ Object.defineProperty(exports, "createDurableFactoryStore", { enumerable: true, get: function () { return durable_factory_store_js_1.createDurableFactoryStore; } });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,47 @@
1
+ import type { FactoryParticipant } from './types.js';
2
+ /** Default coinage (blocks) after which any party may unilaterally withdraw. */
3
+ export declare const FACTORY_TIMEOUT_BLOCKS = 256;
4
+ /** State port base for per-party allocations: party k ⇒ port 200+k. */
5
+ export declare const FACTORY_BALANCE_PORT_BASE = 200;
6
+ export interface FactoryScriptOptions {
7
+ /** Coinage threshold for the unilateral per-party escape (default 256). */
8
+ timeoutBlocks?: number;
9
+ }
10
+ /**
11
+ * Per-party allocation state variables (port 200+k = party k's balance), seeded
12
+ * into the factory funding output so the timeout escape can pay each party its
13
+ * committed share.
14
+ */
15
+ export declare function factoryBalanceStateVariables(participants: FactoryParticipant[]): {
16
+ port: number;
17
+ value: bigint;
18
+ type: 'number';
19
+ }[];
20
+ /**
21
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory
22
+ * (RFC-044, CUSTODY-POLICY §2).
23
+ *
24
+ * Spend paths:
25
+ * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
26
+ * `SETTLEMENT=true` closes after minimal coinage (1 block).
27
+ * - **Unilateral escape** (after `@COINAGE GTE timeoutBlocks`): any single
28
+ * party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its own
29
+ * settlement address, zero its state (`STATE(200+k) EQ 0`), keep the other
30
+ * parties' balances unchanged, and return the remainder to the factory
31
+ * script. Repeated withdrawals cannot double-claim because each zeroes its
32
+ * own port.
33
+ *
34
+ * Minimum 2 participants required.
35
+ */
36
+ export declare function buildFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): string;
37
+ export declare function normalizeScript(script: string): string;
38
+ /** Compute the SHA3-256 script-hash address for a factory script. */
39
+ export declare function scriptAddress(script: string): string;
40
+ /**
41
+ * Build the factory script and compute its canonical address in one step.
42
+ * The address is used as the output address of the factory funding TX.
43
+ */
44
+ export declare function buildAndHashFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): {
45
+ script: string;
46
+ address: string;
47
+ };
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_TIMEOUT_BLOCKS = void 0;
4
+ exports.factoryBalanceStateVariables = factoryBalanceStateVariables;
5
+ exports.buildFactoryScript = buildFactoryScript;
6
+ exports.normalizeScript = normalizeScript;
7
+ exports.scriptAddress = scriptAddress;
8
+ exports.buildAndHashFactoryScript = buildAndHashFactoryScript;
9
+ const scripts_1 = require("@totemsdk/core/scripts");
10
+ /**
11
+ * Normalize a hex public key digest to the KISSVM-compatible format:
12
+ * strip leading 0x/0X and render as upper-case hex with leading '0X'.
13
+ */
14
+ function kissHex(hex) {
15
+ const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
16
+ return '0X' + raw.toUpperCase();
17
+ }
18
+ /** Default coinage (blocks) after which any party may unilaterally withdraw. */
19
+ exports.FACTORY_TIMEOUT_BLOCKS = 256;
20
+ /** State port base for per-party allocations: party k ⇒ port 200+k. */
21
+ exports.FACTORY_BALANCE_PORT_BASE = 200;
22
+ /**
23
+ * Per-party allocation state variables (port 200+k = party k's balance), seeded
24
+ * into the factory funding output so the timeout escape can pay each party its
25
+ * committed share.
26
+ */
27
+ function factoryBalanceStateVariables(participants) {
28
+ return participants.map((p, k) => ({
29
+ port: exports.FACTORY_BALANCE_PORT_BASE + k,
30
+ value: p.contributionAmount,
31
+ type: 'number',
32
+ }));
33
+ }
34
+ /**
35
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory
36
+ * (RFC-044, CUSTODY-POLICY §2).
37
+ *
38
+ * Spend paths:
39
+ * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
40
+ * `SETTLEMENT=true` closes after minimal coinage (1 block).
41
+ * - **Unilateral escape** (after `@COINAGE GTE timeoutBlocks`): any single
42
+ * party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its own
43
+ * settlement address, zero its state (`STATE(200+k) EQ 0`), keep the other
44
+ * parties' balances unchanged, and return the remainder to the factory
45
+ * script. Repeated withdrawals cannot double-claim because each zeroes its
46
+ * own port.
47
+ *
48
+ * Minimum 2 participants required.
49
+ */
50
+ function buildFactoryScript(participants, options = {}) {
51
+ if (participants.length < 2) {
52
+ throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
53
+ }
54
+ const count = participants.length;
55
+ const timeout = options.timeoutBlocks ?? exports.FACTORY_TIMEOUT_BLOCKS;
56
+ if (!Number.isInteger(timeout) || timeout < 0) {
57
+ throw new Error(`timeoutBlocks must be a non-negative integer, got ${JSON.stringify(timeout)}`);
58
+ }
59
+ const pks = participants.map((p) => kissHex(p.publicKeyDigest));
60
+ const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
61
+ const lines = [
62
+ 'LET SETTLEMENT=STATE(100)',
63
+ `IF @COINAGE GTE ${timeout} THEN`,
64
+ ];
65
+ participants.forEach((_, k) => {
66
+ const port = exports.FACTORY_BALANCE_PORT_BASE + k;
67
+ lines.push(` LET SHARE${k}=STATE(${port})`);
68
+ lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
69
+ lines.push(` IF SHARE${k} GT 0 THEN`);
70
+ lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
71
+ for (let j = 0; j < count; j++) {
72
+ if (j === k)
73
+ continue;
74
+ lines.push(` ASSERT STATE(${exports.FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + j})`);
75
+ }
76
+ lines.push(` ASSERT STATE(${port}) EQ 0`);
77
+ lines.push(` RETURN VERIFYOUT(@INPUT @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
78
+ lines.push(' ENDIF');
79
+ lines.push(' ENDIF');
80
+ });
81
+ lines.push('ENDIF');
82
+ lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
83
+ lines.push('IF SETTLEMENT THEN');
84
+ lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
85
+ lines.push('ELSE');
86
+ lines.push(' RETURN TRUE');
87
+ lines.push('ENDIF');
88
+ return lines.join('\n');
89
+ }
90
+ function normalizeScript(script) {
91
+ return script.trim().toUpperCase();
92
+ }
93
+ /** Compute the SHA3-256 script-hash address for a factory script. */
94
+ function scriptAddress(script) {
95
+ return (0, scripts_1.computeScriptAddress)(script);
96
+ }
97
+ /**
98
+ * Build the factory script and compute its canonical address in one step.
99
+ * The address is used as the output address of the factory funding TX.
100
+ */
101
+ function buildAndHashFactoryScript(participants, options = {}) {
102
+ const script = buildFactoryScript(participants, options);
103
+ const address = scriptAddress(script);
104
+ return { script, address };
105
+ }
@@ -0,0 +1,55 @@
1
+ import type { OmniaTxDraft } from '@totemsdk/omnia';
2
+ import type { ChainStateProvider } from '@totemsdk/chain-provider';
3
+ import type { ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, WotsLeaseBundle } from './types.js';
4
+ /** Deterministic settlement TX material for a factory (RFC-035 B3). */
5
+ export interface FactorySettlementDraft {
6
+ settlementDraft: OmniaTxDraft;
7
+ settlementTxHex: string;
8
+ txDigest: Uint8Array;
9
+ }
10
+ /** A participant's settlement signature, held until the close is confirmed. */
11
+ export interface FactorySettlementSignature {
12
+ partyId: string;
13
+ signature: Uint8Array;
14
+ reservationId: string;
15
+ }
16
+ /**
17
+ * Build the cooperative settlement TX + digest (no signing). Exported so peers
18
+ * can independently rebuild and bind a proposal (RFC-035 B3).
19
+ */
20
+ export declare function buildFactorySettlement(factory: ChannelFactory): FactorySettlementDraft;
21
+ /**
22
+ * Produce this party's settlement signature WITHOUT committing the lease
23
+ * (RFC-035 B3). The caller commits on `FACTORY_CLOSE_FINALIZED` or burns on expiry.
24
+ */
25
+ export declare function signFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, bundle: WotsLeaseBundle): Promise<FactorySettlementSignature>;
26
+ /** Verify a remote settlement signature against a factory participant. */
27
+ export declare function verifyFactorySettlementSignature(factory: ChannelFactory, txDigest: Uint8Array, partyId: string, signature: Uint8Array, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): boolean;
28
+ /**
29
+ * Assemble N-of-N settlement signatures into the MULTISIG witness + payload, and
30
+ * (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
31
+ */
32
+ export declare function assembleFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, signatures: Record<string, FactorySettlementSignature>, chainProvider?: ChainStateProvider, options?: {
33
+ verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean;
34
+ }): Promise<FactorySettlementPayload>;
35
+ /**
36
+ * Cooperative N-of-N factory close (central/local path).
37
+ *
38
+ * Builds the settlement TX, collects all N signatures (each committing its own
39
+ * lease via the full WOTS cycle), assembles the witness, and — when a
40
+ * `chainProvider` is supplied — mines + broadcasts the settlement TxPoW.
41
+ *
42
+ * @param factory - Active factory with no open virtual channels.
43
+ * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
44
+ * @param chainProvider - Optional: mine + broadcast the settlement TX.
45
+ */
46
+ export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider): Promise<FactorySettlementPayload>;
47
+ /**
48
+ * Build a unilateral factory close (dispute) payload.
49
+ *
50
+ * Includes the full `stateLog` (with monotonically increasing `sequence` entries)
51
+ * for on-chain or arbitration verification. Virtual channels still open at
52
+ * dispute time are included by ID so the dispute resolver can adjudicate their
53
+ * balances independently.
54
+ */
55
+ export declare function buildDisputePayload(factory: ChannelFactory, evidence: string): FactoryDisputePayload;