@totemsdk/omnia-factory 0.1.4 → 0.1.6
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 +21 -0
- package/README.md +4 -4
- package/dist/commitment.js +6 -3
- package/dist/factory.js +27 -21
- package/dist/index.js +21 -5
- package/dist/script.js +12 -6
- package/dist/settlement.js +17 -13
- package/dist/types.js +2 -1
- package/dist/virtual.js +14 -10
- package/package.json +39 -11
- package/src/__tests__/factory.test.ts +0 -763
- package/src/commitment.ts +0 -35
- package/src/factory.ts +0 -397
- package/src/index.ts +0 -38
- package/src/script.ts +0 -67
- package/src/settlement.ts +0 -188
- package/src/types.ts +0 -142
- package/src/virtual.ts +0 -298
package/src/commitment.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { sha3_256 } from '@noble/hashes/sha3';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Compute the canonical 32-byte state commitment for N-of-N factory signing.
|
|
5
|
-
*
|
|
6
|
-
* Covers:
|
|
7
|
-
* - factoryId (factory context isolation)
|
|
8
|
-
* - sequence (monotonicity; prevents replay of old state)
|
|
9
|
-
* - pendingAllocations (the proposed allocation split being signed)
|
|
10
|
-
* - virtualChannelIds (list of currently open VCs; prevents forgery of VC state)
|
|
11
|
-
*
|
|
12
|
-
* All fields are sorted lexicographically for determinism regardless of the
|
|
13
|
-
* order in which keys appear in the caller's objects.
|
|
14
|
-
*
|
|
15
|
-
* This commitment is what every party signs via `FactorySignerOps.sign`, and
|
|
16
|
-
* what `FactorySignerOps.verify` checks against each stored signature.
|
|
17
|
-
*/
|
|
18
|
-
export function computeFactoryStateCommitment(
|
|
19
|
-
factoryId: string,
|
|
20
|
-
sequence: number,
|
|
21
|
-
pendingAllocations: Record<string, bigint>,
|
|
22
|
-
virtualChannelIds: string[],
|
|
23
|
-
): Uint8Array {
|
|
24
|
-
const canonical = {
|
|
25
|
-
factoryId,
|
|
26
|
-
sequence,
|
|
27
|
-
allocations: Object.fromEntries(
|
|
28
|
-
Object.entries(pendingAllocations)
|
|
29
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
30
|
-
.map(([k, v]) => [k, v.toString()]),
|
|
31
|
-
),
|
|
32
|
-
virtualChannelIds: [...virtualChannelIds].sort(),
|
|
33
|
-
};
|
|
34
|
-
return sha3_256(new TextEncoder().encode(JSON.stringify(canonical)));
|
|
35
|
-
}
|
package/src/factory.ts
DELETED
|
@@ -1,397 +0,0 @@
|
|
|
1
|
-
import { sha3_256 } from '@noble/hashes/sha3';
|
|
2
|
-
import { concatBytes, wotsVerifyDigest, fromHex } from '@totemsdk/core';
|
|
3
|
-
import {
|
|
4
|
-
buildFundingTx,
|
|
5
|
-
omniaDraftToMinimaBytes,
|
|
6
|
-
computeTxDraftDigest,
|
|
7
|
-
} from '@totemsdk/omnia';
|
|
8
|
-
import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
|
|
9
|
-
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
10
|
-
import type {
|
|
11
|
-
ChannelFactory,
|
|
12
|
-
FactoryParticipant,
|
|
13
|
-
WotsLeaseBundle,
|
|
14
|
-
FactoryLogEntry,
|
|
15
|
-
} from './types.js';
|
|
16
|
-
import { buildAndHashFactoryScript } from './script.js';
|
|
17
|
-
import { computeFactoryStateCommitment } from './commitment.js';
|
|
18
|
-
|
|
19
|
-
// ─── Balance conservation ────────────────────────────────────────────────────
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Enforce the factory's balance conservation invariant:
|
|
23
|
-
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
24
|
-
*
|
|
25
|
-
* Throws on violation. Called after every committed state transition.
|
|
26
|
-
*/
|
|
27
|
-
export function enforceConservation(factory: ChannelFactory): void {
|
|
28
|
-
const allocSum = Object.values(factory.allocations).reduce((a, b) => a + b, 0n);
|
|
29
|
-
const vcSum = factory.virtualChannels.reduce((acc, vc) => acc + vc.totalValue, 0n);
|
|
30
|
-
if (allocSum + vcSum !== factory.totalValue) {
|
|
31
|
-
throw new Error(
|
|
32
|
-
`Balance conservation violated: allocations(${allocSum}) + virtualChannels(${vcSum}) ` +
|
|
33
|
-
`!== totalValue(${factory.totalValue})`,
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// ─── Internal signing helpers ─────────────────────────────────────────────────
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Execute the full WOTS lease cycle for one party (reserve → sign → verify → commit).
|
|
42
|
-
*
|
|
43
|
-
* Verification uses the optional `bundle.verify` override first; falls back to
|
|
44
|
-
* `wotsVerifyDigest` from `@totemsdk/core`. If verification fails, the reservation
|
|
45
|
-
* is burned and an error is thrown.
|
|
46
|
-
*/
|
|
47
|
-
async function leaseSign(
|
|
48
|
-
factoryId: string,
|
|
49
|
-
commitment: Uint8Array,
|
|
50
|
-
purpose: string,
|
|
51
|
-
participant: FactoryParticipant,
|
|
52
|
-
bundle: WotsLeaseBundle,
|
|
53
|
-
): Promise<Uint8Array> {
|
|
54
|
-
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
55
|
-
treeId: `omnia-factory-${factoryId}`,
|
|
56
|
-
purpose,
|
|
57
|
-
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
let sig: Uint8Array;
|
|
61
|
-
try {
|
|
62
|
-
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
63
|
-
} catch (err) {
|
|
64
|
-
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => {});
|
|
65
|
-
throw err;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Verify the signature against the REGISTERED participant public key digest —
|
|
69
|
-
// not self-reported from the signer, ensuring the signer matches the factory record.
|
|
70
|
-
const verifyFn = bundle.verify
|
|
71
|
-
?? ((s: Uint8Array, c: Uint8Array, pkd: string) => wotsVerifyDigest(s, c, fromHex(pkd)));
|
|
72
|
-
if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
|
|
73
|
-
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => {});
|
|
74
|
-
throw new Error(
|
|
75
|
-
`Signature verification failed for party '${participant.partyId}' — refusing to commit`,
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-${factoryId}`);
|
|
80
|
-
return sig;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Collect N-of-N signatures for a given commitment from ALL factory participants.
|
|
85
|
-
* Throws if any participant's bundle is missing or if any signature fails verification.
|
|
86
|
-
*/
|
|
87
|
-
async function collectNofN(
|
|
88
|
-
factoryId: string,
|
|
89
|
-
commitment: Uint8Array,
|
|
90
|
-
purpose: string,
|
|
91
|
-
participants: FactoryParticipant[],
|
|
92
|
-
leaseProviders: Record<string, WotsLeaseBundle>,
|
|
93
|
-
): Promise<void> {
|
|
94
|
-
for (const p of participants) {
|
|
95
|
-
if (!leaseProviders[p.partyId]) {
|
|
96
|
-
throw new Error(
|
|
97
|
-
`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`,
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
for (const p of participants) {
|
|
102
|
-
await leaseSign(factoryId, commitment, purpose, p, leaseProviders[p.partyId]);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// ─── Factory ID ───────────────────────────────────────────────────────────────
|
|
107
|
-
|
|
108
|
-
function generateFactoryId(participants: FactoryParticipant[], tokenId: string): string {
|
|
109
|
-
const sorted = [...participants].sort((a, b) => a.partyId.localeCompare(b.partyId));
|
|
110
|
-
const nonce = Array.from(
|
|
111
|
-
globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8),
|
|
112
|
-
).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
113
|
-
const input = JSON.stringify({
|
|
114
|
-
participants: sorted.map(p => ({ partyId: p.partyId, pkd: p.publicKeyDigest })),
|
|
115
|
-
tokenId,
|
|
116
|
-
nonce,
|
|
117
|
-
});
|
|
118
|
-
return Buffer.from(sha3_256(new TextEncoder().encode(input))).toString('hex');
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// ─── createFactory ────────────────────────────────────────────────────────────
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Create a factory proposal (proposer step).
|
|
125
|
-
*
|
|
126
|
-
* The calling party (`signer.publicKeyDigest` matches one of `participants`)
|
|
127
|
-
* signs the factory opening commitment via `leaseProvider`, performing the full
|
|
128
|
-
* WOTS reserve → sign → verify → commit cycle.
|
|
129
|
-
*
|
|
130
|
-
* When ALL participants supply `fundingCoinId` and `chainProvider` is given,
|
|
131
|
-
* the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
|
|
132
|
-
* `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
|
|
133
|
-
* The TX draft digest is used as the factory opening commitment so that all
|
|
134
|
-
* parties are co-signing the EXACT on-chain TX structure.
|
|
135
|
-
*
|
|
136
|
-
* Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
|
|
137
|
-
* (useful for testing and off-chain simulation); the commitment falls back to
|
|
138
|
-
* the factory state commitment hash.
|
|
139
|
-
*
|
|
140
|
-
* The returned factory is in `'opening'` status. Every other participant must
|
|
141
|
-
* call `acceptFactory(factory, leaseProvider, signer)` before the factory
|
|
142
|
-
* transitions to `'active'`.
|
|
143
|
-
*
|
|
144
|
-
* @param participants - All N factory participants with their contribution amounts.
|
|
145
|
-
* @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
|
|
146
|
-
* @param leaseProvider - WOTS lease provider for the proposer's key slot.
|
|
147
|
-
* @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
|
|
148
|
-
* one of the registered participants).
|
|
149
|
-
* @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
|
|
150
|
-
*/
|
|
151
|
-
export async function createFactory(
|
|
152
|
-
participants: FactoryParticipant[],
|
|
153
|
-
tokenId: string,
|
|
154
|
-
bundle: WotsLeaseBundle,
|
|
155
|
-
chainProvider?: ChainStateProvider,
|
|
156
|
-
): Promise<ChannelFactory> {
|
|
157
|
-
if (participants.length < 2) {
|
|
158
|
-
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// Identify the proposer by public key digest.
|
|
162
|
-
const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
163
|
-
if (!proposer) {
|
|
164
|
-
throw new Error(
|
|
165
|
-
'signer.publicKeyDigest does not match any registered factory participant',
|
|
166
|
-
);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
|
|
170
|
-
const allocations: Record<string, bigint> = {};
|
|
171
|
-
for (const p of participants) {
|
|
172
|
-
allocations[p.partyId] = p.contributionAmount;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const { script, address } = buildAndHashFactoryScript(participants);
|
|
176
|
-
const factoryId = generateFactoryId(participants, tokenId);
|
|
177
|
-
|
|
178
|
-
// ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
|
|
179
|
-
let fundingTxId: string | undefined;
|
|
180
|
-
let fundingCoinId: string | undefined;
|
|
181
|
-
let pendingCommitment: Uint8Array;
|
|
182
|
-
|
|
183
|
-
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
184
|
-
if (allHaveCoinId && chainProvider) {
|
|
185
|
-
const fundingDraft = buildFundingTx(
|
|
186
|
-
script,
|
|
187
|
-
address,
|
|
188
|
-
totalValue,
|
|
189
|
-
tokenId,
|
|
190
|
-
0,
|
|
191
|
-
participants.map(p => p.fundingCoinId!),
|
|
192
|
-
participants.map(p => p.contributionAmount),
|
|
193
|
-
participants.map(p => p.settlementAddress ?? p.publicKeyDigest),
|
|
194
|
-
);
|
|
195
|
-
|
|
196
|
-
// All parties co-sign the TX digest — the exact on-chain TX structure.
|
|
197
|
-
pendingCommitment = computeTxDraftDigest(fundingDraft);
|
|
198
|
-
|
|
199
|
-
const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
200
|
-
const txBody = serializeTxBody(draftBytes, new Uint8Array(0));
|
|
201
|
-
const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
|
|
202
|
-
const fullTxPoW = concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01]), txBody);
|
|
203
|
-
await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
204
|
-
|
|
205
|
-
fundingTxId = Buffer.from(mined.txpowId).toString('hex');
|
|
206
|
-
fundingCoinId = `${fundingTxId}-0`;
|
|
207
|
-
} else {
|
|
208
|
-
// In-memory / test path: sign the factory state commitment instead.
|
|
209
|
-
pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// Sign with the proposer's lease (full bundle preserved so verify override is available).
|
|
213
|
-
const proposerSig = await leaseSign(
|
|
214
|
-
factoryId,
|
|
215
|
-
pendingCommitment,
|
|
216
|
-
'factory-open',
|
|
217
|
-
proposer,
|
|
218
|
-
bundle,
|
|
219
|
-
);
|
|
220
|
-
|
|
221
|
-
const initialEntry: FactoryLogEntry = {
|
|
222
|
-
sequence: 0,
|
|
223
|
-
timestamp: Date.now(),
|
|
224
|
-
event: 'create',
|
|
225
|
-
allocations: { ...allocations },
|
|
226
|
-
virtualChannelIds: [],
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
const factory: ChannelFactory = {
|
|
230
|
-
factoryId,
|
|
231
|
-
participants,
|
|
232
|
-
totalValue,
|
|
233
|
-
tokenId,
|
|
234
|
-
allocations: { ...allocations },
|
|
235
|
-
virtualChannels: [],
|
|
236
|
-
currentSequence: 0,
|
|
237
|
-
status: 'opening',
|
|
238
|
-
stateLog: [initialEntry],
|
|
239
|
-
fundingScript: script,
|
|
240
|
-
fundingAddress: address,
|
|
241
|
-
fundingTxId,
|
|
242
|
-
fundingCoinId,
|
|
243
|
-
pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
|
|
244
|
-
pendingSignatures: { [proposer.partyId]: proposerSig },
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
// If proposer is the only participant (edge case), activate immediately.
|
|
248
|
-
if (participants.length === 1) {
|
|
249
|
-
return commitOpening(factory);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
return factory;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// ─── acceptFactory ────────────────────────────────────────────────────────────
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Counterparty co-signs the factory proposal.
|
|
259
|
-
*
|
|
260
|
-
* Each non-proposing participant calls this once. When ALL N parties have
|
|
261
|
-
* signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
|
|
262
|
-
* the factory transitions from `'opening'` to `'active'`.
|
|
263
|
-
*
|
|
264
|
-
* Uses the full WOTS lease cycle: reserve → sign → verify → commit.
|
|
265
|
-
*
|
|
266
|
-
* @param factory - Factory in `'opening'` status returned by `createFactory`.
|
|
267
|
-
* @param leaseProvider - This counterparty's WOTS lease provider.
|
|
268
|
-
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
269
|
-
* must match a registered participant not yet signed).
|
|
270
|
-
*/
|
|
271
|
-
export async function acceptFactory(
|
|
272
|
-
factory: ChannelFactory,
|
|
273
|
-
bundle: WotsLeaseBundle,
|
|
274
|
-
): Promise<ChannelFactory> {
|
|
275
|
-
if (factory.status !== 'opening') {
|
|
276
|
-
throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
|
|
277
|
-
}
|
|
278
|
-
if (!factory.pendingCommitment) {
|
|
279
|
-
throw new Error('Factory has no pending commitment — internal state error');
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
const participant = factory.participants.find(
|
|
283
|
-
p => p.publicKeyDigest === bundle.signer.publicKeyDigest,
|
|
284
|
-
);
|
|
285
|
-
if (!participant) {
|
|
286
|
-
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
287
|
-
}
|
|
288
|
-
if (factory.pendingSignatures[participant.partyId]) {
|
|
289
|
-
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
293
|
-
const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
|
|
294
|
-
|
|
295
|
-
const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
|
|
296
|
-
const updatedFactory = { ...factory, pendingSignatures: newSigs };
|
|
297
|
-
|
|
298
|
-
// When all N parties have signed, commit the opening.
|
|
299
|
-
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
300
|
-
if (allSigned) {
|
|
301
|
-
return commitOpening(updatedFactory);
|
|
302
|
-
}
|
|
303
|
-
return updatedFactory;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
function commitOpening(factory: ChannelFactory): ChannelFactory {
|
|
307
|
-
const logEntry: FactoryLogEntry = {
|
|
308
|
-
sequence: 1,
|
|
309
|
-
timestamp: Date.now(),
|
|
310
|
-
event: 'accept',
|
|
311
|
-
allocations: { ...factory.allocations },
|
|
312
|
-
virtualChannelIds: [],
|
|
313
|
-
};
|
|
314
|
-
const committed: ChannelFactory = {
|
|
315
|
-
...factory,
|
|
316
|
-
currentSequence: 1,
|
|
317
|
-
status: 'active',
|
|
318
|
-
pendingCommitment: undefined,
|
|
319
|
-
pendingSignatures: {},
|
|
320
|
-
stateLog: [...factory.stateLog, logEntry],
|
|
321
|
-
};
|
|
322
|
-
enforceConservation(committed);
|
|
323
|
-
return committed;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
// ─── reallocate ───────────────────────────────────────────────────────────────
|
|
327
|
-
|
|
328
|
-
/**
|
|
329
|
-
* Move factory allocation between two participants (atomic N-of-N).
|
|
330
|
-
*
|
|
331
|
-
* All N leaseProviders must be supplied; each party signs the new state
|
|
332
|
-
* commitment in turn. The state commits atomically — no intermediate "pending"
|
|
333
|
-
* object is returned.
|
|
334
|
-
*
|
|
335
|
-
* @param factory - Active factory.
|
|
336
|
-
* @param fromPartyId - Party giving up allocation.
|
|
337
|
-
* @param toPartyId - Party receiving allocation.
|
|
338
|
-
* @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
|
|
339
|
-
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
340
|
-
*/
|
|
341
|
-
export async function reallocate(
|
|
342
|
-
factory: ChannelFactory,
|
|
343
|
-
fromPartyId: string,
|
|
344
|
-
toPartyId: string,
|
|
345
|
-
amount: bigint,
|
|
346
|
-
leaseProviders: Record<string, WotsLeaseBundle>,
|
|
347
|
-
): Promise<ChannelFactory> {
|
|
348
|
-
if (factory.status !== 'active') {
|
|
349
|
-
throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
|
|
350
|
-
}
|
|
351
|
-
if (amount <= 0n) {
|
|
352
|
-
throw new Error(`Reallocation amount must be positive, got ${amount}`);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
const fromAlloc = factory.allocations[fromPartyId] ?? 0n;
|
|
356
|
-
if (fromAlloc < amount) {
|
|
357
|
-
throw new Error(`Insufficient allocation for '${fromPartyId}': has ${fromAlloc}, needs ${amount}`);
|
|
358
|
-
}
|
|
359
|
-
if (!factory.participants.find(p => p.partyId === toPartyId)) {
|
|
360
|
-
throw new Error(`'${toPartyId}' is not a registered factory participant`);
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
const newAllocations: Record<string, bigint> = {
|
|
364
|
-
...factory.allocations,
|
|
365
|
-
[fromPartyId]: fromAlloc - amount,
|
|
366
|
-
[toPartyId]: (factory.allocations[toPartyId] ?? 0n) + amount,
|
|
367
|
-
};
|
|
368
|
-
const newSequence = factory.currentSequence + 1;
|
|
369
|
-
const vcIds = factory.virtualChannels.map(vc => vc.channelId);
|
|
370
|
-
|
|
371
|
-
const commitment = computeFactoryStateCommitment(
|
|
372
|
-
factory.factoryId,
|
|
373
|
-
newSequence,
|
|
374
|
-
newAllocations,
|
|
375
|
-
vcIds,
|
|
376
|
-
);
|
|
377
|
-
|
|
378
|
-
await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
|
|
379
|
-
|
|
380
|
-
const logEntry: FactoryLogEntry = {
|
|
381
|
-
sequence: newSequence,
|
|
382
|
-
timestamp: Date.now(),
|
|
383
|
-
event: 'reallocate',
|
|
384
|
-
allocations: newAllocations,
|
|
385
|
-
virtualChannelIds: vcIds,
|
|
386
|
-
};
|
|
387
|
-
|
|
388
|
-
const updated: ChannelFactory = {
|
|
389
|
-
...factory,
|
|
390
|
-
allocations: newAllocations,
|
|
391
|
-
currentSequence: newSequence,
|
|
392
|
-
stateLog: [...factory.stateLog, logEntry],
|
|
393
|
-
};
|
|
394
|
-
|
|
395
|
-
enforceConservation(updated);
|
|
396
|
-
return updated;
|
|
397
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
FactoryStatus,
|
|
3
|
-
FactoryParticipant,
|
|
4
|
-
FactorySignature,
|
|
5
|
-
FactoryLogEntry,
|
|
6
|
-
ChannelFactory,
|
|
7
|
-
FactorySettlementPayload,
|
|
8
|
-
FactoryDisputePayload,
|
|
9
|
-
FactoryLeaseOps,
|
|
10
|
-
WotsLeaseBundle,
|
|
11
|
-
OmniaChannel,
|
|
12
|
-
} from './types.js';
|
|
13
|
-
|
|
14
|
-
export {
|
|
15
|
-
buildFactoryScript,
|
|
16
|
-
buildAndHashFactoryScript,
|
|
17
|
-
scriptAddress,
|
|
18
|
-
normalizeScript,
|
|
19
|
-
} from './script.js';
|
|
20
|
-
|
|
21
|
-
export { computeFactoryStateCommitment } from './commitment.js';
|
|
22
|
-
|
|
23
|
-
export {
|
|
24
|
-
createFactory,
|
|
25
|
-
acceptFactory,
|
|
26
|
-
reallocate,
|
|
27
|
-
enforceConservation,
|
|
28
|
-
} from './factory.js';
|
|
29
|
-
|
|
30
|
-
export {
|
|
31
|
-
openVirtualChannel,
|
|
32
|
-
closeVirtualChannel,
|
|
33
|
-
} from './virtual.js';
|
|
34
|
-
|
|
35
|
-
export {
|
|
36
|
-
closeFactory,
|
|
37
|
-
buildDisputePayload,
|
|
38
|
-
} from './settlement.js';
|
package/src/script.ts
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { computeScriptAddress } from '@totemsdk/core';
|
|
2
|
-
import type { FactoryParticipant } from './types.js';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Normalize a hex public key digest to the KISSVM-compatible format:
|
|
6
|
-
* strip leading 0x/0X and render as upper-case hex with leading '0X'.
|
|
7
|
-
*/
|
|
8
|
-
function kissHex(hex: string): string {
|
|
9
|
-
const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
|
|
10
|
-
return '0X' + raw.toUpperCase();
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Build the N-of-N MULTISIG MAST funding script for a channel factory.
|
|
15
|
-
*
|
|
16
|
-
* Spending rules:
|
|
17
|
-
* - Any cooperative close (SETTLEMENT=true): all N parties sign, spend after
|
|
18
|
-
* minimal coinage (1 block) so the factory can be closed immediately after
|
|
19
|
-
* a confirmed update.
|
|
20
|
-
* - Non-settlement path: all N parties must still sign (ASSERT MULTISIG(N ...))
|
|
21
|
-
* but can spend in the same block (no coinage requirement) — used for future
|
|
22
|
-
* optimistic factory updates if desired.
|
|
23
|
-
*
|
|
24
|
-
* `storestate=true` is achieved by encoding STATE(100) in the output state
|
|
25
|
-
* variables of every factory TX.
|
|
26
|
-
*
|
|
27
|
-
* Minimum 2 participants required.
|
|
28
|
-
*/
|
|
29
|
-
export function buildFactoryScript(participants: FactoryParticipant[]): string {
|
|
30
|
-
if (participants.length < 2) {
|
|
31
|
-
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
32
|
-
}
|
|
33
|
-
const n = participants.length;
|
|
34
|
-
const pks = participants.map(p => kissHex(p.publicKeyDigest)).join(' ');
|
|
35
|
-
|
|
36
|
-
return [
|
|
37
|
-
'LET SETTLEMENT=STATE(100)',
|
|
38
|
-
`ASSERT MULTISIG(${n} ${pks})`,
|
|
39
|
-
'IF SETTLEMENT THEN',
|
|
40
|
-
' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF',
|
|
41
|
-
'ELSE',
|
|
42
|
-
' RETURN TRUE',
|
|
43
|
-
'ENDIF',
|
|
44
|
-
].join('\n');
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function normalizeScript(script: string): string {
|
|
48
|
-
return script.trim().toUpperCase();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Compute the SHA3-256 script-hash address for a factory script. */
|
|
52
|
-
export function scriptAddress(script: string): string {
|
|
53
|
-
return computeScriptAddress(script);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Build the factory script and compute its canonical address in one step.
|
|
58
|
-
* The address is used as the output address of the factory funding TX.
|
|
59
|
-
*/
|
|
60
|
-
export function buildAndHashFactoryScript(participants: FactoryParticipant[]): {
|
|
61
|
-
script: string;
|
|
62
|
-
address: string;
|
|
63
|
-
} {
|
|
64
|
-
const script = buildFactoryScript(participants);
|
|
65
|
-
const address = scriptAddress(script);
|
|
66
|
-
return { script, address };
|
|
67
|
-
}
|