@totemsdk/omnia-factory 0.5.4 → 0.6.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.
@@ -146,8 +146,9 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
146
146
  // All parties co-sign the TX digest — the exact on-chain TX structure.
147
147
  pendingCommitment = (0, omnia_1.computeTxDraftDigest)(fundingDraft);
148
148
  const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
149
- const txBody = (0, txpow_1.serializeTxBody)(draftBytes, new Uint8Array(0));
150
- const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
149
+ const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
150
+ const txBody = (0, txpow_1.serializeTxBody)(draftBytes, new Uint8Array(0), { txnDifficulty });
151
+ const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
151
152
  const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
152
153
  await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
153
154
  fundingTxId = Buffer.from(mined.txpowId).toString('hex');
@@ -1,6 +1,7 @@
1
1
  export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
2
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
3
3
  export { computeFactoryStateCommitment } from './commitment.js';
4
+ export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
4
5
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
6
  export type { FactoryOpeningSignature } from './factory.js';
6
7
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
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.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.MSHS_PORT_FLOOR = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
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.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;
4
4
  var script_js_1 = require("./script.js");
5
5
  Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
6
6
  Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
@@ -11,11 +11,14 @@ Object.defineProperty(exports, "factoryPartyRootStateVariable", { enumerable: tr
11
11
  Object.defineProperty(exports, "factoryPartyProof", { enumerable: true, get: function () { return script_js_1.factoryPartyProof; } });
12
12
  Object.defineProperty(exports, "factoryBalanceSetRoot", { enumerable: true, get: function () { return script_js_1.factoryBalanceSetRoot; } });
13
13
  Object.defineProperty(exports, "factoryBalanceProof", { enumerable: true, get: function () { return script_js_1.factoryBalanceProof; } });
14
+ Object.defineProperty(exports, "factoryDistributionOutputs", { enumerable: true, get: function () { return script_js_1.factoryDistributionOutputs; } });
15
+ Object.defineProperty(exports, "buildFactoryDistributionScript", { enumerable: true, get: function () { return script_js_1.buildFactoryDistributionScript; } });
14
16
  Object.defineProperty(exports, "FACTORY_BALANCE_PORT_BASE", { enumerable: true, get: function () { return script_js_1.FACTORY_BALANCE_PORT_BASE; } });
15
17
  Object.defineProperty(exports, "FACTORY_ESCAPE_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_PORT; } });
16
18
  Object.defineProperty(exports, "FACTORY_ESCAPE_DELAY_BLOCKS", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS; } });
17
19
  Object.defineProperty(exports, "FACTORY_MAX_PARTICIPANTS", { enumerable: true, get: function () { return script_js_1.FACTORY_MAX_PARTICIPANTS; } });
18
20
  Object.defineProperty(exports, "FACTORY_PARTY_ROOT_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_PARTY_ROOT_PORT; } });
21
+ Object.defineProperty(exports, "FACTORY_BALANCE_ROOT_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_BALANCE_ROOT_PORT; } });
19
22
  Object.defineProperty(exports, "MSHS_PORT_FLOOR", { enumerable: true, get: function () { return script_js_1.MSHS_PORT_FLOOR; } });
20
23
  Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: function () { return script_js_1.scriptAddress; } });
21
24
  Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
@@ -12,6 +12,11 @@ export declare const FACTORY_ESCAPE_PORT = 103;
12
12
  * (proof-based) scaling.
13
13
  */
14
14
  export declare const FACTORY_PARTY_ROOT_PORT = 111;
15
+ /**
16
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
17
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
18
+ */
19
+ export declare const FACTORY_BALANCE_ROOT_PORT = 112;
15
20
  /** MMR root (hex, no `0x`) over the participants' public-key digests.
16
21
  *
17
22
  * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
@@ -43,6 +48,36 @@ export declare function factoryBalanceSetRoot(participants: FactoryParticipant[]
43
48
  * balance escape (leaf sum = the participant's balance).
44
49
  */
45
50
  export declare function factoryBalanceProof(participants: FactoryParticipant[], index: number): string;
51
+ export interface FactoryDistributionOutput {
52
+ /** Payout destination (hex pubkey digest). */
53
+ address: string;
54
+ /** Committed balance (atoms). */
55
+ amount: bigint;
56
+ tokenId: string;
57
+ }
58
+ /**
59
+ * The exact payout set the pre-signed all-party distribution must contain — one
60
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
61
+ * equals `factoryBalanceSetRoot(...).rootSum`.
62
+ */
63
+ export declare function factoryDistributionOutputs(participants: FactoryParticipant[], tokenId?: string): FactoryDistributionOutput[];
64
+ export interface FactoryDistributionScriptConfig {
65
+ participants: FactoryParticipant[];
66
+ /** State port carrying the escape block. Default `FACTORY_ESCAPE_PORT` (103). */
67
+ escapePort?: number;
68
+ /** State port carrying the committed party-set root. Default `FACTORY_PARTY_ROOT_PORT` (111). */
69
+ partyRootPort?: number;
70
+ /** State port carrying the committed balance set-root. Default `FACTORY_BALANCE_ROOT_PORT` (112). */
71
+ balanceRootPort?: number;
72
+ }
73
+ /**
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.
79
+ */
80
+ export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
46
81
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
47
82
  export declare function factoryPartyRootStateVariable(root: string): {
48
83
  port: number;
@@ -85,7 +120,7 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
85
120
  *
86
121
  * Spend paths:
87
122
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
88
- * `SETTLEMENT=true` closes after minimal coinage (1 block).
123
+ * `settlement=true` closes after minimal coinage (1 block).
89
124
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
90
125
  * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
91
126
  * (the spent coin's share) to its own settlement address, zero its state in
@@ -1,10 +1,12 @@
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_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_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
+ exports.factoryDistributionOutputs = factoryDistributionOutputs;
9
+ exports.buildFactoryDistributionScript = buildFactoryDistributionScript;
8
10
  exports.factoryPartyRootStateVariable = factoryPartyRootStateVariable;
9
11
  exports.factoryBalanceStateVariables = factoryBalanceStateVariables;
10
12
  exports.factoryEscapeStateVariable = factoryEscapeStateVariable;
@@ -16,11 +18,11 @@ const scripts_1 = require("@totemsdk/core/scripts");
16
18
  const core_1 = require("@totemsdk/core");
17
19
  /**
18
20
  * Normalize a hex public key digest to the KISSVM-compatible format:
19
- * strip leading 0x/0X and render as upper-case hex with leading '0X'.
21
+ * strip leading 0x/0X and render as upper-case hex with a lowercase 0x prefix.
20
22
  */
21
23
  function kissHex(hex) {
22
24
  const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
23
- return '0X' + raw.toUpperCase();
25
+ return '0x' + raw.toUpperCase();
24
26
  }
25
27
  /** Blocks after the funding tip at which the unilateral escape opens. */
26
28
  exports.FACTORY_ESCAPE_DELAY_BLOCKS = 256;
@@ -35,6 +37,11 @@ exports.FACTORY_ESCAPE_PORT = 103;
35
37
  * (proof-based) scaling.
36
38
  */
37
39
  exports.FACTORY_PARTY_ROOT_PORT = 111;
40
+ /**
41
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
42
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
43
+ */
44
+ exports.FACTORY_BALANCE_ROOT_PORT = 112;
38
45
  /** Public-key digests for the party set, padded to a power of two (Minima MMR). */
39
46
  function padPartySet(participants) {
40
47
  if (!Array.isArray(participants) || participants.length === 0) {
@@ -129,6 +136,58 @@ function buildBalanceTree(participants) {
129
136
  }
130
137
  return tree;
131
138
  }
139
+ /**
140
+ * The exact payout set the pre-signed all-party distribution must contain — one
141
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
142
+ * equals `factoryBalanceSetRoot(...).rootSum`.
143
+ */
144
+ function factoryDistributionOutputs(participants, tokenId = '0x00') {
145
+ if (!Array.isArray(participants) || participants.length === 0) {
146
+ throw new Error('factoryDistributionOutputs requires at least one participant');
147
+ }
148
+ return participants.map((p, i) => {
149
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
150
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
151
+ throw new Error(`factoryDistributionOutputs: participant[${i}] payout address must be a 64-hex digest`);
152
+ }
153
+ if (p.contributionAmount < 0n) {
154
+ throw new Error(`factoryDistributionOutputs: participant[${i}].contributionAmount must be non-negative`);
155
+ }
156
+ return { address: (0, core_1.wotsAddressData)(raw), amount: p.contributionAmount, tokenId };
157
+ });
158
+ }
159
+ /**
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.
165
+ */
166
+ function buildFactoryDistributionScript(config) {
167
+ const participants = config.participants;
168
+ if (!Array.isArray(participants) || participants.length < 1) {
169
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
170
+ }
171
+ const pks = participants.map((p, i) => {
172
+ if (!p.publicKeyDigest)
173
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
174
+ return kissHex(p.publicKeyDigest);
175
+ });
176
+ const escapePort = config.escapePort ?? exports.FACTORY_ESCAPE_PORT;
177
+ const partyRootPort = config.partyRootPort ?? exports.FACTORY_PARTY_ROOT_PORT;
178
+ const balanceRootPort = config.balanceRootPort ?? exports.FACTORY_BALANCE_ROOT_PORT;
179
+ return [
180
+ '// Scalable factory escape — pre-signed all-party distribution (RFC-048 §12.4)',
181
+ `ASSERT SAMESTATE(${escapePort} ${escapePort})`,
182
+ `ASSERT SAMESTATE(${partyRootPort} ${partyRootPort})`,
183
+ `ASSERT SAMESTATE(${balanceRootPort} ${balanceRootPort})`,
184
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
185
+ ` ASSERT MULTISIG(${participants.length} ${pks.join(' ')})`,
186
+ ` RETURN TRUE`,
187
+ `ENDIF`,
188
+ `RETURN FALSE`,
189
+ ].join('\n');
190
+ }
132
191
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
133
192
  function factoryPartyRootStateVariable(root) {
134
193
  const raw = root.replace(/^0x/i, '');
@@ -172,7 +231,7 @@ function factoryEscapeStateVariable(escapeBlock) {
172
231
  *
173
232
  * Spend paths:
174
233
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
175
- * `SETTLEMENT=true` closes after minimal coinage (1 block).
234
+ * `settlement=true` closes after minimal coinage (1 block).
176
235
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
177
236
  * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
178
237
  * (the spent coin's share) to its own settlement address, zero its state in
@@ -192,9 +251,9 @@ function buildFactoryScript(participants, _options = {}) {
192
251
  }
193
252
  const count = participants.length;
194
253
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
195
- const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
254
+ const payouts = participants.map((p) => (0, core_1.wotsAddressData)(p.settlementAddress ?? p.publicKeyDigest));
196
255
  const lines = [
197
- 'LET SETTLEMENT=STATE(100)',
256
+ 'LET settlement=STATE(100)',
198
257
  `ASSERT SAMESTATE(${exports.FACTORY_ESCAPE_PORT} ${exports.FACTORY_ESCAPE_PORT})`,
199
258
  // RFC-048 §12.4/§12.5: the committed party-set root is immutable on every spend.
200
259
  `ASSERT SAMESTATE(${exports.FACTORY_PARTY_ROOT_PORT} ${exports.FACTORY_PARTY_ROOT_PORT})`,
@@ -202,10 +261,10 @@ function buildFactoryScript(participants, _options = {}) {
202
261
  ];
203
262
  participants.forEach((_, k) => {
204
263
  const port = exports.FACTORY_BALANCE_PORT_BASE + k;
205
- lines.push(` LET SHARE${k}=PREVSTATE(${port})`);
264
+ lines.push(` LET share=PREVSTATE(${port})`);
206
265
  lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
207
- lines.push(` IF SHARE${k} GT 0 THEN`);
208
- lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
266
+ lines.push(` IF share GT 0 THEN`);
267
+ lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} share @TOKENID FALSE)`);
209
268
  for (let j = 0; j < count; j++) {
210
269
  if (j === k)
211
270
  continue;
@@ -215,8 +274,8 @@ function buildFactoryScript(participants, _options = {}) {
215
274
  // Whole-share guard (mirrors the VTXO script): when the withdrawing party's
216
275
  // share is the entire output there is no remainder, so a 0-amount output is
217
276
  // never required.
218
- lines.push(` IF @AMOUNT GT SHARE${k} THEN`);
219
- lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
277
+ lines.push(` IF @AMOUNT GT share THEN`);
278
+ lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)`);
220
279
  lines.push(' ENDIF');
221
280
  lines.push(' RETURN TRUE');
222
281
  lines.push(' ENDIF');
@@ -224,12 +283,12 @@ function buildFactoryScript(participants, _options = {}) {
224
283
  });
225
284
  lines.push('ENDIF');
226
285
  lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
227
- lines.push('IF SETTLEMENT THEN');
286
+ lines.push('IF settlement THEN');
228
287
  lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
229
288
  lines.push('ELSE');
230
289
  lines.push(' RETURN TRUE');
231
290
  lines.push('ENDIF');
232
- return lines.join('\n');
291
+ return (0, core_1.toNodeScript)(lines.join('\n'));
233
292
  }
234
293
  function normalizeScript(script) {
235
294
  return script.trim().toUpperCase();
@@ -123,8 +123,9 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
123
123
  };
124
124
  if (chainProvider) {
125
125
  const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(draft.settlementDraft);
126
- const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes);
127
- const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
126
+ const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
127
+ const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
128
+ const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
128
129
  const fullTxPoW = (0, wasm_1.concatBytes)((0, wasm_1.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
129
130
  await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
130
131
  payload.txpowId = Buffer.from(mined.txpowId).toString('hex');
package/dist/factory.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { sha3_256 } from '@totemsdk/core/wasm';
2
2
  import { concatBytes } from '@totemsdk/core/wasm';
3
3
  import { buildFundingTx, omniaDraftToMinimaBytes, computeTxDraftDigest, verifyChannelSignature, } from '@totemsdk/omnia';
4
- import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
4
+ import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
5
5
  import { buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS } from './script.js';
6
6
  import { computeFactoryStateCommitment } from './commitment.js';
7
7
  // ─── Balance conservation ────────────────────────────────────────────────────
@@ -137,8 +137,9 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
137
137
  // All parties co-sign the TX digest — the exact on-chain TX structure.
138
138
  pendingCommitment = computeTxDraftDigest(fundingDraft);
139
139
  const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
140
- const txBody = serializeTxBody(draftBytes, new Uint8Array(0));
141
- const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
140
+ const txnDifficulty = await resolveTxPowTarget(chainProvider);
141
+ const txBody = serializeTxBody(draftBytes, new Uint8Array(0), { txnDifficulty });
142
+ const mined = await mineTxPoW(txBody, txnDifficulty);
142
143
  const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
143
144
  await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
144
145
  fundingTxId = Buffer.from(mined.txpowId).toString('hex');
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
2
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
3
3
  export { computeFactoryStateCommitment } from './commitment.js';
4
+ export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
4
5
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
6
  export type { FactoryOpeningSignature } from './factory.js';
6
7
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
1
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
2
2
  export { computeFactoryStateCommitment } from './commitment.js';
3
3
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
4
4
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
package/dist/script.d.ts CHANGED
@@ -12,6 +12,11 @@ export declare const FACTORY_ESCAPE_PORT = 103;
12
12
  * (proof-based) scaling.
13
13
  */
14
14
  export declare const FACTORY_PARTY_ROOT_PORT = 111;
15
+ /**
16
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
17
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
18
+ */
19
+ export declare const FACTORY_BALANCE_ROOT_PORT = 112;
15
20
  /** MMR root (hex, no `0x`) over the participants' public-key digests.
16
21
  *
17
22
  * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
@@ -43,6 +48,36 @@ export declare function factoryBalanceSetRoot(participants: FactoryParticipant[]
43
48
  * balance escape (leaf sum = the participant's balance).
44
49
  */
45
50
  export declare function factoryBalanceProof(participants: FactoryParticipant[], index: number): string;
51
+ export interface FactoryDistributionOutput {
52
+ /** Payout destination (hex pubkey digest). */
53
+ address: string;
54
+ /** Committed balance (atoms). */
55
+ amount: bigint;
56
+ tokenId: string;
57
+ }
58
+ /**
59
+ * The exact payout set the pre-signed all-party distribution must contain — one
60
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
61
+ * equals `factoryBalanceSetRoot(...).rootSum`.
62
+ */
63
+ export declare function factoryDistributionOutputs(participants: FactoryParticipant[], tokenId?: string): FactoryDistributionOutput[];
64
+ export interface FactoryDistributionScriptConfig {
65
+ participants: FactoryParticipant[];
66
+ /** State port carrying the escape block. Default `FACTORY_ESCAPE_PORT` (103). */
67
+ escapePort?: number;
68
+ /** State port carrying the committed party-set root. Default `FACTORY_PARTY_ROOT_PORT` (111). */
69
+ partyRootPort?: number;
70
+ /** State port carrying the committed balance set-root. Default `FACTORY_BALANCE_ROOT_PORT` (112). */
71
+ balanceRootPort?: number;
72
+ }
73
+ /**
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.
79
+ */
80
+ export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
46
81
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
47
82
  export declare function factoryPartyRootStateVariable(root: string): {
48
83
  port: number;
@@ -85,7 +120,7 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
85
120
  *
86
121
  * Spend paths:
87
122
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
88
- * `SETTLEMENT=true` closes after minimal coinage (1 block).
123
+ * `settlement=true` closes after minimal coinage (1 block).
89
124
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
90
125
  * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
91
126
  * (the spent coin's share) to its own settlement address, zero its state in
package/dist/script.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { computeScriptAddress } from '@totemsdk/core/scripts';
2
- import { MMRTree, hexToBytes, bytesToHex, serializeMMRProof, createMMRDataLeafNode } from '@totemsdk/core';
2
+ import { MMRTree, hexToBytes, bytesToHex, serializeMMRProof, createMMRDataLeafNode, toNodeScript, wotsAddressData } from '@totemsdk/core';
3
3
  /**
4
4
  * Normalize a hex public key digest to the KISSVM-compatible format:
5
- * strip leading 0x/0X and render as upper-case hex with leading '0X'.
5
+ * strip leading 0x/0X and render as upper-case hex with a lowercase 0x prefix.
6
6
  */
7
7
  function kissHex(hex) {
8
8
  const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
9
- return '0X' + raw.toUpperCase();
9
+ return '0x' + raw.toUpperCase();
10
10
  }
11
11
  /** Blocks after the funding tip at which the unilateral escape opens. */
12
12
  export const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
@@ -21,6 +21,11 @@ export const FACTORY_ESCAPE_PORT = 103;
21
21
  * (proof-based) scaling.
22
22
  */
23
23
  export const FACTORY_PARTY_ROOT_PORT = 111;
24
+ /**
25
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
26
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
27
+ */
28
+ export const FACTORY_BALANCE_ROOT_PORT = 112;
24
29
  /** Public-key digests for the party set, padded to a power of two (Minima MMR). */
25
30
  function padPartySet(participants) {
26
31
  if (!Array.isArray(participants) || participants.length === 0) {
@@ -115,6 +120,58 @@ function buildBalanceTree(participants) {
115
120
  }
116
121
  return tree;
117
122
  }
123
+ /**
124
+ * The exact payout set the pre-signed all-party distribution must contain — one
125
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
126
+ * equals `factoryBalanceSetRoot(...).rootSum`.
127
+ */
128
+ export function factoryDistributionOutputs(participants, tokenId = '0x00') {
129
+ if (!Array.isArray(participants) || participants.length === 0) {
130
+ throw new Error('factoryDistributionOutputs requires at least one participant');
131
+ }
132
+ return participants.map((p, i) => {
133
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
134
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
135
+ throw new Error(`factoryDistributionOutputs: participant[${i}] payout address must be a 64-hex digest`);
136
+ }
137
+ if (p.contributionAmount < 0n) {
138
+ throw new Error(`factoryDistributionOutputs: participant[${i}].contributionAmount must be non-negative`);
139
+ }
140
+ return { address: wotsAddressData(raw), amount: p.contributionAmount, tokenId };
141
+ });
142
+ }
143
+ /**
144
+ * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
145
+ * distribution. After the committed escape block **any** party may broadcast the
146
+ * distribution (all-party `MULTISIG`), with no counterparty liveness and no
147
+ * on-chain root recomputation. The committed party-set and balance roots are
148
+ * pinned (`SAMESTATE`) so the set and balances cannot move.
149
+ */
150
+ export function buildFactoryDistributionScript(config) {
151
+ const participants = config.participants;
152
+ if (!Array.isArray(participants) || participants.length < 1) {
153
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
154
+ }
155
+ const pks = participants.map((p, i) => {
156
+ if (!p.publicKeyDigest)
157
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
158
+ return kissHex(p.publicKeyDigest);
159
+ });
160
+ const escapePort = config.escapePort ?? FACTORY_ESCAPE_PORT;
161
+ const partyRootPort = config.partyRootPort ?? FACTORY_PARTY_ROOT_PORT;
162
+ const balanceRootPort = config.balanceRootPort ?? FACTORY_BALANCE_ROOT_PORT;
163
+ return [
164
+ '// Scalable factory escape — pre-signed all-party distribution (RFC-048 §12.4)',
165
+ `ASSERT SAMESTATE(${escapePort} ${escapePort})`,
166
+ `ASSERT SAMESTATE(${partyRootPort} ${partyRootPort})`,
167
+ `ASSERT SAMESTATE(${balanceRootPort} ${balanceRootPort})`,
168
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
169
+ ` ASSERT MULTISIG(${participants.length} ${pks.join(' ')})`,
170
+ ` RETURN TRUE`,
171
+ `ENDIF`,
172
+ `RETURN FALSE`,
173
+ ].join('\n');
174
+ }
118
175
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
119
176
  export function factoryPartyRootStateVariable(root) {
120
177
  const raw = root.replace(/^0x/i, '');
@@ -158,7 +215,7 @@ export function factoryEscapeStateVariable(escapeBlock) {
158
215
  *
159
216
  * Spend paths:
160
217
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
161
- * `SETTLEMENT=true` closes after minimal coinage (1 block).
218
+ * `settlement=true` closes after minimal coinage (1 block).
162
219
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
163
220
  * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
164
221
  * (the spent coin's share) to its own settlement address, zero its state in
@@ -178,9 +235,9 @@ export function buildFactoryScript(participants, _options = {}) {
178
235
  }
179
236
  const count = participants.length;
180
237
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
181
- const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
238
+ const payouts = participants.map((p) => wotsAddressData(p.settlementAddress ?? p.publicKeyDigest));
182
239
  const lines = [
183
- 'LET SETTLEMENT=STATE(100)',
240
+ 'LET settlement=STATE(100)',
184
241
  `ASSERT SAMESTATE(${FACTORY_ESCAPE_PORT} ${FACTORY_ESCAPE_PORT})`,
185
242
  // RFC-048 §12.4/§12.5: the committed party-set root is immutable on every spend.
186
243
  `ASSERT SAMESTATE(${FACTORY_PARTY_ROOT_PORT} ${FACTORY_PARTY_ROOT_PORT})`,
@@ -188,10 +245,10 @@ export function buildFactoryScript(participants, _options = {}) {
188
245
  ];
189
246
  participants.forEach((_, k) => {
190
247
  const port = FACTORY_BALANCE_PORT_BASE + k;
191
- lines.push(` LET SHARE${k}=PREVSTATE(${port})`);
248
+ lines.push(` LET share=PREVSTATE(${port})`);
192
249
  lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
193
- lines.push(` IF SHARE${k} GT 0 THEN`);
194
- lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
250
+ lines.push(` IF share GT 0 THEN`);
251
+ lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} share @TOKENID FALSE)`);
195
252
  for (let j = 0; j < count; j++) {
196
253
  if (j === k)
197
254
  continue;
@@ -201,8 +258,8 @@ export function buildFactoryScript(participants, _options = {}) {
201
258
  // Whole-share guard (mirrors the VTXO script): when the withdrawing party's
202
259
  // share is the entire output there is no remainder, so a 0-amount output is
203
260
  // never required.
204
- lines.push(` IF @AMOUNT GT SHARE${k} THEN`);
205
- lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
261
+ lines.push(` IF @AMOUNT GT share THEN`);
262
+ lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)`);
206
263
  lines.push(' ENDIF');
207
264
  lines.push(' RETURN TRUE');
208
265
  lines.push(' ENDIF');
@@ -210,12 +267,12 @@ export function buildFactoryScript(participants, _options = {}) {
210
267
  });
211
268
  lines.push('ENDIF');
212
269
  lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
213
- lines.push('IF SETTLEMENT THEN');
270
+ lines.push('IF settlement THEN');
214
271
  lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
215
272
  lines.push('ELSE');
216
273
  lines.push(' RETURN TRUE');
217
274
  lines.push('ENDIF');
218
- return lines.join('\n');
275
+ return toNodeScript(lines.join('\n'));
219
276
  }
220
277
  export function normalizeScript(script) {
221
278
  return script.trim().toUpperCase();
@@ -1,6 +1,6 @@
1
1
  import { concatBytes } from '@totemsdk/core/wasm';
2
2
  import { serializeTxDraft, omniaDraftToMinimaBytes, computeTxDraftDigest, toRawMinima, verifyChannelSignature, } from '@totemsdk/omnia';
3
- import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
3
+ import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
4
4
  /**
5
5
  * Build the cooperative settlement TX + digest (no signing). Exported so peers
6
6
  * can independently rebuild and bind a proposal (RFC-035 B3).
@@ -115,8 +115,9 @@ export async function assembleFactorySettlement(factory, draft, signatures, chai
115
115
  };
116
116
  if (chainProvider) {
117
117
  const draftBytes = omniaDraftToMinimaBytes(draft.settlementDraft);
118
- const txBody = serializeTxBody(draftBytes, witnessBytes);
119
- const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
118
+ const txnDifficulty = await resolveTxPowTarget(chainProvider);
119
+ const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
120
+ const mined = await mineTxPoW(txBody, txnDifficulty);
120
121
  const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
121
122
  await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
122
123
  payload.txpowId = Buffer.from(mined.txpowId).toString('hex');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-factory",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "description": "Channel factory layer for Omnia — N-of-N MULTISIG funding, virtual channel management, and factory settlement",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -24,12 +24,12 @@
24
24
  "LICENSE"
25
25
  ],
26
26
  "dependencies": {
27
- "@totemsdk/omnia": "^2.0.1",
28
- "@totemsdk/core": "^1.3.0",
29
- "@totemsdk/tx-builder": "^0.2.1",
27
+ "@totemsdk/core": "^1.4.0",
28
+ "@totemsdk/omnia": "^2.2.0",
30
29
  "@totemsdk/wots-lease": "^1.0.1",
31
- "@totemsdk/txpow": "^1.0.2",
32
- "@totemsdk/chain-provider": "^0.2.1",
30
+ "@totemsdk/tx-builder": "^0.2.1",
31
+ "@totemsdk/txpow": "^1.1.0",
32
+ "@totemsdk/chain-provider": "^0.3.0",
33
33
  "@totemsdk/storage": "^0.1.0"
34
34
  },
35
35
  "devDependencies": {