@totemsdk/omnia-factory 0.7.1 → 0.8.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.
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
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.assembleVirtualChannelClose = exports.signVirtualChannelClose = exports.buildVirtualChannelClose = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.finalizeFactoryOpening = exports.buildFactoryOpening = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
3
+ exports.assembleVirtualChannelClose = exports.signVirtualChannelClose = exports.buildVirtualChannelClose = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.assertFactoryFinalized = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.finalizeFactoryOpening = exports.buildFactoryOpening = exports.proposeFactoryOpening = exports.createFactoryFromPlan = exports.createFactory = exports.factoryCheckpointSnapshot = exports.assertFactoryCheckpointTransition = exports.factoryCheckpointStateVariables = exports.buildFactoryCheckpoint = exports.factoryDistributionPayouts = exports.buildFactoryDistribution = exports.assertFactoryDistributable = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_CHECKPOINT_SEQUENCE_PORT = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryPresignedDistributionScript = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
4
+ exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = void 0;
4
5
  var script_js_1 = require("./script.js");
5
6
  Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
6
7
  Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
@@ -13,8 +14,10 @@ Object.defineProperty(exports, "factoryBalanceSetRoot", { enumerable: true, get:
13
14
  Object.defineProperty(exports, "factoryBalanceProof", { enumerable: true, get: function () { return script_js_1.factoryBalanceProof; } });
14
15
  Object.defineProperty(exports, "factoryDistributionOutputs", { enumerable: true, get: function () { return script_js_1.factoryDistributionOutputs; } });
15
16
  Object.defineProperty(exports, "buildFactoryDistributionScript", { enumerable: true, get: function () { return script_js_1.buildFactoryDistributionScript; } });
17
+ Object.defineProperty(exports, "buildFactoryPresignedDistributionScript", { enumerable: true, get: function () { return script_js_1.buildFactoryPresignedDistributionScript; } });
16
18
  Object.defineProperty(exports, "FACTORY_BALANCE_PORT_BASE", { enumerable: true, get: function () { return script_js_1.FACTORY_BALANCE_PORT_BASE; } });
17
19
  Object.defineProperty(exports, "FACTORY_ESCAPE_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_PORT; } });
20
+ Object.defineProperty(exports, "FACTORY_CHECKPOINT_SEQUENCE_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_CHECKPOINT_SEQUENCE_PORT; } });
18
21
  Object.defineProperty(exports, "FACTORY_ESCAPE_DELAY_BLOCKS", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS; } });
19
22
  Object.defineProperty(exports, "FACTORY_MAX_PARTICIPANTS", { enumerable: true, get: function () { return script_js_1.FACTORY_MAX_PARTICIPANTS; } });
20
23
  Object.defineProperty(exports, "FACTORY_PARTY_ROOT_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_PARTY_ROOT_PORT; } });
@@ -24,8 +27,19 @@ Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: functio
24
27
  Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
25
28
  var commitment_js_1 = require("./commitment.js");
26
29
  Object.defineProperty(exports, "computeFactoryStateCommitment", { enumerable: true, get: function () { return commitment_js_1.computeFactoryStateCommitment; } });
30
+ var distribution_js_1 = require("./distribution.js");
31
+ Object.defineProperty(exports, "assertFactoryDistributable", { enumerable: true, get: function () { return distribution_js_1.assertFactoryDistributable; } });
32
+ Object.defineProperty(exports, "buildFactoryDistribution", { enumerable: true, get: function () { return distribution_js_1.buildFactoryDistribution; } });
33
+ Object.defineProperty(exports, "factoryDistributionPayouts", { enumerable: true, get: function () { return distribution_js_1.factoryDistributionPayouts; } });
34
+ var checkpoint_js_1 = require("./checkpoint.js");
35
+ Object.defineProperty(exports, "buildFactoryCheckpoint", { enumerable: true, get: function () { return checkpoint_js_1.buildFactoryCheckpoint; } });
36
+ Object.defineProperty(exports, "factoryCheckpointStateVariables", { enumerable: true, get: function () { return checkpoint_js_1.factoryCheckpointStateVariables; } });
37
+ Object.defineProperty(exports, "assertFactoryCheckpointTransition", { enumerable: true, get: function () { return checkpoint_js_1.assertFactoryCheckpointTransition; } });
38
+ Object.defineProperty(exports, "factoryCheckpointSnapshot", { enumerable: true, get: function () { return checkpoint_js_1.factoryCheckpointSnapshot; } });
27
39
  var factory_js_1 = require("./factory.js");
28
40
  Object.defineProperty(exports, "createFactory", { enumerable: true, get: function () { return factory_js_1.createFactory; } });
41
+ Object.defineProperty(exports, "createFactoryFromPlan", { enumerable: true, get: function () { return factory_js_1.createFactoryFromPlan; } });
42
+ Object.defineProperty(exports, "proposeFactoryOpening", { enumerable: true, get: function () { return factory_js_1.proposeFactoryOpening; } });
29
43
  Object.defineProperty(exports, "buildFactoryOpening", { enumerable: true, get: function () { return factory_js_1.buildFactoryOpening; } });
30
44
  Object.defineProperty(exports, "finalizeFactoryOpening", { enumerable: true, get: function () { return factory_js_1.finalizeFactoryOpening; } });
31
45
  Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
@@ -34,6 +48,7 @@ Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: f
34
48
  Object.defineProperty(exports, "signFactoryOpening", { enumerable: true, get: function () { return factory_js_1.signFactoryOpening; } });
35
49
  Object.defineProperty(exports, "verifyFactorySignature", { enumerable: true, get: function () { return factory_js_1.verifyFactorySignature; } });
36
50
  Object.defineProperty(exports, "applyFactorySignature", { enumerable: true, get: function () { return factory_js_1.applyFactorySignature; } });
51
+ Object.defineProperty(exports, "assertFactoryFinalized", { enumerable: true, get: function () { return factory_js_1.assertFactoryFinalized; } });
37
52
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
38
53
  var coordination_js_1 = require("./coordination.js");
39
54
  Object.defineProperty(exports, "createFactoryCoordination", { enumerable: true, get: function () { return coordination_js_1.createFactoryCoordination; } });
@@ -3,6 +3,12 @@ import type { FactoryParticipant } from './types.js';
3
3
  export declare const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
4
4
  /** State port carrying the absolute escape block (STATE(103)). */
5
5
  export declare const FACTORY_ESCAPE_PORT = 103;
6
+ /**
7
+ * OMN-058/RFC-079 §4: checkpoint sequence (STATE(104)). Seeded at funding and
8
+ * advanced by exactly one on every checkpoint spend, so a checkpoint can never
9
+ * be replayed against a newer state.
10
+ */
11
+ export declare const FACTORY_CHECKPOINT_SEQUENCE_PORT = 104;
6
12
  /**
7
13
  * State port carrying the committed party-set root (STATE(111)) — the MMR root
8
14
  * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
@@ -71,13 +77,41 @@ export interface FactoryDistributionScriptConfig {
71
77
  balanceRootPort?: number;
72
78
  }
73
79
  /**
74
- * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
75
- * distribution. After the committed escape block **any** party may broadcast the
76
- * distribution (all-party `MULTISIG`), with no counterparty liveness and no
77
- * on-chain root recomputation. The committed party-set and balance roots are
78
- * pinned (`SAMESTATE`) so the set and balances cannot move.
80
+ * Pre-signed all-party distribution (RFC-048 §12.4) — kept as a **separate**
81
+ * mechanism for a dedicated distribution coin.
82
+ *
83
+ * This script authorizes the spend with `MULTISIG` after the escape height. It
84
+ * does **not** verify the payout set; allocation correctness comes from the
85
+ * pre-signed transaction that the parties exchange. Do not describe or use it as
86
+ * an allocation verifier — use `buildFactoryDistributionScript` (output-enforced)
87
+ * or the `settlement: 'full-distribution'` funding branch instead.
88
+ */
89
+ export declare function buildFactoryPresignedDistributionScript(config: FactoryDistributionScriptConfig): string;
90
+ /**
91
+ * OMN-058/RFC-079 §4A — output-enforced full distribution for a factory coin.
92
+ *
93
+ * After the committed escape block, any participant may settle the factory by
94
+ * paying **every** committed share. The covenant reads the shares from the spent
95
+ * coin (`PREVSTATE`), pins the output count, each destination, each amount and
96
+ * the total, so neither the broadcaster nor an outsider can redirect or resize a
97
+ * payout. One participant signature authorizes the trigger.
98
+ *
99
+ * Use `buildFactoryDistribution` to materialize the matching transaction.
79
100
  */
80
101
  export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
102
+ /**
103
+ * OMN-060: deterministic party-set root committed by STATE(111).
104
+ * Canonical: parties sorted by id, `id:pubkeyDigest`.
105
+ */
106
+ export declare function computeFactoryPartyRoot(participants: FactoryParticipant[]): string;
107
+ /** OMN-060: deterministic balance root committed by STATE(112). */
108
+ export declare function computeFactoryBalanceRoot(allocations: Record<string, bigint>): string;
109
+ /** Committed balance-set root state variable (STATE(112)) for the funding output. */
110
+ export declare function factoryBalanceRootStateVariable(root: string): {
111
+ port: number;
112
+ value: string;
113
+ type: 'hex';
114
+ };
81
115
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
82
116
  export declare function factoryPartyRootStateVariable(root: string): {
83
117
  port: number;
@@ -97,6 +131,22 @@ export declare const FACTORY_MAX_PARTICIPANTS: number;
97
131
  export interface FactoryScriptOptions {
98
132
  /** Reserved for callers; the escape block is carried in STATE(103) at funding. */
99
133
  escapeBlock?: number;
134
+ /**
135
+ * OMN-058 checkpoint mode (RFC-079 §4). When true, the cooperative branch only
136
+ * accepts a same-script, same-value successor whose sequence advanced by one.
137
+ * Every allocation change then has an on-chain artifact, and the unilateral
138
+ * escape pays the latest checkpoint instead of the original funding split.
139
+ *
140
+ * Off by default: the off-chain factory design stays available, with OMN-058
141
+ * open until the contestable protocol lands.
142
+ */
143
+ enforceCheckpoints?: boolean;
144
+ /**
145
+ * OMN-058/RFC-079 §4A: add the output-enforced full-distribution branch.
146
+ * Any participant can settle every committed share in one transaction; the
147
+ * covenant pins each destination, amount, the output count and conservation.
148
+ */
149
+ settlement?: 'per-party' | 'full-distribution';
100
150
  }
101
151
  /**
102
152
  * Per-party allocation state variables (port base+k = party k's balance), seeded
@@ -107,6 +157,7 @@ export declare function factoryBalanceStateVariables(participants: FactoryPartic
107
157
  port: number;
108
158
  value: bigint;
109
159
  type: 'number';
160
+ scale: number;
110
161
  }[];
111
162
  /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
112
163
  export declare function factoryEscapeStateVariable(escapeBlock: number): {
@@ -115,23 +166,28 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
115
166
  type: 'number';
116
167
  };
117
168
  /**
118
- * Build the N-of-N MULTISIG MAST funding script for a channel factory
119
- * (RFC-039, CUSTODY-POLICY §2).
169
+ * Build the factory funding script.
120
170
  *
121
171
  * Spend paths:
122
- * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
123
- * `settlement=true` closes after minimal coinage (1 block).
124
- * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
125
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
126
- * (the spent coin's share) to its own settlement address, zero its state in
127
- * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
128
- * unchanged, and return the remainder to the factory script. Repeated
129
- * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
130
- * so the escape clock cannot be pushed by any counterparty.
172
+ * - **Cooperative / checkpoint** (any time, all parties): `MULTISIG(N …)`.
173
+ * With `enforceCheckpoints`, the successor must stay at this script, keep the
174
+ * value and advance `STATE(104)` by exactly one.
175
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any single
176
+ * party may withdraw its committed share `PREVSTATE(base+k)` to its own
177
+ * settlement address. With a remainder, the successor keeps the script, the
178
+ * other shares are untouched and the withdrawing port is zeroed.
179
+ * - **Full distribution** (`settlement: 'full-distribution'`, after the same
180
+ * block): one transaction pays **every** committed share. The covenant pins
181
+ * the output count, each destination and each amount read from `PREVSTATE`,
182
+ * so a broadcaster cannot redirect or resize a payout. One participant
183
+ * signature is enough to trigger it.
184
+ *
185
+ * The escape branches are terminal (no successor state), so the state-continuity
186
+ * assertions live in the cooperative path only.
131
187
  *
132
188
  * Minimum 2 participants required.
133
189
  */
134
- export declare function buildFactoryScript(participants: FactoryParticipant[], _options?: FactoryScriptOptions): string;
190
+ export declare function buildFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): string;
135
191
  export declare function normalizeScript(script: string): string;
136
192
  /** Compute the SHA3-256 script-hash address for a factory script. */
137
193
  export declare function scriptAddress(script: string): string;
@@ -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();
@@ -109,6 +109,14 @@ export interface ChannelFactory {
109
109
  allocations: Record<string, bigint>;
110
110
  /** Currently open virtual channels backed by this factory's shared UTXO. */
111
111
  virtualChannels: OmniaChannel[];
112
+ /**
113
+ * OMN-058: the covenant only permits cooperative spends that recreate the
114
+ * coin at the same script/value with the checkpoint sequence advanced
115
+ * (`enforceCheckpoints`). When set, off-chain allocation changes (virtual
116
+ * channels) are refused until they can be committed as a checkpoint, so a
117
+ * unilateral escape can never pay a stale split.
118
+ */
119
+ enforceCheckpoints?: boolean;
112
120
  /** Monotonically increasing. Incremented on every committed state transition. */
113
121
  currentSequence: number;
114
122
  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;