@totemsdk/omnia-factory 0.6.0 → 0.7.1
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/LICENSE +202 -21
- package/NOTICE +60 -0
- package/dist/cjs/factory.d.ts +27 -2
- package/dist/cjs/factory.js +188 -11
- package/dist/cjs/index.d.ts +5 -4
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/settlement.d.ts +5 -1
- package/dist/cjs/settlement.js +34 -11
- package/dist/cjs/types.d.ts +22 -0
- package/dist/cjs/virtual.d.ts +14 -0
- package/dist/cjs/virtual.js +85 -1
- package/dist/factory.d.ts +27 -2
- package/dist/factory.js +187 -12
- package/dist/index.d.ts +5 -4
- package/dist/index.js +2 -2
- package/dist/settlement.d.ts +5 -1
- package/dist/settlement.js +35 -12
- package/dist/types.d.ts +22 -0
- package/dist/virtual.d.ts +14 -0
- package/dist/virtual.js +82 -1
- package/package.json +11 -10
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/package.json +1 -1
package/dist/cjs/settlement.js
CHANGED
|
@@ -7,6 +7,7 @@ exports.assembleFactorySettlement = assembleFactorySettlement;
|
|
|
7
7
|
exports.closeFactory = closeFactory;
|
|
8
8
|
exports.buildDisputePayload = buildDisputePayload;
|
|
9
9
|
const wasm_1 = require("@totemsdk/core/wasm");
|
|
10
|
+
const core_1 = require("@totemsdk/core");
|
|
10
11
|
const omnia_1 = require("@totemsdk/omnia");
|
|
11
12
|
const txpow_1 = require("@totemsdk/txpow");
|
|
12
13
|
/**
|
|
@@ -54,7 +55,7 @@ function buildFactorySettlement(factory) {
|
|
|
54
55
|
return {
|
|
55
56
|
settlementDraft,
|
|
56
57
|
settlementTxHex: (0, omnia_1.serializeTxDraft)(settlementDraft),
|
|
57
|
-
txDigest: (0, omnia_1.
|
|
58
|
+
txDigest: (0, omnia_1.computeOmniaTxDigest)(settlementDraft),
|
|
58
59
|
};
|
|
59
60
|
}
|
|
60
61
|
/**
|
|
@@ -104,7 +105,7 @@ function verifyFactorySettlementSignature(factory, txDigest, partyId, signature,
|
|
|
104
105
|
* (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
|
|
105
106
|
*/
|
|
106
107
|
async function assembleFactorySettlement(factory, draft, signatures, chainProvider, options) {
|
|
107
|
-
const
|
|
108
|
+
const signaturesOut = [];
|
|
108
109
|
for (const p of factory.participants) {
|
|
109
110
|
const s = signatures[p.partyId];
|
|
110
111
|
if (!s)
|
|
@@ -112,9 +113,8 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
112
113
|
if (!verifyFactorySettlementSignature(factory, draft.txDigest, p.partyId, s.signature, options?.verify)) {
|
|
113
114
|
throw new Error(`Settlement signature verification failed for party '${p.partyId}'`);
|
|
114
115
|
}
|
|
115
|
-
|
|
116
|
+
signaturesOut.push(s.signature);
|
|
116
117
|
}
|
|
117
|
-
const witnessBytes = witnessParts.reduce((a, b) => (0, wasm_1.concatBytes)(a, b));
|
|
118
118
|
const payload = {
|
|
119
119
|
factoryId: factory.factoryId,
|
|
120
120
|
sequence: factory.currentSequence,
|
|
@@ -122,13 +122,35 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
122
122
|
finalAllocations: { ...factory.allocations },
|
|
123
123
|
};
|
|
124
124
|
if (chainProvider) {
|
|
125
|
+
if (!options?.coinProof) {
|
|
126
|
+
throw new Error('closeFactory broadcast requires the factory coin proof (coinexport data)');
|
|
127
|
+
}
|
|
128
|
+
// The settlement input is the factory's N-of-N MULTISIG UTXO; the witness
|
|
129
|
+
// needs all N signatures + the coin proof + the funding-script proof.
|
|
130
|
+
const witnessBytes = (0, omnia_1.serializeOmniaWitness)({
|
|
131
|
+
signatures: signaturesOut,
|
|
132
|
+
coinProofs: [options.coinProof],
|
|
133
|
+
scriptProofs: [(0, core_1.buildScriptProof)(factory.fundingScript)],
|
|
134
|
+
});
|
|
125
135
|
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(draft.settlementDraft);
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
if (chainProvider.submitTransaction) {
|
|
137
|
+
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
138
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
139
|
+
throw new Error(`Factory settlement submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
140
|
+
}
|
|
141
|
+
payload.txpowId = submitted.txpowid;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
|
|
145
|
+
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
|
|
146
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
|
|
147
|
+
const fullTxPoW = (0, wasm_1.concatBytes)((0, wasm_1.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
148
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
149
|
+
if (broadcast.success === false) {
|
|
150
|
+
throw new Error(`Factory settlement broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
151
|
+
}
|
|
152
|
+
payload.txpowId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
153
|
+
}
|
|
132
154
|
}
|
|
133
155
|
return payload;
|
|
134
156
|
}
|
|
@@ -143,7 +165,7 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
143
165
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
144
166
|
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
145
167
|
*/
|
|
146
|
-
async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
168
|
+
async function closeFactory(factory, leaseProviders, chainProvider, opts) {
|
|
147
169
|
for (const p of factory.participants) {
|
|
148
170
|
if (!leaseProviders[p.partyId]) {
|
|
149
171
|
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
|
|
@@ -163,6 +185,7 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
163
185
|
const fn = bundle?.verify ?? omnia_1.verifyChannelSignature;
|
|
164
186
|
return fn(sig, digest, pkd);
|
|
165
187
|
},
|
|
188
|
+
coinProof: opts?.coinProof,
|
|
166
189
|
});
|
|
167
190
|
}
|
|
168
191
|
// ─── buildDisputePayload ──────────────────────────────────────────────────────
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface FactoryParticipant {
|
|
|
18
18
|
fundingCoinId?: string;
|
|
19
19
|
/** Address to receive funds on cooperative settlement. Falls back to publicKeyDigest. */
|
|
20
20
|
settlementAddress?: string;
|
|
21
|
+
/** Native transport identity (ed25519 pubkey) from the signed manifest. */
|
|
22
|
+
transportPubkey?: string;
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* Minimal lease operations required by the factory signing cycle.
|
|
@@ -51,6 +53,26 @@ export interface FactoryLeaseOps {
|
|
|
51
53
|
* `@totemsdk/core`, allowing test code to inject a no-op verifier without
|
|
52
54
|
* requiring real WOTS key material.
|
|
53
55
|
*/
|
|
56
|
+
/**
|
|
57
|
+
* On-chain funding material for one factory participant. Required by
|
|
58
|
+
* `createFactory` when the on-chain funding path is used (every participant
|
|
59
|
+
* supplies a `fundingCoinId` and a `chainProvider` is given).
|
|
60
|
+
*/
|
|
61
|
+
export interface FactoryFundingMaterial {
|
|
62
|
+
partyId: string;
|
|
63
|
+
/** Serialized Minima CoinProof for this party's funding coin (coinexport `data`). */
|
|
64
|
+
coinProof: Uint8Array;
|
|
65
|
+
/** Address of the funding coin (must match the coin in `coinProof`). */
|
|
66
|
+
coinAddress?: string;
|
|
67
|
+
/** Funding coin script; used to build its ScriptProof when `scriptProof` is absent. */
|
|
68
|
+
script?: string;
|
|
69
|
+
/** Pre-built serialized ScriptProof for the funding coin's address. */
|
|
70
|
+
scriptProof?: Uint8Array;
|
|
71
|
+
/** Sign the funding TX digest with the funding coin's wallet key. */
|
|
72
|
+
signer?: (digest: Uint8Array) => Promise<Uint8Array> | Uint8Array;
|
|
73
|
+
/** Or a pre-computed serialized Signature over the funding digest. */
|
|
74
|
+
signature?: Uint8Array;
|
|
75
|
+
}
|
|
54
76
|
export interface WotsLeaseBundle {
|
|
55
77
|
leaseProvider: FactoryLeaseOps;
|
|
56
78
|
signer: ChannelSigner;
|
package/dist/cjs/virtual.d.ts
CHANGED
|
@@ -56,6 +56,20 @@ export declare function openVirtualChannel(factory: ChannelFactory, parties: [st
|
|
|
56
56
|
factory: ChannelFactory;
|
|
57
57
|
channel: OmniaChannel;
|
|
58
58
|
}>;
|
|
59
|
+
/** Deterministic VC-close plan (no signing). Exported for peer co-signing. */
|
|
60
|
+
export interface VirtualChannelClosePlan {
|
|
61
|
+
vcId: string;
|
|
62
|
+
finalAllocations: Record<string, bigint>;
|
|
63
|
+
newSequence: number;
|
|
64
|
+
newAllocations: Record<string, bigint>;
|
|
65
|
+
newVcIds: string[];
|
|
66
|
+
commitment: Uint8Array;
|
|
67
|
+
}
|
|
68
|
+
export declare function buildVirtualChannelClose(factory: ChannelFactory, channel: OmniaChannel): VirtualChannelClosePlan;
|
|
69
|
+
/** Produce this party's VC-close signature without committing the lease. */
|
|
70
|
+
export declare function signVirtualChannelClose(factory: ChannelFactory, plan: VirtualChannelClosePlan, bundle: WotsLeaseBundle): Promise<VirtualChannelOpenSignature>;
|
|
71
|
+
/** Assemble N-of-N VC-close signatures into the updated factory. */
|
|
72
|
+
export declare function assembleVirtualChannelClose(factory: ChannelFactory, plan: VirtualChannelClosePlan, signatures: Record<string, VirtualChannelOpenSignature>, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): ChannelFactory;
|
|
59
73
|
/**
|
|
60
74
|
* Close a virtual channel and return its final balances to factory allocations.
|
|
61
75
|
*
|
package/dist/cjs/virtual.js
CHANGED
|
@@ -5,6 +5,9 @@ exports.signVirtualChannelOpen = signVirtualChannelOpen;
|
|
|
5
5
|
exports.verifyVirtualChannelOpenSignature = verifyVirtualChannelOpenSignature;
|
|
6
6
|
exports.assembleVirtualChannelOpen = assembleVirtualChannelOpen;
|
|
7
7
|
exports.openVirtualChannel = openVirtualChannel;
|
|
8
|
+
exports.buildVirtualChannelClose = buildVirtualChannelClose;
|
|
9
|
+
exports.signVirtualChannelClose = signVirtualChannelClose;
|
|
10
|
+
exports.assembleVirtualChannelClose = assembleVirtualChannelClose;
|
|
8
11
|
exports.closeVirtualChannel = closeVirtualChannel;
|
|
9
12
|
const omnia_1 = require("@totemsdk/omnia");
|
|
10
13
|
const factory_js_1 = require("./factory.js");
|
|
@@ -155,12 +158,14 @@ function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
|
155
158
|
publicKeyDigest: partyAMeta.publicKeyDigest,
|
|
156
159
|
addressIndex: partyAMeta.addressIndex,
|
|
157
160
|
settlementAddress: partyAMeta.settlementAddress,
|
|
161
|
+
transportPubkey: partyAMeta.transportPubkey,
|
|
158
162
|
};
|
|
159
163
|
const partyB = {
|
|
160
164
|
partyId: partyBId,
|
|
161
165
|
publicKeyDigest: partyBMeta.publicKeyDigest,
|
|
162
166
|
addressIndex: partyBMeta.addressIndex,
|
|
163
167
|
settlementAddress: partyBMeta.settlementAddress,
|
|
168
|
+
transportPubkey: partyBMeta.transportPubkey,
|
|
164
169
|
};
|
|
165
170
|
const channel = {
|
|
166
171
|
channelId: plan.vcId,
|
|
@@ -221,7 +226,86 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
221
226
|
return (bundle?.verify ?? omnia_1.verifyChannelSignature)(sig, digest, pkd);
|
|
222
227
|
});
|
|
223
228
|
}
|
|
224
|
-
|
|
229
|
+
function buildVirtualChannelClose(factory, channel) {
|
|
230
|
+
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
231
|
+
if (!existing)
|
|
232
|
+
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
233
|
+
const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
|
|
234
|
+
const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
|
|
235
|
+
if (finalSum !== channel.totalValue) {
|
|
236
|
+
throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
|
|
237
|
+
}
|
|
238
|
+
const newSequence = factory.currentSequence + 1;
|
|
239
|
+
const newAllocations = { ...factory.allocations };
|
|
240
|
+
for (const [partyId, amount] of Object.entries(finalAllocations)) {
|
|
241
|
+
newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
|
|
242
|
+
}
|
|
243
|
+
const newVcIds = factory.virtualChannels
|
|
244
|
+
.filter(c => c.channelId !== channel.channelId)
|
|
245
|
+
.map(c => c.channelId);
|
|
246
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
247
|
+
return {
|
|
248
|
+
vcId: channel.channelId,
|
|
249
|
+
finalAllocations,
|
|
250
|
+
newSequence,
|
|
251
|
+
newAllocations,
|
|
252
|
+
newVcIds,
|
|
253
|
+
commitment,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** Produce this party's VC-close signature without committing the lease. */
|
|
257
|
+
async function signVirtualChannelClose(factory, plan, bundle) {
|
|
258
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
259
|
+
if (!participant) {
|
|
260
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
261
|
+
}
|
|
262
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
263
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
264
|
+
purpose: 'factory-vc-close',
|
|
265
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
266
|
+
});
|
|
267
|
+
let sig;
|
|
268
|
+
try {
|
|
269
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
270
|
+
}
|
|
271
|
+
catch (err) {
|
|
272
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
273
|
+
throw err;
|
|
274
|
+
}
|
|
275
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
276
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
277
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
278
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${participant.partyId}'`);
|
|
279
|
+
}
|
|
280
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
281
|
+
}
|
|
282
|
+
/** Assemble N-of-N VC-close signatures into the updated factory. */
|
|
283
|
+
function assembleVirtualChannelClose(factory, plan, signatures, verify) {
|
|
284
|
+
for (const p of factory.participants) {
|
|
285
|
+
const s = signatures[p.partyId];
|
|
286
|
+
if (!s)
|
|
287
|
+
throw new Error(`Missing virtual-channel close signature for party '${p.partyId}' — close requires all N`);
|
|
288
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
289
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${p.partyId}'`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const logEntry = {
|
|
293
|
+
sequence: plan.newSequence,
|
|
294
|
+
timestamp: Date.now(),
|
|
295
|
+
event: 'virtual_close',
|
|
296
|
+
allocations: plan.newAllocations,
|
|
297
|
+
virtualChannelIds: plan.newVcIds,
|
|
298
|
+
};
|
|
299
|
+
const updated = {
|
|
300
|
+
...factory,
|
|
301
|
+
allocations: plan.newAllocations,
|
|
302
|
+
virtualChannels: factory.virtualChannels.filter(c => c.channelId !== plan.vcId),
|
|
303
|
+
currentSequence: plan.newSequence,
|
|
304
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
305
|
+
};
|
|
306
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
307
|
+
return updated;
|
|
308
|
+
}
|
|
225
309
|
/**
|
|
226
310
|
* Close a virtual channel and return its final balances to factory allocations.
|
|
227
311
|
*
|
package/dist/factory.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
2
|
-
import type { ChannelFactory, FactoryParticipant, WotsLeaseBundle } from './types.js';
|
|
2
|
+
import type { ChannelFactory, FactoryParticipant, FactoryFundingMaterial, WotsLeaseBundle } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Enforce the factory's balance conservation invariant:
|
|
5
5
|
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
@@ -38,7 +38,32 @@ export declare function enforceConservation(factory: ChannelFactory): void;
|
|
|
38
38
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
39
39
|
* Defaults to 0.
|
|
40
40
|
*/
|
|
41
|
-
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number): Promise<ChannelFactory>;
|
|
41
|
+
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
|
|
42
|
+
/** A factory opening built without any signatures or broadcast. */
|
|
43
|
+
export interface FactoryOpeningPlan {
|
|
44
|
+
factory: ChannelFactory;
|
|
45
|
+
fundingTxBytes?: Uint8Array;
|
|
46
|
+
fundingDigest?: Uint8Array;
|
|
47
|
+
fundingCoinId?: string;
|
|
48
|
+
fundingMaterials?: FactoryFundingMaterial[];
|
|
49
|
+
onChain: boolean;
|
|
50
|
+
}
|
|
51
|
+
export interface FinalizeFactoryOpeningOptions {
|
|
52
|
+
/** Funding-witness signatures for every participant (on-chain only). */
|
|
53
|
+
fundingSignatures?: Record<string, Uint8Array>;
|
|
54
|
+
/** Factory opening signatures to record on the proposal. */
|
|
55
|
+
openingSignatures: Record<string, Uint8Array>;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Build a factory and (when every participant supplies a funding coin) its
|
|
59
|
+
* deterministic funding draft, without signing or broadcasting.
|
|
60
|
+
*/
|
|
61
|
+
export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[]): Promise<FactoryOpeningPlan>;
|
|
62
|
+
/**
|
|
63
|
+
* Broadcast the prepared factory funding (when on-chain) and record opening
|
|
64
|
+
* signatures. When every participant signature is supplied the factory commits.
|
|
65
|
+
*/
|
|
66
|
+
export declare function finalizeFactoryOpening(plan: FactoryOpeningPlan, opts: FinalizeFactoryOpeningOptions, chainProvider?: ChainStateProvider): Promise<ChannelFactory>;
|
|
42
67
|
/**
|
|
43
68
|
* Counterparty co-signs the factory proposal.
|
|
44
69
|
*
|
package/dist/factory.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { sha3_256 } from '@totemsdk/core/wasm';
|
|
2
2
|
import { concatBytes } from '@totemsdk/core/wasm';
|
|
3
|
-
import {
|
|
3
|
+
import { buildScriptProof, computeScriptAddress } from '@totemsdk/core';
|
|
4
|
+
import { buildFundingTx, omniaDraftToMinimaBytes, computeOmniaTxDigest, minimaOutputCoinIdsForDraft, serializeOmniaWitness, verifyChannelSignature, } from '@totemsdk/omnia';
|
|
4
5
|
import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
|
|
5
6
|
import { buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS } from './script.js';
|
|
6
7
|
import { computeFactoryStateCommitment } from './commitment.js';
|
|
@@ -109,7 +110,7 @@ function generateFactoryId(participants, tokenId, tokenScale) {
|
|
|
109
110
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
110
111
|
* Defaults to 0.
|
|
111
112
|
*/
|
|
112
|
-
export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
|
|
113
|
+
export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
|
|
113
114
|
if (participants.length < 2) {
|
|
114
115
|
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
115
116
|
}
|
|
@@ -131,19 +132,70 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
|
|
|
131
132
|
let pendingCommitment;
|
|
132
133
|
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
133
134
|
if (allHaveCoinId && chainProvider) {
|
|
135
|
+
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
136
|
+
// The transaction input address must be the *funding coin's* address, not
|
|
137
|
+
// the participant's settlement address. Callers supply it directly or via
|
|
138
|
+
// the funding coin script.
|
|
139
|
+
const inputAddresses = participants.map(p => {
|
|
140
|
+
const m = materialByParty.get(p.partyId);
|
|
141
|
+
return m?.coinAddress ?? (m?.script ? computeScriptAddress(m.script) : '');
|
|
142
|
+
});
|
|
143
|
+
if (inputAddresses.some(a => !a)) {
|
|
144
|
+
throw new Error('createFactory on-chain requires funding material (coinAddress or script) for every participant');
|
|
145
|
+
}
|
|
134
146
|
const tip = await chainProvider.getTip();
|
|
135
147
|
const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
136
|
-
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount),
|
|
137
|
-
//
|
|
138
|
-
pendingCommitment =
|
|
148
|
+
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
|
|
149
|
+
// Production signatures must cover the canonical Minima transaction ID.
|
|
150
|
+
pendingCommitment = computeOmniaTxDigest(fundingDraft);
|
|
151
|
+
// Assemble the real witness: one CoinProof + ScriptProof + signature per
|
|
152
|
+
// input coin (the factory's own MULTISIG script is the *output* script).
|
|
153
|
+
const signatures = [];
|
|
154
|
+
const coinProofs = [];
|
|
155
|
+
const scriptProofs = [];
|
|
156
|
+
for (const p of participants) {
|
|
157
|
+
const m = materialByParty.get(p.partyId);
|
|
158
|
+
if (!m)
|
|
159
|
+
throw new Error(`Missing funding material for factory party '${p.partyId}'`);
|
|
160
|
+
coinProofs.push(m.coinProof);
|
|
161
|
+
let scriptProof = m.scriptProof;
|
|
162
|
+
if (!scriptProof) {
|
|
163
|
+
if (!m.script)
|
|
164
|
+
throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
|
|
165
|
+
scriptProof = buildScriptProof(m.script);
|
|
166
|
+
}
|
|
167
|
+
scriptProofs.push(scriptProof);
|
|
168
|
+
if (m.signature) {
|
|
169
|
+
signatures.push(m.signature);
|
|
170
|
+
}
|
|
171
|
+
else if (m.signer) {
|
|
172
|
+
signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
139
178
|
const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
179
|
+
const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
|
|
180
|
+
if (chainProvider.submitTransaction) {
|
|
181
|
+
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
182
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
183
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
184
|
+
}
|
|
185
|
+
fundingTxId = submitted.txpowid;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
const txnDifficulty = await resolveTxPowTarget(chainProvider);
|
|
189
|
+
const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
|
|
190
|
+
const mined = await mineTxPoW(txBody, txnDifficulty);
|
|
191
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
192
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
193
|
+
if (broadcast.success === false) {
|
|
194
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
195
|
+
}
|
|
196
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
197
|
+
}
|
|
198
|
+
fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
|
|
147
199
|
}
|
|
148
200
|
else {
|
|
149
201
|
// In-memory / test path: sign the factory state commitment instead.
|
|
@@ -182,6 +234,129 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
|
|
|
182
234
|
}
|
|
183
235
|
return factory;
|
|
184
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Build a factory and (when every participant supplies a funding coin) its
|
|
239
|
+
* deterministic funding draft, without signing or broadcasting.
|
|
240
|
+
*/
|
|
241
|
+
export async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding) {
|
|
242
|
+
if (participants.length < 2) {
|
|
243
|
+
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
244
|
+
}
|
|
245
|
+
const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
|
|
246
|
+
const allocations = {};
|
|
247
|
+
for (const p of participants)
|
|
248
|
+
allocations[p.partyId] = p.contributionAmount;
|
|
249
|
+
const { script, address } = buildAndHashFactoryScript(participants);
|
|
250
|
+
const factoryId = generateFactoryId(participants, tokenId, tokenScale);
|
|
251
|
+
let fundingTxBytes;
|
|
252
|
+
let fundingDigest;
|
|
253
|
+
let fundingCoinId;
|
|
254
|
+
let pendingCommitment;
|
|
255
|
+
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
256
|
+
if (allHaveCoinId && chainProvider) {
|
|
257
|
+
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
258
|
+
const inputAddresses = participants.map(p => {
|
|
259
|
+
const m = materialByParty.get(p.partyId);
|
|
260
|
+
return m?.coinAddress ?? (m?.script ? computeScriptAddress(m.script) : '');
|
|
261
|
+
});
|
|
262
|
+
if (inputAddresses.some(a => !a)) {
|
|
263
|
+
throw new Error('Factory opening on-chain requires funding material (coinAddress or script) for every participant');
|
|
264
|
+
}
|
|
265
|
+
const tip = await chainProvider.getTip();
|
|
266
|
+
const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
267
|
+
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
|
|
268
|
+
fundingDigest = computeOmniaTxDigest(fundingDraft);
|
|
269
|
+
fundingTxBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
270
|
+
fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
|
|
271
|
+
pendingCommitment = fundingDigest;
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
|
|
275
|
+
}
|
|
276
|
+
const initialEntry = {
|
|
277
|
+
sequence: 0,
|
|
278
|
+
timestamp: Date.now(),
|
|
279
|
+
event: 'create',
|
|
280
|
+
allocations: { ...allocations },
|
|
281
|
+
virtualChannelIds: [],
|
|
282
|
+
};
|
|
283
|
+
const factory = {
|
|
284
|
+
factoryId,
|
|
285
|
+
participants,
|
|
286
|
+
totalValue,
|
|
287
|
+
tokenId,
|
|
288
|
+
tokenScale,
|
|
289
|
+
allocations: { ...allocations },
|
|
290
|
+
virtualChannels: [],
|
|
291
|
+
currentSequence: 0,
|
|
292
|
+
status: 'opening',
|
|
293
|
+
stateLog: [initialEntry],
|
|
294
|
+
fundingScript: script,
|
|
295
|
+
fundingAddress: address,
|
|
296
|
+
fundingTxId: undefined,
|
|
297
|
+
fundingCoinId: undefined,
|
|
298
|
+
pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
|
|
299
|
+
pendingSignatures: {},
|
|
300
|
+
};
|
|
301
|
+
return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Broadcast the prepared factory funding (when on-chain) and record opening
|
|
305
|
+
* signatures. When every participant signature is supplied the factory commits.
|
|
306
|
+
*/
|
|
307
|
+
export async function finalizeFactoryOpening(plan, opts, chainProvider) {
|
|
308
|
+
let factory = plan.factory;
|
|
309
|
+
if (plan.onChain) {
|
|
310
|
+
if (!chainProvider || !plan.fundingTxBytes)
|
|
311
|
+
throw new Error('Factory funding requires a chain provider');
|
|
312
|
+
const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
|
|
313
|
+
const signatures = [];
|
|
314
|
+
const coinProofs = [];
|
|
315
|
+
const scriptProofs = [];
|
|
316
|
+
for (const participant of factory.participants) {
|
|
317
|
+
const signature = opts.fundingSignatures?.[participant.partyId];
|
|
318
|
+
if (!signature)
|
|
319
|
+
throw new Error(`Missing funding signature for factory party '${participant.partyId}'`);
|
|
320
|
+
const material = materials.get(participant.partyId);
|
|
321
|
+
if (!material)
|
|
322
|
+
throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
|
|
323
|
+
coinProofs.push(material.coinProof);
|
|
324
|
+
const scriptProof = material.scriptProof ?? (material.script ? buildScriptProof(material.script) : undefined);
|
|
325
|
+
if (!scriptProof)
|
|
326
|
+
throw new Error(`Missing script or scriptProof for factory party '${participant.partyId}'`);
|
|
327
|
+
scriptProofs.push(scriptProof);
|
|
328
|
+
signatures.push(signature);
|
|
329
|
+
}
|
|
330
|
+
const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
|
|
331
|
+
let fundingTxId;
|
|
332
|
+
if (chainProvider.submitTransaction) {
|
|
333
|
+
const submitted = await chainProvider.submitTransaction(plan.fundingTxBytes, witnessBytes);
|
|
334
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
335
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
336
|
+
}
|
|
337
|
+
fundingTxId = submitted.txpowid;
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
const txnDifficulty = await resolveTxPowTarget(chainProvider);
|
|
341
|
+
const txBody = serializeTxBody(plan.fundingTxBytes, witnessBytes, { txnDifficulty });
|
|
342
|
+
const mined = await mineTxPoW(txBody, txnDifficulty);
|
|
343
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
344
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
345
|
+
if (broadcast.success === false) {
|
|
346
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
347
|
+
}
|
|
348
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
349
|
+
}
|
|
350
|
+
factory = {
|
|
351
|
+
...factory,
|
|
352
|
+
fundingTxId,
|
|
353
|
+
fundingCoinId: plan.fundingCoinId,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
|
|
357
|
+
const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
|
|
358
|
+
return allSigned ? commitOpening(factory) : factory;
|
|
359
|
+
}
|
|
185
360
|
// ─── acceptFactory ────────────────────────────────────────────────────────────
|
|
186
361
|
/**
|
|
187
362
|
* Counterparty co-signs the factory proposal.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
export type {
|
|
1
|
+
export type { FactoryOpeningPlan, FinalizeFactoryOpeningOptions } from './factory.js';
|
|
2
|
+
export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
2
3
|
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
4
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
5
|
export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
|
|
5
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
|
+
export { createFactory, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
7
|
export type { FactoryOpeningSignature } from './factory.js';
|
|
7
8
|
export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
|
|
8
|
-
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
9
|
-
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, } from './virtual.js';
|
|
9
|
+
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
10
|
+
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, VirtualChannelClosePlan, } from './virtual.js';
|
|
10
11
|
export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
11
12
|
export type { FactorySettlementDraft, FactorySettlementSignature, } from './settlement.js';
|
|
12
13
|
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
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
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
3
|
+
export { createFactory, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
4
4
|
// RFC-035 B2 — factory opening round-trip over the coordination transport.
|
|
5
5
|
export { createFactoryCoordination, } from './coordination.js';
|
|
6
|
-
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
6
|
+
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
7
7
|
export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
8
8
|
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
package/dist/settlement.d.ts
CHANGED
|
@@ -31,6 +31,8 @@ export declare function verifyFactorySettlementSignature(factory: ChannelFactory
|
|
|
31
31
|
*/
|
|
32
32
|
export declare function assembleFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, signatures: Record<string, FactorySettlementSignature>, chainProvider?: ChainStateProvider, options?: {
|
|
33
33
|
verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean;
|
|
34
|
+
/** Serialized CoinProof for the factory's shared UTXO (coinexport `data`). */
|
|
35
|
+
coinProof?: Uint8Array;
|
|
34
36
|
}): Promise<FactorySettlementPayload>;
|
|
35
37
|
/**
|
|
36
38
|
* Cooperative N-of-N factory close (central/local path).
|
|
@@ -43,7 +45,9 @@ export declare function assembleFactorySettlement(factory: ChannelFactory, draft
|
|
|
43
45
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
44
46
|
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
45
47
|
*/
|
|
46
|
-
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider
|
|
48
|
+
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider, opts?: {
|
|
49
|
+
coinProof?: Uint8Array;
|
|
50
|
+
}): Promise<FactorySettlementPayload>;
|
|
47
51
|
/**
|
|
48
52
|
* Build a unilateral factory close (dispute) payload.
|
|
49
53
|
*
|