@totemsdk/omnia-factory 0.7.2 → 0.9.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.
@@ -1,12 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FACTORY_MAX_PARTICIPANTS = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_ESCAPE_DELAY_BLOCKS = void 0;
3
+ exports.FACTORY_MAX_PARTICIPANTS = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_CHECKPOINT_SEQUENCE_PORT = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_ESCAPE_DELAY_BLOCKS = void 0;
4
4
  exports.factoryPartySetRoot = factoryPartySetRoot;
5
5
  exports.factoryPartyProof = factoryPartyProof;
6
6
  exports.factoryBalanceSetRoot = factoryBalanceSetRoot;
7
7
  exports.factoryBalanceProof = factoryBalanceProof;
8
8
  exports.factoryDistributionOutputs = factoryDistributionOutputs;
9
+ exports.buildFactoryPresignedDistributionScript = buildFactoryPresignedDistributionScript;
9
10
  exports.buildFactoryDistributionScript = buildFactoryDistributionScript;
11
+ exports.computeFactoryPartyRoot = computeFactoryPartyRoot;
12
+ exports.computeFactoryBalanceRoot = computeFactoryBalanceRoot;
13
+ exports.factoryBalanceRootStateVariable = factoryBalanceRootStateVariable;
10
14
  exports.factoryPartyRootStateVariable = factoryPartyRootStateVariable;
11
15
  exports.factoryBalanceStateVariables = factoryBalanceStateVariables;
12
16
  exports.factoryEscapeStateVariable = factoryEscapeStateVariable;
@@ -16,6 +20,7 @@ exports.scriptAddress = scriptAddress;
16
20
  exports.buildAndHashFactoryScript = buildAndHashFactoryScript;
17
21
  const scripts_1 = require("@totemsdk/core/scripts");
18
22
  const core_1 = require("@totemsdk/core");
23
+ const core_2 = require("@totemsdk/core");
19
24
  /**
20
25
  * Normalize a hex public key digest to the KISSVM-compatible format:
21
26
  * strip leading 0x/0X and render as upper-case hex with a lowercase 0x prefix.
@@ -28,6 +33,12 @@ function kissHex(hex) {
28
33
  exports.FACTORY_ESCAPE_DELAY_BLOCKS = 256;
29
34
  /** State port carrying the absolute escape block (STATE(103)). */
30
35
  exports.FACTORY_ESCAPE_PORT = 103;
36
+ /**
37
+ * OMN-058/RFC-079 §4: checkpoint sequence (STATE(104)). Seeded at funding and
38
+ * advanced by exactly one on every checkpoint spend, so a checkpoint can never
39
+ * be replayed against a newer state.
40
+ */
41
+ exports.FACTORY_CHECKPOINT_SEQUENCE_PORT = 104;
31
42
  /**
32
43
  * State port carrying the committed party-set root (STATE(111)) — the MMR root
33
44
  * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
@@ -52,7 +63,7 @@ function padPartySet(participants) {
52
63
  if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
53
64
  throw new Error(`participant[${i}].publicKeyDigest must be a hex string`);
54
65
  }
55
- return (0, core_1.hexToBytes)(raw);
66
+ return (0, core_2.hexToBytes)(raw);
56
67
  });
57
68
  let size = 1;
58
69
  while (size < pubkeys.length)
@@ -70,10 +81,10 @@ function padPartySet(participants) {
70
81
  * verifies — over an arbitrary number of participants.
71
82
  */
72
83
  function factoryPartySetRoot(participants) {
73
- const root = core_1.MMRTree.fromPublicKeys(padPartySet(participants)).getRoot();
84
+ const root = core_2.MMRTree.fromPublicKeys(padPartySet(participants)).getRoot();
74
85
  if (!root)
75
86
  throw new Error('factoryPartySetRoot: failed to compute the party-set root');
76
- return (0, core_1.bytesToHex)(root.data).toLowerCase();
87
+ return (0, core_2.bytesToHex)(root.data).toLowerCase();
77
88
  }
78
89
  /**
79
90
  * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
@@ -84,8 +95,8 @@ function factoryPartyProof(participants, index) {
84
95
  if (!Number.isInteger(index) || index < 0 || index >= participants.length) {
85
96
  throw new Error(`factoryPartyProof: index ${index} is out of range (0..${participants.length - 1})`);
86
97
  }
87
- const proof = core_1.MMRTree.fromPublicKeys(padPartySet(participants)).getProof(index);
88
- return (0, core_1.bytesToHex)((0, core_1.serializeMMRProof)(proof)).toLowerCase();
98
+ const proof = core_2.MMRTree.fromPublicKeys(padPartySet(participants)).getProof(index);
99
+ return (0, core_2.bytesToHex)((0, core_2.serializeMMRProof)(proof)).toLowerCase();
89
100
  }
90
101
  /**
91
102
  * Balance set-root (RFC-048 §12.4) — the MMR root over `(pubkey, balance)` leaves,
@@ -98,7 +109,7 @@ function factoryBalanceSetRoot(participants) {
98
109
  const root = tree.getRoot();
99
110
  if (!root)
100
111
  throw new Error('factoryBalanceSetRoot: failed to compute the balance set-root');
101
- return { root: (0, core_1.bytesToHex)(root.data).toLowerCase(), rootSum: root.value };
112
+ return { root: (0, core_2.bytesToHex)(root.data).toLowerCase(), rootSum: root.value };
102
113
  }
103
114
  /**
104
115
  * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
@@ -110,14 +121,14 @@ function factoryBalanceProof(participants, index) {
110
121
  throw new Error(`factoryBalanceProof: index ${index} is out of range (0..${participants.length - 1})`);
111
122
  }
112
123
  const proof = buildBalanceTree(participants).getProof(index);
113
- return (0, core_1.bytesToHex)((0, core_1.serializeMMRProof)(proof)).toLowerCase();
124
+ return (0, core_2.bytesToHex)((0, core_2.serializeMMRProof)(proof)).toLowerCase();
114
125
  }
115
126
  /** Padded (power-of-two) MMR tree over `(pubkey, balance)` leaves. */
116
127
  function buildBalanceTree(participants) {
117
128
  if (!Array.isArray(participants) || participants.length === 0) {
118
129
  throw new Error('factory balance set requires at least one participant');
119
130
  }
120
- const tree = new core_1.MMRTree();
131
+ const tree = new core_2.MMRTree();
121
132
  for (const [i, p] of participants.entries()) {
122
133
  const raw = (p.publicKeyDigest ?? '').replace(/^0x/i, '');
123
134
  if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
@@ -126,13 +137,13 @@ function buildBalanceTree(participants) {
126
137
  if (p.contributionAmount < 0n) {
127
138
  throw new Error(`participant[${i}].contributionAmount must be non-negative`);
128
139
  }
129
- tree.addLeaf((0, core_1.createMMRDataLeafNode)((0, core_1.hexToBytes)(raw), p.contributionAmount));
140
+ tree.addLeaf((0, core_2.createMMRDataLeafNode)((0, core_2.hexToBytes)(raw), p.contributionAmount));
130
141
  }
131
142
  let size = 1;
132
143
  while (size < participants.length)
133
144
  size <<= 1;
134
145
  for (let i = participants.length; i < size; i++) {
135
- tree.addLeaf((0, core_1.createMMRDataLeafNode)(new Uint8Array(32), 0n));
146
+ tree.addLeaf((0, core_2.createMMRDataLeafNode)(new Uint8Array(32), 0n));
136
147
  }
137
148
  return tree;
138
149
  }
@@ -153,17 +164,20 @@ function factoryDistributionOutputs(participants, tokenId = '0x00') {
153
164
  if (p.contributionAmount < 0n) {
154
165
  throw new Error(`factoryDistributionOutputs: participant[${i}].contributionAmount must be non-negative`);
155
166
  }
156
- return { address: (0, core_1.wotsAddressData)(raw), amount: p.contributionAmount, tokenId };
167
+ return { address: (0, core_2.wotsAddressData)(raw), amount: p.contributionAmount, tokenId };
157
168
  });
158
169
  }
159
170
  /**
160
- * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
161
- * distribution. After the committed escape block **any** party may broadcast the
162
- * distribution (all-party `MULTISIG`), with no counterparty liveness and no
163
- * on-chain root recomputation. The committed party-set and balance roots are
164
- * pinned (`SAMESTATE`) so the set and balances cannot move.
171
+ * Pre-signed all-party distribution (RFC-048 §12.4) — kept as a **separate**
172
+ * mechanism for a dedicated distribution coin.
173
+ *
174
+ * This script authorizes the spend with `MULTISIG` after the escape height. It
175
+ * does **not** verify the payout set; allocation correctness comes from the
176
+ * pre-signed transaction that the parties exchange. Do not describe or use it as
177
+ * an allocation verifier — use `buildFactoryDistributionScript` (output-enforced)
178
+ * or the `settlement: 'full-distribution'` funding branch instead.
165
179
  */
166
- function buildFactoryDistributionScript(config) {
180
+ function buildFactoryPresignedDistributionScript(config) {
167
181
  const participants = config.participants;
168
182
  if (!Array.isArray(participants) || participants.length < 1) {
169
183
  throw new Error('buildFactoryDistributionScript requires at least one participant');
@@ -188,6 +202,81 @@ function buildFactoryDistributionScript(config) {
188
202
  `RETURN FALSE`,
189
203
  ].join('\n');
190
204
  }
205
+ /**
206
+ * OMN-058/RFC-079 §4A — output-enforced full distribution for a factory coin.
207
+ *
208
+ * After the committed escape block, any participant may settle the factory by
209
+ * paying **every** committed share. The covenant reads the shares from the spent
210
+ * coin (`PREVSTATE`), pins the output count, each destination, each amount and
211
+ * the total, so neither the broadcaster nor an outsider can redirect or resize a
212
+ * payout. One participant signature authorizes the trigger.
213
+ *
214
+ * Use `buildFactoryDistribution` to materialize the matching transaction.
215
+ */
216
+ function buildFactoryDistributionScript(config) {
217
+ const participants = config.participants;
218
+ if (!Array.isArray(participants) || participants.length < 1) {
219
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
220
+ }
221
+ const pks = participants.map((p, i) => {
222
+ if (!p.publicKeyDigest)
223
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
224
+ return kissHex(p.publicKeyDigest);
225
+ });
226
+ const payouts = participants.map((p, i) => {
227
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
228
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
229
+ throw new Error(`participant[${i}] payout address must be a 64-hex digest`);
230
+ }
231
+ return (0, core_2.wotsAddressData)(raw);
232
+ });
233
+ const escapePort = config.escapePort ?? exports.FACTORY_ESCAPE_PORT;
234
+ const count = participants.length;
235
+ const lines = [
236
+ '// Output-enforced factory distribution (OMN-058 / RFC-079 §4A)',
237
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
238
+ ' ASSERT @TOTIN EQ 1',
239
+ ' ASSERT @INPUT EQ 0',
240
+ ` ASSERT @TOTOUT EQ ${count}`,
241
+ ];
242
+ const terms = participants.map((_, k) => `PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + k})`);
243
+ lines.push(` ASSERT ${terms.join(' + ')} EQ @AMOUNT`);
244
+ participants.forEach((_, k) => {
245
+ lines.push(` ASSERT VERIFYOUT(${k} ${payouts[k]} PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + k}) @TOKENID FALSE)`);
246
+ });
247
+ lines.push(` ASSERT (${pks.map((pk) => `SIGNEDBY(${pk})`).join(' OR ')})`);
248
+ lines.push(' RETURN TRUE');
249
+ lines.push('ENDIF');
250
+ lines.push('RETURN FALSE');
251
+ return (0, core_2.toNodeScript)(lines.join('\n'));
252
+ }
253
+ /**
254
+ * OMN-060: deterministic party-set root committed by STATE(111).
255
+ * Canonical: parties sorted by id, `id:pubkeyDigest`.
256
+ */
257
+ function computeFactoryPartyRoot(participants) {
258
+ const canonical = [...participants]
259
+ .map((p) => `${p.partyId}:${p.publicKeyDigest.replace(/^0x/i, '').toLowerCase()}`)
260
+ .sort()
261
+ .join('|');
262
+ return '0x' + (0, core_2.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode('totemsdk/factory/party-root/v1|' + canonical))).toLowerCase();
263
+ }
264
+ /** OMN-060: deterministic balance root committed by STATE(112). */
265
+ function computeFactoryBalanceRoot(allocations) {
266
+ const canonical = Object.entries(allocations)
267
+ .map(([partyId, amount]) => `${partyId}:${amount.toString()}`)
268
+ .sort()
269
+ .join('|');
270
+ return '0x' + (0, core_2.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode('totemsdk/factory/balance-root/v1|' + canonical))).toLowerCase();
271
+ }
272
+ /** Committed balance-set root state variable (STATE(112)) for the funding output. */
273
+ function factoryBalanceRootStateVariable(root) {
274
+ const raw = root.replace(/^0x/i, '');
275
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
276
+ throw new Error(`factoryBalanceRootStateVariable: root must be 32 bytes of hex; got ${JSON.stringify(root)}`);
277
+ }
278
+ return { port: exports.FACTORY_BALANCE_ROOT_PORT, value: '0x' + raw, type: 'hex' };
279
+ }
191
280
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
192
281
  function factoryPartyRootStateVariable(root) {
193
282
  const raw = root.replace(/^0x/i, '');
@@ -212,10 +301,13 @@ exports.FACTORY_MAX_PARTICIPANTS = exports.MSHS_PORT_FLOOR - exports.FACTORY_BAL
212
301
  * committed share.
213
302
  */
214
303
  function factoryBalanceStateVariables(participants) {
304
+ // OMN-034: these ports are used as exact payout amounts by the unilateral
305
+ // escape script, so they must carry MiniNumber scale 44 like every coin amount.
215
306
  return participants.map((p, k) => ({
216
307
  port: exports.FACTORY_BALANCE_PORT_BASE + k,
217
308
  value: p.contributionAmount,
218
309
  type: 'number',
310
+ scale: core_2.MINIMA_DECIMALS,
219
311
  }));
220
312
  }
221
313
  /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
@@ -226,23 +318,28 @@ function factoryEscapeStateVariable(escapeBlock) {
226
318
  return { port: exports.FACTORY_ESCAPE_PORT, value: BigInt(escapeBlock), type: 'number' };
227
319
  }
228
320
  /**
229
- * Build the N-of-N MULTISIG MAST funding script for a channel factory
230
- * (RFC-039, CUSTODY-POLICY §2).
321
+ * Build the factory funding script.
231
322
  *
232
323
  * Spend paths:
233
- * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
234
- * `settlement=true` closes after minimal coinage (1 block).
235
- * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
236
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
237
- * (the spent coin's share) to its own settlement address, zero its state in
238
- * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
239
- * unchanged, and return the remainder to the factory script. Repeated
240
- * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
241
- * so the escape clock cannot be pushed by any counterparty.
324
+ * - **Cooperative / checkpoint** (any time, all parties): `MULTISIG(N …)`.
325
+ * With `enforceCheckpoints`, the successor must stay at this script, keep the
326
+ * value and advance `STATE(104)` by exactly one.
327
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any single
328
+ * party may withdraw its committed share `PREVSTATE(base+k)` to its own
329
+ * settlement address. With a remainder, the successor keeps the script, the
330
+ * other shares are untouched and the withdrawing port is zeroed.
331
+ * - **Full distribution** (`settlement: 'full-distribution'`, after the same
332
+ * block): one transaction pays **every** committed share. The covenant pins
333
+ * the output count, each destination and each amount read from `PREVSTATE`,
334
+ * so a broadcaster cannot redirect or resize a payout. One participant
335
+ * signature is enough to trigger it.
336
+ *
337
+ * The escape branches are terminal (no successor state), so the state-continuity
338
+ * assertions live in the cooperative path only.
242
339
  *
243
340
  * Minimum 2 participants required.
244
341
  */
245
- function buildFactoryScript(participants, _options = {}) {
342
+ function buildFactoryScript(participants, options = {}) {
246
343
  if (participants.length < 2) {
247
344
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
248
345
  }
@@ -251,44 +348,74 @@ function buildFactoryScript(participants, _options = {}) {
251
348
  }
252
349
  const count = participants.length;
253
350
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
254
- const payouts = participants.map((p) => (0, core_1.wotsAddressData)(p.settlementAddress ?? p.publicKeyDigest));
351
+ const payouts = participants.map((p) => (0, core_2.wotsAddressData)(p.settlementAddress ?? p.publicKeyDigest));
352
+ const enforceCheckpoints = options.enforceCheckpoints === true;
353
+ const fullDistribution = options.settlement === 'full-distribution';
255
354
  const lines = [
256
355
  'LET settlement=STATE(100)',
257
- `ASSERT SAMESTATE(${exports.FACTORY_ESCAPE_PORT} ${exports.FACTORY_ESCAPE_PORT})`,
258
- // RFC-048 §12.4/§12.5: the committed party-set root is immutable on every spend.
259
- `ASSERT SAMESTATE(${exports.FACTORY_PARTY_ROOT_PORT} ${exports.FACTORY_PARTY_ROOT_PORT})`,
260
356
  `IF @BLOCK GT PREVSTATE(${exports.FACTORY_ESCAPE_PORT}) THEN`,
261
357
  ];
358
+ if (fullDistribution) {
359
+ // OMN-058/RFC-079 §4A: output-enforced settlement. Every amount is read from
360
+ // the coin being spent, never from the transaction's own claims.
361
+ lines.push(' // Full distribution: pay every committed share in one transaction.');
362
+ lines.push(' IF @TOTIN EQ 1 THEN');
363
+ lines.push(` IF @TOTOUT EQ ${count} THEN`);
364
+ // Gate on the last payout address so a per-party escape (which leaves the
365
+ // remainder at the factory script) falls through to its own branch instead
366
+ // of failing this one.
367
+ lines.push(` IF GETOUTADDR(${count - 1}) EQ ${payouts[count - 1]} THEN`);
368
+ lines.push(' ASSERT @INPUT EQ 0');
369
+ const terms = participants.map((_, k) => `PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + k})`);
370
+ lines.push(` ASSERT ${terms.join(' + ')} EQ @AMOUNT`);
371
+ participants.forEach((_, k) => {
372
+ lines.push(` ASSERT VERIFYOUT(${k} ${payouts[k]} PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + k}) @TOKENID FALSE)`);
373
+ });
374
+ lines.push(` ASSERT (${pks.map((pk) => `SIGNEDBY(${pk})`).join(' OR ')})`);
375
+ lines.push(' RETURN TRUE');
376
+ lines.push(' ENDIF');
377
+ lines.push(' ENDIF');
378
+ lines.push(' ENDIF');
379
+ }
262
380
  participants.forEach((_, k) => {
263
381
  const port = exports.FACTORY_BALANCE_PORT_BASE + k;
264
382
  lines.push(` LET share=PREVSTATE(${port})`);
265
383
  lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
266
- lines.push(` IF share GT 0 THEN`);
384
+ lines.push(' IF share GT 0 THEN');
267
385
  lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} share @TOKENID FALSE)`);
386
+ // Whole-share exit: no successor state exists, so no remainder and no state
387
+ // continuity assertions.
388
+ lines.push(' IF @AMOUNT EQ share THEN');
389
+ lines.push(' ASSERT @TOTOUT EQ 1');
390
+ lines.push(' RETURN TRUE');
391
+ lines.push(' ENDIF');
268
392
  for (let j = 0; j < count; j++) {
269
393
  if (j === k)
270
394
  continue;
271
395
  lines.push(` ASSERT STATE(${exports.FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + j})`);
272
396
  }
273
397
  lines.push(` ASSERT STATE(${port}) EQ 0`);
274
- // Whole-share guard (mirrors the VTXO script): when the withdrawing party's
275
- // share is the entire output there is no remainder, so a 0-amount output is
276
- // never required.
277
- lines.push(` IF @AMOUNT GT share THEN`);
278
- lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)`);
279
- lines.push(' ENDIF');
280
- lines.push(' RETURN TRUE');
398
+ lines.push(' RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)');
281
399
  lines.push(' ENDIF');
282
400
  lines.push(' ENDIF');
283
401
  });
284
402
  lines.push('ENDIF');
403
+ // Cooperative path: the successor keeps the escape clock and the party set.
404
+ lines.push(`ASSERT SAMESTATE(${exports.FACTORY_ESCAPE_PORT} ${exports.FACTORY_ESCAPE_PORT})`);
405
+ lines.push(`ASSERT SAMESTATE(${exports.FACTORY_PARTY_ROOT_PORT} ${exports.FACTORY_PARTY_ROOT_PORT})`);
285
406
  lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
286
407
  lines.push('IF settlement THEN');
287
408
  lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
288
409
  lines.push('ELSE');
410
+ if (enforceCheckpoints) {
411
+ // Checkpoint continuity: same script, same value, sequence advanced by one.
412
+ lines.push(` ASSERT STATE(${exports.FACTORY_CHECKPOINT_SEQUENCE_PORT}) EQ INC(PREVSTATE(${exports.FACTORY_CHECKPOINT_SEQUENCE_PORT}))`);
413
+ lines.push(' ASSERT VERIFYOUT(@INPUT @ADDRESS @AMOUNT @TOKENID TRUE)');
414
+ }
289
415
  lines.push(' RETURN TRUE');
290
416
  lines.push('ENDIF');
291
- return (0, core_1.toNodeScript)(lines.join('\n'));
417
+ lines.push('RETURN FALSE');
418
+ return (0, core_2.toNodeScript)(lines.join('\n'));
292
419
  }
293
420
  function normalizeScript(script) {
294
421
  return script.trim().toUpperCase();
@@ -92,6 +92,13 @@ export interface FactoryLogEntry {
92
92
  allocations: Record<string, bigint>;
93
93
  virtualChannelIds: string[];
94
94
  }
95
+ /**
96
+ * OMN-095: the two production capability levels of a factory.
97
+ *
98
+ * `checkpoint` is the only mode that can back a unilateral exit. `none` is a
99
+ * release restriction, not an equivalent alternative.
100
+ */
101
+ export type FactoryAllocationEnforcement = 'checkpoint' | 'none';
95
102
  export interface ChannelFactory {
96
103
  factoryId: string;
97
104
  participants: FactoryParticipant[];
@@ -109,6 +116,25 @@ export interface ChannelFactory {
109
116
  allocations: Record<string, bigint>;
110
117
  /** Currently open virtual channels backed by this factory's shared UTXO. */
111
118
  virtualChannels: OmniaChannel[];
119
+ /**
120
+ * OMN-058: the covenant only permits cooperative spends that recreate the
121
+ * coin at the same script/value with the checkpoint sequence advanced
122
+ * (`enforceCheckpoints`). When set, off-chain allocation changes (virtual
123
+ * channels) are refused until they can be committed as a checkpoint, so a
124
+ * unilateral escape can never pay a stale split.
125
+ */
126
+ enforceCheckpoints?: boolean;
127
+ /**
128
+ * OMN-095: what a participant's latest allocation is enforceable to.
129
+ *
130
+ * - `checkpoint` — the covenant only accepts a same-script, same-value
131
+ * successor whose sequence advanced by one, so a unilateral exit pays the
132
+ * latest **confirmed** allocation.
133
+ * - `none` — the legacy off-chain mode. The timeout escape pays the original
134
+ * funding split, so a newer off-chain allocation is *not* unilaterally
135
+ * enforceable. Creating this mode requires an explicit opt-in.
136
+ */
137
+ allocationEnforcement?: FactoryAllocationEnforcement;
112
138
  /** Monotonically increasing. Incremented on every committed state transition. */
113
139
  currentSequence: number;
114
140
  status: FactoryStatus;
@@ -58,6 +58,14 @@ function buildVirtualChannelOpen(factory, parties, amounts, channelId) {
58
58
  if (factory.status !== 'active') {
59
59
  throw new Error(`openVirtualChannel requires factory status 'active', got '${factory.status}'`);
60
60
  }
61
+ if (factory.enforceCheckpoints) {
62
+ // OMN-058: an off-chain allocation change would leave the on-chain coin
63
+ // paying the previous split. Refuse until the change can be committed as a
64
+ // checkpoint transaction (same script, same value, sequence + 1).
65
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: opening a virtual channel changes the committed allocation `
66
+ + 'and must be committed with a factory checkpoint transaction first. '
67
+ + 'Create the factory with { enforceCheckpoints: false } only for a factory that will not rely on unilateral exits.');
68
+ }
61
69
  const [partyAId, partyBId] = parties;
62
70
  const amountA = amounts[partyAId] ?? 0n;
63
71
  const amountB = amounts[partyBId] ?? 0n;
@@ -230,6 +238,10 @@ function buildVirtualChannelClose(factory, channel) {
230
238
  const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
231
239
  if (!existing)
232
240
  throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
241
+ if (factory.enforceCheckpoints) {
242
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: closing a virtual channel changes the committed allocation `
243
+ + 'and must be committed with a factory checkpoint transaction first.');
244
+ }
233
245
  const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
234
246
  const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
235
247
  if (finalSum !== channel.totalValue) {
@@ -0,0 +1,47 @@
1
+ /**
2
+ * OMN-058 / RFC-079 §4A — output-enforced full distribution.
3
+ *
4
+ * The covenant built by `buildFactoryDistributionScript` (and the
5
+ * `settlement: 'full-distribution'` funding branch) pays every committed share
6
+ * of the *spent* coin. This module materializes the matching transaction from
7
+ * the factory's authoritative allocation, so the SDK cannot build a payout set
8
+ * the covenant would reject.
9
+ *
10
+ * Scope: the latest **confirmed** allocation (funding coin or checkpoint). A
11
+ * newer off-chain state is not covered until the contestable protocol lands.
12
+ */
13
+ import type { OmniaTxDraft, TxOutputDraft } from '@totemsdk/omnia';
14
+ import type { ChannelFactory } from './types.js';
15
+ export interface FactoryDistributionEntry extends TxOutputDraft {
16
+ partyId: string;
17
+ }
18
+ export interface FactoryDistribution {
19
+ draft: OmniaTxDraft;
20
+ outputs: FactoryDistributionEntry[];
21
+ /** Total value distributed (atoms). */
22
+ total: bigint;
23
+ }
24
+ /**
25
+ * Refuse to distribute while the factory still backs open virtual channels: the
26
+ * distribution covenant pays only the participant shares, so a VC reserve would
27
+ * be stranded or, worse, paid to the wrong party.
28
+ */
29
+ export declare function assertFactoryDistributable(factory: ChannelFactory): void;
30
+ /**
31
+ * The exact payout set for the current committed allocation, in participant
32
+ * order. Addresses default to the participant settlement address.
33
+ */
34
+ export declare function factoryDistributionPayouts(factory: ChannelFactory): Array<{
35
+ partyId: string;
36
+ address: string;
37
+ amount: bigint;
38
+ }>;
39
+ /**
40
+ * Build the distribution transaction for the factory coin. The output order
41
+ * matches the participant order used by the covenant, and every amount comes
42
+ * from the committed allocation.
43
+ */
44
+ export declare function buildFactoryDistribution(factory: ChannelFactory, params: {
45
+ fundingCoinId: string;
46
+ fundingAddress?: string;
47
+ }): FactoryDistribution;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * OMN-058 / RFC-079 §4A — output-enforced full distribution.
3
+ *
4
+ * The covenant built by `buildFactoryDistributionScript` (and the
5
+ * `settlement: 'full-distribution'` funding branch) pays every committed share
6
+ * of the *spent* coin. This module materializes the matching transaction from
7
+ * the factory's authoritative allocation, so the SDK cannot build a payout set
8
+ * the covenant would reject.
9
+ *
10
+ * Scope: the latest **confirmed** allocation (funding coin or checkpoint). A
11
+ * newer off-chain state is not covered until the contestable protocol lands.
12
+ */
13
+ import { wotsAddressData } from '@totemsdk/core';
14
+ /**
15
+ * Refuse to distribute while the factory still backs open virtual channels: the
16
+ * distribution covenant pays only the participant shares, so a VC reserve would
17
+ * be stranded or, worse, paid to the wrong party.
18
+ */
19
+ export function assertFactoryDistributable(factory) {
20
+ const open = (factory.virtualChannels ?? []).filter((channel) => channel.status !== 'closed' && channel.totalValue > 0n);
21
+ if (open.length > 0) {
22
+ const ids = open.map((channel) => channel.channelId).join(', ');
23
+ throw new Error(`factory ${factory.factoryId} cannot be distributed while ${open.length} virtual channel(s) hold value (${ids}); `
24
+ + 'settle them to separately enforceable outputs first');
25
+ }
26
+ }
27
+ /**
28
+ * The exact payout set for the current committed allocation, in participant
29
+ * order. Addresses default to the participant settlement address.
30
+ */
31
+ export function factoryDistributionPayouts(factory) {
32
+ const participants = factory.participants ?? [];
33
+ if (participants.length === 0) {
34
+ throw new Error(`factory ${factory.factoryId} has no participants`);
35
+ }
36
+ let sum = 0n;
37
+ const payouts = participants.map((participant, index) => {
38
+ const amount = factory.allocations?.[participant.partyId] ?? 0n;
39
+ if (amount < 0n) {
40
+ throw new Error(`allocation for ${participant.partyId} must be non-negative`);
41
+ }
42
+ // The covenant is built once, at funding, and pins one output per
43
+ // participant (`@TOTOUT EQ N`) with `VERIFYOUT(k … PREVSTATE(port))`. A
44
+ // zero committed share would require a zero-value output, which Minima
45
+ // rejects (`0 < amount`), so the branch cannot settle. Fail closed with the
46
+ // actionable alternative instead of building an invalid transaction.
47
+ if (amount === 0n) {
48
+ throw new Error(`factory ${factory.factoryId} cannot distribute: participant ${participant.partyId} has a zero committed share `
49
+ + 'and the distribution covenant requires a non-zero output for every participant. '
50
+ + 'Rebalance with a checkpoint, or use the per-party escape for the other shares.');
51
+ }
52
+ sum += amount;
53
+ const raw = (participant.settlementAddress ?? participant.publicKeyDigest ?? '').replace(/^0x/i, '');
54
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
55
+ throw new Error(`participant[${index}] payout address must be a 64-hex digest`);
56
+ }
57
+ return { partyId: participant.partyId, address: wotsAddressData(raw), amount };
58
+ });
59
+ const vcReserve = (factory.virtualChannels ?? [])
60
+ .filter((channel) => channel.status !== 'closed')
61
+ .reduce((total, channel) => total + channel.totalValue, 0n);
62
+ if (sum + vcReserve !== factory.totalValue) {
63
+ throw new Error(`factory allocations (${sum}) plus virtual-channel reserves (${vcReserve}) do not equal the factory total (${factory.totalValue})`);
64
+ }
65
+ return payouts;
66
+ }
67
+ /**
68
+ * Build the distribution transaction for the factory coin. The output order
69
+ * matches the participant order used by the covenant, and every amount comes
70
+ * from the committed allocation.
71
+ */
72
+ export function buildFactoryDistribution(factory, params) {
73
+ assertFactoryDistributable(factory);
74
+ if (!params.fundingCoinId) {
75
+ throw new Error('buildFactoryDistribution requires the factory funding coin id');
76
+ }
77
+ const address = params.fundingAddress ?? factory.fundingAddress;
78
+ if (!address) {
79
+ throw new Error('buildFactoryDistribution requires the factory funding address');
80
+ }
81
+ const payouts = factoryDistributionPayouts(factory);
82
+ const total = payouts.reduce((sum, payout) => sum + payout.amount, 0n);
83
+ const outputs = payouts.map((payout) => ({
84
+ partyId: payout.partyId,
85
+ address: payout.address,
86
+ amount: payout.amount,
87
+ tokenId: factory.tokenId,
88
+ storeState: false,
89
+ stateVariables: [],
90
+ }));
91
+ const draft = {
92
+ type: 'settlement',
93
+ inputs: [{
94
+ coinId: params.fundingCoinId,
95
+ address,
96
+ amount: factory.totalValue,
97
+ tokenId: factory.tokenId,
98
+ scriptHex: '',
99
+ storeState: true,
100
+ }],
101
+ outputs,
102
+ storeState: false,
103
+ stateVariables: [],
104
+ };
105
+ return { draft, outputs, total };
106
+ }
package/dist/factory.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ChainStateProvider } from '@totemsdk/chain-provider';
2
2
  import type { ChannelFactory, FactoryParticipant, FactoryFundingMaterial, WotsLeaseBundle } from './types.js';
3
+ import { buildAndHashFactoryScript } from './script.js';
3
4
  /**
4
5
  * Enforce the factory's balance conservation invariant:
5
6
  * sum(allocations) + sum(virtualChannel.totalValue) === totalValue
@@ -38,7 +39,7 @@ export declare function enforceConservation(factory: ChannelFactory): void;
38
39
  * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
39
40
  * Defaults to 0.
40
41
  */
41
- export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
42
+ export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[], scriptOptions?: Parameters<typeof buildAndHashFactoryScript>[1]): Promise<ChannelFactory>;
42
43
  /**
43
44
  * Sign the opening commitment for a plan and record the proposer's signature.
44
45
  * Nothing is broadcast and no funding signature is requested, so callers can
@@ -59,6 +60,12 @@ export interface FactoryOpeningPlan {
59
60
  fundingDigest?: Uint8Array;
60
61
  fundingCoinId?: string;
61
62
  fundingMaterials?: FactoryFundingMaterial[];
63
+ /** State variables seeded into the funding output (OMN-060 roots included). */
64
+ fundingStateVariables?: Array<{
65
+ port: number;
66
+ value: string | bigint;
67
+ type: string;
68
+ }>;
62
69
  onChain: boolean;
63
70
  }
64
71
  export interface FinalizeFactoryOpeningOptions {
@@ -66,12 +73,23 @@ export interface FinalizeFactoryOpeningOptions {
66
73
  fundingSignatures?: Record<string, Uint8Array>;
67
74
  /** Factory opening signatures to record on the proposal. */
68
75
  openingSignatures: Record<string, Uint8Array>;
76
+ /**
77
+ * OMN-063: confirmations required before an on-chain factory becomes active.
78
+ * Default 1. A factory whose funding cannot be observed at depth stays
79
+ * `opening` instead of being advertised as operational.
80
+ */
81
+ minConfirmations?: number;
69
82
  }
70
83
  /**
71
84
  * Build a factory and (when every participant supplies a funding coin) its
72
85
  * deterministic funding draft, without signing or broadcasting.
73
86
  */
74
- export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[]): Promise<FactoryOpeningPlan>;
87
+ export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[],
88
+ /**
89
+ * OMN-058: `enforceCheckpoints` uses the checkpoint-mode covenant, so every
90
+ * allocation change must consume and recreate the factory coin (RFC-079 §4).
91
+ */
92
+ scriptOptions?: Parameters<typeof buildAndHashFactoryScript>[1]): Promise<FactoryOpeningPlan>;
75
93
  /**
76
94
  * Broadcast the prepared factory funding (when on-chain) and record opening
77
95
  * signatures. When every participant signature is supplied the factory commits.