@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/README.md CHANGED
@@ -68,3 +68,8 @@ await provider.broadcastTxPoW(settlementHex);
68
68
  - [`@totemsdk/omnia-router`](https://www.npmjs.com/package/@totemsdk/omnia-router) — route payments across factory and direct channels
69
69
  - [`@totemsdk/wots-lease`](https://www.npmjs.com/package/@totemsdk/wots-lease) — WOTS key safety for factory signing
70
70
  - [`@totemsdk/tx-builder`](https://www.npmjs.com/package/@totemsdk/tx-builder) — builds the N-of-N funding transaction
71
+
72
+
73
+ ## Testing
74
+
75
+ Tests live outside the published package in `tests/unit/omnia-factory/`. Package `test:*` scripts are repository delegates; tests are not shipped.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * OMN-058 checkpoint mode (RFC-079 §4).
3
+ *
4
+ * A checkpoint consumes the current factory coin and recreates it at the same
5
+ * script with the new allocation, an advanced sequence and refreshed
6
+ * commitments. The previous version becomes unspendable, so the unilateral
7
+ * escape always pays the latest checkpointed shares instead of the original
8
+ * funding split.
9
+ *
10
+ * This is the enforceable baseline: it costs one on-chain transaction per
11
+ * allocation change. The contestable off-chain design in RFC-079 §3 remains the
12
+ * target once its remaining preconditions are proven.
13
+ */
14
+ import type { OmniaTxDraft, StateValue, TxOutputDraft } from '@totemsdk/omnia';
15
+ import type { FactoryParticipant } from './types.js';
16
+ export interface FactoryCheckpointParams {
17
+ participants: FactoryParticipant[];
18
+ /** New per-party allocations in atoms. Must conserve `totalValue`. */
19
+ allocations: Record<string, bigint>;
20
+ tokenId: string;
21
+ tokenScale: number;
22
+ totalValue: bigint;
23
+ /** Address and coin of the factory UTXO being consumed. */
24
+ fundingAddress: string;
25
+ fundingCoinId: string;
26
+ /** Absolute escape block, carried forward from the committed state. */
27
+ escapeBlock: bigint | number;
28
+ /** New sequence; must be strictly greater than `previousSequence`. */
29
+ sequence: bigint | number;
30
+ previousSequence?: bigint | number;
31
+ /** Previous state variables of the spent coin (for PREVSTATE continuity). */
32
+ previousStateVariables?: StateValue[];
33
+ }
34
+ export interface FactoryCheckpoint {
35
+ draft: OmniaTxDraft;
36
+ output: TxOutputDraft;
37
+ stateVariables: StateValue[];
38
+ sequence: bigint;
39
+ partyRoot: string;
40
+ balanceRoot: string;
41
+ }
42
+ /**
43
+ * Build the state variables the successor factory coin must carry. Exported so
44
+ * a verifier can recompute the commitment from a candidate transition.
45
+ */
46
+ export declare function factoryCheckpointStateVariables(params: {
47
+ participants: FactoryParticipant[];
48
+ allocations: Record<string, bigint>;
49
+ tokenId: string;
50
+ totalValue: bigint;
51
+ escapeBlock: bigint | number;
52
+ sequence: bigint | number;
53
+ }): StateValue[];
54
+ /**
55
+ * Build the checkpoint transaction: one input (the factory coin), one successor
56
+ * at the same script and value, carrying the new allocation and sequence.
57
+ */
58
+ export declare function buildFactoryCheckpoint(params: FactoryCheckpointParams): FactoryCheckpoint;
59
+ export interface FactoryCheckpointSnapshot {
60
+ address: string;
61
+ tokenId: string;
62
+ totalValue: bigint;
63
+ sequence: bigint;
64
+ partyRoot: string;
65
+ balanceRoot: string;
66
+ allocations: Record<string, bigint>;
67
+ }
68
+ /**
69
+ * Validate a candidate checkpoint against the state it replaces. This is the
70
+ * rule the covenant enforces on chain; running it here lets the SDK refuse to
71
+ * build a transition the node would reject.
72
+ */
73
+ export declare function assertFactoryCheckpointTransition(before: FactoryCheckpointSnapshot, after: FactoryCheckpointSnapshot): void;
74
+ /** Snapshot helper for the state a checkpoint would produce. */
75
+ export declare function factoryCheckpointSnapshot(checkpoint: FactoryCheckpoint, participants: FactoryParticipant[]): FactoryCheckpointSnapshot;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * OMN-058 checkpoint mode (RFC-079 §4).
3
+ *
4
+ * A checkpoint consumes the current factory coin and recreates it at the same
5
+ * script with the new allocation, an advanced sequence and refreshed
6
+ * commitments. The previous version becomes unspendable, so the unilateral
7
+ * escape always pays the latest checkpointed shares instead of the original
8
+ * funding split.
9
+ *
10
+ * This is the enforceable baseline: it costs one on-chain transaction per
11
+ * allocation change. The contestable off-chain design in RFC-079 §3 remains the
12
+ * target once its remaining preconditions are proven.
13
+ */
14
+ import { MINIMA_DECIMALS } from '@totemsdk/core';
15
+ import { computeFactoryBalanceRoot, computeFactoryPartyRoot, FACTORY_BALANCE_PORT_BASE, FACTORY_BALANCE_ROOT_PORT, FACTORY_CHECKPOINT_SEQUENCE_PORT, FACTORY_ESCAPE_PORT, FACTORY_PARTY_ROOT_PORT, } from './script.js';
16
+ function toAtoms(value, label) {
17
+ const atoms = typeof value === 'bigint' ? value : BigInt(Math.trunc(value));
18
+ if (atoms < 0n)
19
+ throw new Error(`${label} must be non-negative`);
20
+ return atoms;
21
+ }
22
+ /**
23
+ * Build the state variables the successor factory coin must carry. Exported so
24
+ * a verifier can recompute the commitment from a candidate transition.
25
+ */
26
+ export function factoryCheckpointStateVariables(params) {
27
+ const { participants, allocations } = params;
28
+ if (participants.length === 0)
29
+ throw new Error('factory checkpoint requires at least one participant');
30
+ const expected = new Set(participants.map((party) => party.partyId));
31
+ const actual = Object.keys(allocations);
32
+ if (actual.length !== expected.size || actual.some((id) => !expected.has(id))) {
33
+ throw new Error('checkpoint allocations must name exactly the factory participants');
34
+ }
35
+ let sum = 0n;
36
+ const balanceVariables = participants.map((party, index) => {
37
+ const amount = allocations[party.partyId] ?? 0n;
38
+ if (amount < 0n)
39
+ throw new Error(`allocation for ${party.partyId} must be non-negative`);
40
+ sum += amount;
41
+ return {
42
+ port: FACTORY_BALANCE_PORT_BASE + index,
43
+ value: amount,
44
+ type: 'number',
45
+ // Exact payout amounts read by the escape branch: scale 44, like a coin.
46
+ scale: MINIMA_DECIMALS,
47
+ };
48
+ });
49
+ if (sum !== params.totalValue) {
50
+ throw new Error(`checkpoint allocations (${sum}) do not conserve the factory total (${params.totalValue})`);
51
+ }
52
+ return [
53
+ ...balanceVariables,
54
+ {
55
+ port: FACTORY_CHECKPOINT_SEQUENCE_PORT,
56
+ value: toAtoms(params.sequence, 'sequence'),
57
+ type: 'number',
58
+ },
59
+ {
60
+ port: FACTORY_ESCAPE_PORT,
61
+ value: toAtoms(params.escapeBlock, 'escapeBlock'),
62
+ type: 'number',
63
+ },
64
+ {
65
+ port: FACTORY_PARTY_ROOT_PORT,
66
+ value: computeFactoryPartyRoot(participants),
67
+ type: 'hex',
68
+ },
69
+ {
70
+ port: FACTORY_BALANCE_ROOT_PORT,
71
+ value: computeFactoryBalanceRoot(allocations),
72
+ type: 'hex',
73
+ },
74
+ ];
75
+ }
76
+ /**
77
+ * Build the checkpoint transaction: one input (the factory coin), one successor
78
+ * at the same script and value, carrying the new allocation and sequence.
79
+ */
80
+ export function buildFactoryCheckpoint(params) {
81
+ const sequence = toAtoms(params.sequence, 'sequence');
82
+ if (params.previousSequence !== undefined
83
+ && sequence <= toAtoms(params.previousSequence, 'previousSequence')) {
84
+ throw new Error(`checkpoint sequence ${sequence} must be greater than ${params.previousSequence}`);
85
+ }
86
+ const stateVariables = factoryCheckpointStateVariables({
87
+ participants: params.participants,
88
+ allocations: params.allocations,
89
+ tokenId: params.tokenId,
90
+ totalValue: params.totalValue,
91
+ escapeBlock: params.escapeBlock,
92
+ sequence,
93
+ });
94
+ const output = {
95
+ address: params.fundingAddress,
96
+ amount: params.totalValue,
97
+ tokenId: params.tokenId,
98
+ storeState: true,
99
+ stateVariables,
100
+ };
101
+ const draft = {
102
+ type: 'update',
103
+ inputs: [{
104
+ coinId: params.fundingCoinId,
105
+ address: params.fundingAddress,
106
+ amount: params.totalValue,
107
+ tokenId: params.tokenId,
108
+ scriptHex: '',
109
+ storeState: true,
110
+ ...(params.previousStateVariables ? { stateVariables: params.previousStateVariables } : {}),
111
+ }],
112
+ outputs: [output],
113
+ storeState: true,
114
+ stateVariables,
115
+ };
116
+ return {
117
+ draft,
118
+ output,
119
+ stateVariables,
120
+ sequence,
121
+ partyRoot: computeFactoryPartyRoot(params.participants),
122
+ balanceRoot: computeFactoryBalanceRoot(params.allocations),
123
+ };
124
+ }
125
+ /**
126
+ * Validate a candidate checkpoint against the state it replaces. This is the
127
+ * rule the covenant enforces on chain; running it here lets the SDK refuse to
128
+ * build a transition the node would reject.
129
+ */
130
+ export function assertFactoryCheckpointTransition(before, after) {
131
+ if (after.address !== before.address) {
132
+ throw new Error('factory checkpoint must stay at the same script address');
133
+ }
134
+ if (after.tokenId !== before.tokenId) {
135
+ throw new Error('factory checkpoint must preserve the token');
136
+ }
137
+ if (after.totalValue !== before.totalValue) {
138
+ throw new Error('factory checkpoint must conserve the factory value');
139
+ }
140
+ if (after.sequence <= before.sequence) {
141
+ throw new Error(`factory checkpoint sequence ${after.sequence} must advance from ${before.sequence}`);
142
+ }
143
+ if (after.partyRoot !== before.partyRoot) {
144
+ throw new Error('factory checkpoint must preserve the committed party set');
145
+ }
146
+ const beforeKeys = Object.keys(before.allocations).sort();
147
+ const afterKeys = Object.keys(after.allocations).sort();
148
+ if (beforeKeys.join(',') !== afterKeys.join(',')) {
149
+ throw new Error('factory checkpoint must preserve the participant set');
150
+ }
151
+ let sum = 0n;
152
+ for (const key of afterKeys) {
153
+ if (after.allocations[key] < 0n)
154
+ throw new Error(`allocation for ${key} must be non-negative`);
155
+ sum += after.allocations[key];
156
+ }
157
+ if (sum !== after.totalValue) {
158
+ throw new Error(`factory checkpoint allocations (${sum}) do not conserve ${after.totalValue}`);
159
+ }
160
+ if (after.balanceRoot !== computeFactoryBalanceRoot(after.allocations)) {
161
+ throw new Error('factory checkpoint balance root does not commit the new allocations');
162
+ }
163
+ }
164
+ /** Snapshot helper for the state a checkpoint would produce. */
165
+ export function factoryCheckpointSnapshot(checkpoint, participants) {
166
+ const allocations = {};
167
+ participants.forEach((party, index) => {
168
+ const variable = checkpoint.stateVariables.find((entry) => entry.port === FACTORY_BALANCE_PORT_BASE + index);
169
+ allocations[party.partyId] = BigInt((variable?.value ?? 0n));
170
+ });
171
+ return {
172
+ address: checkpoint.output.address,
173
+ tokenId: checkpoint.output.tokenId,
174
+ totalValue: checkpoint.output.amount,
175
+ sequence: checkpoint.sequence,
176
+ partyRoot: checkpoint.partyRoot,
177
+ balanceRoot: checkpoint.balanceRoot,
178
+ allocations,
179
+ };
180
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * OMN-058 checkpoint mode (RFC-079 §4).
3
+ *
4
+ * A checkpoint consumes the current factory coin and recreates it at the same
5
+ * script with the new allocation, an advanced sequence and refreshed
6
+ * commitments. The previous version becomes unspendable, so the unilateral
7
+ * escape always pays the latest checkpointed shares instead of the original
8
+ * funding split.
9
+ *
10
+ * This is the enforceable baseline: it costs one on-chain transaction per
11
+ * allocation change. The contestable off-chain design in RFC-079 §3 remains the
12
+ * target once its remaining preconditions are proven.
13
+ */
14
+ import type { OmniaTxDraft, StateValue, TxOutputDraft } from '@totemsdk/omnia';
15
+ import type { FactoryParticipant } from './types.js';
16
+ export interface FactoryCheckpointParams {
17
+ participants: FactoryParticipant[];
18
+ /** New per-party allocations in atoms. Must conserve `totalValue`. */
19
+ allocations: Record<string, bigint>;
20
+ tokenId: string;
21
+ tokenScale: number;
22
+ totalValue: bigint;
23
+ /** Address and coin of the factory UTXO being consumed. */
24
+ fundingAddress: string;
25
+ fundingCoinId: string;
26
+ /** Absolute escape block, carried forward from the committed state. */
27
+ escapeBlock: bigint | number;
28
+ /** New sequence; must be strictly greater than `previousSequence`. */
29
+ sequence: bigint | number;
30
+ previousSequence?: bigint | number;
31
+ /** Previous state variables of the spent coin (for PREVSTATE continuity). */
32
+ previousStateVariables?: StateValue[];
33
+ }
34
+ export interface FactoryCheckpoint {
35
+ draft: OmniaTxDraft;
36
+ output: TxOutputDraft;
37
+ stateVariables: StateValue[];
38
+ sequence: bigint;
39
+ partyRoot: string;
40
+ balanceRoot: string;
41
+ }
42
+ /**
43
+ * Build the state variables the successor factory coin must carry. Exported so
44
+ * a verifier can recompute the commitment from a candidate transition.
45
+ */
46
+ export declare function factoryCheckpointStateVariables(params: {
47
+ participants: FactoryParticipant[];
48
+ allocations: Record<string, bigint>;
49
+ tokenId: string;
50
+ totalValue: bigint;
51
+ escapeBlock: bigint | number;
52
+ sequence: bigint | number;
53
+ }): StateValue[];
54
+ /**
55
+ * Build the checkpoint transaction: one input (the factory coin), one successor
56
+ * at the same script and value, carrying the new allocation and sequence.
57
+ */
58
+ export declare function buildFactoryCheckpoint(params: FactoryCheckpointParams): FactoryCheckpoint;
59
+ export interface FactoryCheckpointSnapshot {
60
+ address: string;
61
+ tokenId: string;
62
+ totalValue: bigint;
63
+ sequence: bigint;
64
+ partyRoot: string;
65
+ balanceRoot: string;
66
+ allocations: Record<string, bigint>;
67
+ }
68
+ /**
69
+ * Validate a candidate checkpoint against the state it replaces. This is the
70
+ * rule the covenant enforces on chain; running it here lets the SDK refuse to
71
+ * build a transition the node would reject.
72
+ */
73
+ export declare function assertFactoryCheckpointTransition(before: FactoryCheckpointSnapshot, after: FactoryCheckpointSnapshot): void;
74
+ /** Snapshot helper for the state a checkpoint would produce. */
75
+ export declare function factoryCheckpointSnapshot(checkpoint: FactoryCheckpoint, participants: FactoryParticipant[]): FactoryCheckpointSnapshot;
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ /**
3
+ * OMN-058 checkpoint mode (RFC-079 §4).
4
+ *
5
+ * A checkpoint consumes the current factory coin and recreates it at the same
6
+ * script with the new allocation, an advanced sequence and refreshed
7
+ * commitments. The previous version becomes unspendable, so the unilateral
8
+ * escape always pays the latest checkpointed shares instead of the original
9
+ * funding split.
10
+ *
11
+ * This is the enforceable baseline: it costs one on-chain transaction per
12
+ * allocation change. The contestable off-chain design in RFC-079 §3 remains the
13
+ * target once its remaining preconditions are proven.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.factoryCheckpointStateVariables = factoryCheckpointStateVariables;
17
+ exports.buildFactoryCheckpoint = buildFactoryCheckpoint;
18
+ exports.assertFactoryCheckpointTransition = assertFactoryCheckpointTransition;
19
+ exports.factoryCheckpointSnapshot = factoryCheckpointSnapshot;
20
+ const core_1 = require("@totemsdk/core");
21
+ const script_js_1 = require("./script.js");
22
+ function toAtoms(value, label) {
23
+ const atoms = typeof value === 'bigint' ? value : BigInt(Math.trunc(value));
24
+ if (atoms < 0n)
25
+ throw new Error(`${label} must be non-negative`);
26
+ return atoms;
27
+ }
28
+ /**
29
+ * Build the state variables the successor factory coin must carry. Exported so
30
+ * a verifier can recompute the commitment from a candidate transition.
31
+ */
32
+ function factoryCheckpointStateVariables(params) {
33
+ const { participants, allocations } = params;
34
+ if (participants.length === 0)
35
+ throw new Error('factory checkpoint requires at least one participant');
36
+ const expected = new Set(participants.map((party) => party.partyId));
37
+ const actual = Object.keys(allocations);
38
+ if (actual.length !== expected.size || actual.some((id) => !expected.has(id))) {
39
+ throw new Error('checkpoint allocations must name exactly the factory participants');
40
+ }
41
+ let sum = 0n;
42
+ const balanceVariables = participants.map((party, index) => {
43
+ const amount = allocations[party.partyId] ?? 0n;
44
+ if (amount < 0n)
45
+ throw new Error(`allocation for ${party.partyId} must be non-negative`);
46
+ sum += amount;
47
+ return {
48
+ port: script_js_1.FACTORY_BALANCE_PORT_BASE + index,
49
+ value: amount,
50
+ type: 'number',
51
+ // Exact payout amounts read by the escape branch: scale 44, like a coin.
52
+ scale: core_1.MINIMA_DECIMALS,
53
+ };
54
+ });
55
+ if (sum !== params.totalValue) {
56
+ throw new Error(`checkpoint allocations (${sum}) do not conserve the factory total (${params.totalValue})`);
57
+ }
58
+ return [
59
+ ...balanceVariables,
60
+ {
61
+ port: script_js_1.FACTORY_CHECKPOINT_SEQUENCE_PORT,
62
+ value: toAtoms(params.sequence, 'sequence'),
63
+ type: 'number',
64
+ },
65
+ {
66
+ port: script_js_1.FACTORY_ESCAPE_PORT,
67
+ value: toAtoms(params.escapeBlock, 'escapeBlock'),
68
+ type: 'number',
69
+ },
70
+ {
71
+ port: script_js_1.FACTORY_PARTY_ROOT_PORT,
72
+ value: (0, script_js_1.computeFactoryPartyRoot)(participants),
73
+ type: 'hex',
74
+ },
75
+ {
76
+ port: script_js_1.FACTORY_BALANCE_ROOT_PORT,
77
+ value: (0, script_js_1.computeFactoryBalanceRoot)(allocations),
78
+ type: 'hex',
79
+ },
80
+ ];
81
+ }
82
+ /**
83
+ * Build the checkpoint transaction: one input (the factory coin), one successor
84
+ * at the same script and value, carrying the new allocation and sequence.
85
+ */
86
+ function buildFactoryCheckpoint(params) {
87
+ const sequence = toAtoms(params.sequence, 'sequence');
88
+ if (params.previousSequence !== undefined
89
+ && sequence <= toAtoms(params.previousSequence, 'previousSequence')) {
90
+ throw new Error(`checkpoint sequence ${sequence} must be greater than ${params.previousSequence}`);
91
+ }
92
+ const stateVariables = factoryCheckpointStateVariables({
93
+ participants: params.participants,
94
+ allocations: params.allocations,
95
+ tokenId: params.tokenId,
96
+ totalValue: params.totalValue,
97
+ escapeBlock: params.escapeBlock,
98
+ sequence,
99
+ });
100
+ const output = {
101
+ address: params.fundingAddress,
102
+ amount: params.totalValue,
103
+ tokenId: params.tokenId,
104
+ storeState: true,
105
+ stateVariables,
106
+ };
107
+ const draft = {
108
+ type: 'update',
109
+ inputs: [{
110
+ coinId: params.fundingCoinId,
111
+ address: params.fundingAddress,
112
+ amount: params.totalValue,
113
+ tokenId: params.tokenId,
114
+ scriptHex: '',
115
+ storeState: true,
116
+ ...(params.previousStateVariables ? { stateVariables: params.previousStateVariables } : {}),
117
+ }],
118
+ outputs: [output],
119
+ storeState: true,
120
+ stateVariables,
121
+ };
122
+ return {
123
+ draft,
124
+ output,
125
+ stateVariables,
126
+ sequence,
127
+ partyRoot: (0, script_js_1.computeFactoryPartyRoot)(params.participants),
128
+ balanceRoot: (0, script_js_1.computeFactoryBalanceRoot)(params.allocations),
129
+ };
130
+ }
131
+ /**
132
+ * Validate a candidate checkpoint against the state it replaces. This is the
133
+ * rule the covenant enforces on chain; running it here lets the SDK refuse to
134
+ * build a transition the node would reject.
135
+ */
136
+ function assertFactoryCheckpointTransition(before, after) {
137
+ if (after.address !== before.address) {
138
+ throw new Error('factory checkpoint must stay at the same script address');
139
+ }
140
+ if (after.tokenId !== before.tokenId) {
141
+ throw new Error('factory checkpoint must preserve the token');
142
+ }
143
+ if (after.totalValue !== before.totalValue) {
144
+ throw new Error('factory checkpoint must conserve the factory value');
145
+ }
146
+ if (after.sequence <= before.sequence) {
147
+ throw new Error(`factory checkpoint sequence ${after.sequence} must advance from ${before.sequence}`);
148
+ }
149
+ if (after.partyRoot !== before.partyRoot) {
150
+ throw new Error('factory checkpoint must preserve the committed party set');
151
+ }
152
+ const beforeKeys = Object.keys(before.allocations).sort();
153
+ const afterKeys = Object.keys(after.allocations).sort();
154
+ if (beforeKeys.join(',') !== afterKeys.join(',')) {
155
+ throw new Error('factory checkpoint must preserve the participant set');
156
+ }
157
+ let sum = 0n;
158
+ for (const key of afterKeys) {
159
+ if (after.allocations[key] < 0n)
160
+ throw new Error(`allocation for ${key} must be non-negative`);
161
+ sum += after.allocations[key];
162
+ }
163
+ if (sum !== after.totalValue) {
164
+ throw new Error(`factory checkpoint allocations (${sum}) do not conserve ${after.totalValue}`);
165
+ }
166
+ if (after.balanceRoot !== (0, script_js_1.computeFactoryBalanceRoot)(after.allocations)) {
167
+ throw new Error('factory checkpoint balance root does not commit the new allocations');
168
+ }
169
+ }
170
+ /** Snapshot helper for the state a checkpoint would produce. */
171
+ function factoryCheckpointSnapshot(checkpoint, participants) {
172
+ const allocations = {};
173
+ participants.forEach((party, index) => {
174
+ const variable = checkpoint.stateVariables.find((entry) => entry.port === script_js_1.FACTORY_BALANCE_PORT_BASE + index);
175
+ allocations[party.partyId] = BigInt((variable?.value ?? 0n));
176
+ });
177
+ return {
178
+ address: checkpoint.output.address,
179
+ tokenId: checkpoint.output.tokenId,
180
+ totalValue: checkpoint.output.amount,
181
+ sequence: checkpoint.sequence,
182
+ partyRoot: checkpoint.partyRoot,
183
+ balanceRoot: checkpoint.balanceRoot,
184
+ allocations,
185
+ };
186
+ }
@@ -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,111 @@
1
+ "use strict";
2
+ /**
3
+ * OMN-058 / RFC-079 §4A — output-enforced full distribution.
4
+ *
5
+ * The covenant built by `buildFactoryDistributionScript` (and the
6
+ * `settlement: 'full-distribution'` funding branch) pays every committed share
7
+ * of the *spent* coin. This module materializes the matching transaction from
8
+ * the factory's authoritative allocation, so the SDK cannot build a payout set
9
+ * the covenant would reject.
10
+ *
11
+ * Scope: the latest **confirmed** allocation (funding coin or checkpoint). A
12
+ * newer off-chain state is not covered until the contestable protocol lands.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.assertFactoryDistributable = assertFactoryDistributable;
16
+ exports.factoryDistributionPayouts = factoryDistributionPayouts;
17
+ exports.buildFactoryDistribution = buildFactoryDistribution;
18
+ const core_1 = require("@totemsdk/core");
19
+ /**
20
+ * Refuse to distribute while the factory still backs open virtual channels: the
21
+ * distribution covenant pays only the participant shares, so a VC reserve would
22
+ * be stranded or, worse, paid to the wrong party.
23
+ */
24
+ function assertFactoryDistributable(factory) {
25
+ const open = (factory.virtualChannels ?? []).filter((channel) => channel.status !== 'closed' && channel.totalValue > 0n);
26
+ if (open.length > 0) {
27
+ const ids = open.map((channel) => channel.channelId).join(', ');
28
+ throw new Error(`factory ${factory.factoryId} cannot be distributed while ${open.length} virtual channel(s) hold value (${ids}); `
29
+ + 'settle them to separately enforceable outputs first');
30
+ }
31
+ }
32
+ /**
33
+ * The exact payout set for the current committed allocation, in participant
34
+ * order. Addresses default to the participant settlement address.
35
+ */
36
+ function factoryDistributionPayouts(factory) {
37
+ const participants = factory.participants ?? [];
38
+ if (participants.length === 0) {
39
+ throw new Error(`factory ${factory.factoryId} has no participants`);
40
+ }
41
+ let sum = 0n;
42
+ const payouts = participants.map((participant, index) => {
43
+ const amount = factory.allocations?.[participant.partyId] ?? 0n;
44
+ if (amount < 0n) {
45
+ throw new Error(`allocation for ${participant.partyId} must be non-negative`);
46
+ }
47
+ // The covenant is built once, at funding, and pins one output per
48
+ // participant (`@TOTOUT EQ N`) with `VERIFYOUT(k … PREVSTATE(port))`. A
49
+ // zero committed share would require a zero-value output, which Minima
50
+ // rejects (`0 < amount`), so the branch cannot settle. Fail closed with the
51
+ // actionable alternative instead of building an invalid transaction.
52
+ if (amount === 0n) {
53
+ throw new Error(`factory ${factory.factoryId} cannot distribute: participant ${participant.partyId} has a zero committed share `
54
+ + 'and the distribution covenant requires a non-zero output for every participant. '
55
+ + 'Rebalance with a checkpoint, or use the per-party escape for the other shares.');
56
+ }
57
+ sum += amount;
58
+ const raw = (participant.settlementAddress ?? participant.publicKeyDigest ?? '').replace(/^0x/i, '');
59
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
60
+ throw new Error(`participant[${index}] payout address must be a 64-hex digest`);
61
+ }
62
+ return { partyId: participant.partyId, address: (0, core_1.wotsAddressData)(raw), amount };
63
+ });
64
+ const vcReserve = (factory.virtualChannels ?? [])
65
+ .filter((channel) => channel.status !== 'closed')
66
+ .reduce((total, channel) => total + channel.totalValue, 0n);
67
+ if (sum + vcReserve !== factory.totalValue) {
68
+ throw new Error(`factory allocations (${sum}) plus virtual-channel reserves (${vcReserve}) do not equal the factory total (${factory.totalValue})`);
69
+ }
70
+ return payouts;
71
+ }
72
+ /**
73
+ * Build the distribution transaction for the factory coin. The output order
74
+ * matches the participant order used by the covenant, and every amount comes
75
+ * from the committed allocation.
76
+ */
77
+ function buildFactoryDistribution(factory, params) {
78
+ assertFactoryDistributable(factory);
79
+ if (!params.fundingCoinId) {
80
+ throw new Error('buildFactoryDistribution requires the factory funding coin id');
81
+ }
82
+ const address = params.fundingAddress ?? factory.fundingAddress;
83
+ if (!address) {
84
+ throw new Error('buildFactoryDistribution requires the factory funding address');
85
+ }
86
+ const payouts = factoryDistributionPayouts(factory);
87
+ const total = payouts.reduce((sum, payout) => sum + payout.amount, 0n);
88
+ const outputs = payouts.map((payout) => ({
89
+ partyId: payout.partyId,
90
+ address: payout.address,
91
+ amount: payout.amount,
92
+ tokenId: factory.tokenId,
93
+ storeState: false,
94
+ stateVariables: [],
95
+ }));
96
+ const draft = {
97
+ type: 'settlement',
98
+ inputs: [{
99
+ coinId: params.fundingCoinId,
100
+ address,
101
+ amount: factory.totalValue,
102
+ tokenId: factory.tokenId,
103
+ scriptHex: '',
104
+ storeState: true,
105
+ }],
106
+ outputs,
107
+ storeState: false,
108
+ stateVariables: [],
109
+ };
110
+ return { draft, outputs, total };
111
+ }