@ocap/util 1.30.26 → 1.31.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/esm/amm.d.mts +158 -0
- package/esm/amm.mjs +269 -0
- package/esm/arcade.d.mts +217 -0
- package/esm/arcade.mjs +484 -0
- package/esm/bonding-reserve-aup.d.mts +125 -0
- package/esm/bonding-reserve-aup.mjs +230 -0
- package/esm/composable-container.d.mts +141 -0
- package/esm/composable-container.mjs +264 -0
- package/esm/conditional-market.d.mts +151 -0
- package/esm/conditional-market.mjs +376 -0
- package/esm/curve.d.mts +43 -5
- package/esm/curve.mjs +71 -9
- package/esm/foreign-receipt.d.mts +126 -0
- package/esm/foreign-receipt.mjs +388 -0
- package/esm/index.d.mts +8 -1
- package/esm/index.mjs +8 -1
- package/esm/node_modules/@noble/hashes/_md.mjs +168 -0
- package/esm/node_modules/@noble/hashes/sha2.mjs +185 -0
- package/esm/node_modules/@noble/hashes/utils.mjs +175 -0
- package/lib/amm.cjs +279 -0
- package/lib/amm.d.cts +158 -0
- package/lib/arcade.cjs +491 -0
- package/lib/arcade.d.cts +217 -0
- package/lib/bonding-reserve-aup.cjs +232 -0
- package/lib/bonding-reserve-aup.d.cts +125 -0
- package/lib/composable-container.cjs +270 -0
- package/lib/composable-container.d.cts +141 -0
- package/lib/conditional-market.cjs +377 -0
- package/lib/conditional-market.d.cts +151 -0
- package/lib/curve.cjs +73 -9
- package/lib/curve.d.cts +43 -5
- package/lib/foreign-receipt.cjs +396 -0
- package/lib/foreign-receipt.d.cts +126 -0
- package/lib/index.cjs +57 -1
- package/lib/index.d.cts +8 -1
- package/lib/node_modules/@noble/hashes/_md.cjs +171 -0
- package/lib/node_modules/@noble/hashes/sha2.cjs +185 -0
- package/lib/node_modules/@noble/hashes/utils.cjs +183 -0
- package/package.json +2 -2
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { sha256 } from "./node_modules/@noble/hashes/sha2.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/bonding-reserve-aup.ts
|
|
4
|
+
const utf8Encoder = new TextEncoder();
|
|
5
|
+
function toHex(bytes) {
|
|
6
|
+
let out = "";
|
|
7
|
+
for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
function sha256Hex(input) {
|
|
11
|
+
return toHex(sha256(utf8Encoder.encode(input)));
|
|
12
|
+
}
|
|
13
|
+
function parseNonNegativeBigInt(value, label) {
|
|
14
|
+
let parsed;
|
|
15
|
+
if (typeof value === "bigint") parsed = value;
|
|
16
|
+
else if (typeof value === "number") {
|
|
17
|
+
if (!Number.isSafeInteger(value)) throw new Error(`Invalid ${label}: must be a safe integer`);
|
|
18
|
+
parsed = BigInt(value);
|
|
19
|
+
} else if (typeof value === "string") {
|
|
20
|
+
const trimmed = value.trim();
|
|
21
|
+
if (!/^-?\d+$/.test(trimmed)) throw new Error(`Invalid ${label}: must be a base-10 integer string`);
|
|
22
|
+
parsed = BigInt(trimmed);
|
|
23
|
+
} else throw new Error(`Invalid ${label}: must be an integer`);
|
|
24
|
+
if (parsed < 0n) throw new Error(`Invalid ${label}: must be non-negative`);
|
|
25
|
+
return parsed;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Quotes the deterministic bonding curve mint price at `supplyIndex` and computes the exact
|
|
29
|
+
* 4-bucket split (`reserveCut + devCut + studioKeyCut + protocolFeeCut === grossPrice`).
|
|
30
|
+
* Any integer rounding remainder is retained in `reserveCut` so floor solvency never leaks.
|
|
31
|
+
*/
|
|
32
|
+
function quoteBondingCurveMint(config, supplyIndex) {
|
|
33
|
+
const s = parseNonNegativeBigInt(supplyIndex, "supplyIndex");
|
|
34
|
+
const basePrice = parseNonNegativeBigInt(config.basePrice, "basePrice");
|
|
35
|
+
const slope = parseNonNegativeBigInt(config.linearSlope, "linearSlope");
|
|
36
|
+
if (basePrice <= 0n) throw new Error("BondingCurveMintConfig requires positive basePrice");
|
|
37
|
+
const { reserveBps, devBps, studioKeyBps, protocolFeeBps } = config;
|
|
38
|
+
if (!Number.isSafeInteger(reserveBps) || reserveBps <= 0 || reserveBps > 1e4) throw new Error("Invalid reserveBps: must be an integer between 1 and 10000");
|
|
39
|
+
for (const [label, val] of [
|
|
40
|
+
["devBps", devBps],
|
|
41
|
+
["studioKeyBps", studioKeyBps],
|
|
42
|
+
["protocolFeeBps", protocolFeeBps]
|
|
43
|
+
]) if (!Number.isSafeInteger(val) || val < 0 || val > 1e4) throw new Error(`Invalid ${label}: must be an integer between 0 and 10000`);
|
|
44
|
+
if (reserveBps + devBps + studioKeyBps + protocolFeeBps !== 1e4) throw new Error("BondingCurveMintConfig bps must sum to 10000");
|
|
45
|
+
const grossPrice = basePrice + slope * s;
|
|
46
|
+
const devCut = grossPrice * BigInt(devBps) / 10000n;
|
|
47
|
+
const studioKeyCut = grossPrice * BigInt(studioKeyBps) / 10000n;
|
|
48
|
+
const protocolFeeCut = grossPrice * BigInt(protocolFeeBps) / 10000n;
|
|
49
|
+
return {
|
|
50
|
+
supplyIndex: s,
|
|
51
|
+
grossPrice,
|
|
52
|
+
reserveCut: grossPrice - devCut - studioKeyCut - protocolFeeCut,
|
|
53
|
+
devCut,
|
|
54
|
+
studioKeyCut,
|
|
55
|
+
protocolFeeCut
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Stateful Reserve Vault for Bonding-Curve Asset Factories (#1185):
|
|
60
|
+
* - Isolates `reserveBucket` (strictly backing asset floor redemptions; developer can never withdraw it)
|
|
61
|
+
* from `devBucket`, `studioKeyBucket`, and `protocolFeeBucket`.
|
|
62
|
+
* - Supports guaranteed floor burn redemption (`redeemAssetFloor`), returning the asset's locked
|
|
63
|
+
* floor reserve (plus any mounted owned child reserves) upon burn.
|
|
64
|
+
*/
|
|
65
|
+
var BondingReserveVault = class {
|
|
66
|
+
constructor(config) {
|
|
67
|
+
this.currentSupply = 0n;
|
|
68
|
+
this.activeCirculatingCount = 0n;
|
|
69
|
+
this.reserveBucket = 0n;
|
|
70
|
+
this.devBucket = 0n;
|
|
71
|
+
this.studioKeyBucket = 0n;
|
|
72
|
+
this.protocolFeeBucket = 0n;
|
|
73
|
+
this.assets = /* @__PURE__ */ new Map();
|
|
74
|
+
if (!config.factoryDid || !config.factoryDid.trim()) throw new Error("factoryDid is required");
|
|
75
|
+
quoteBondingCurveMint(config, 0n);
|
|
76
|
+
this.config = {
|
|
77
|
+
...config,
|
|
78
|
+
factoryDid: config.factoryDid.trim()
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
getBuckets() {
|
|
82
|
+
return {
|
|
83
|
+
currentSupply: this.currentSupply,
|
|
84
|
+
activeCirculatingCount: this.activeCirculatingCount,
|
|
85
|
+
reserveBucket: this.reserveBucket,
|
|
86
|
+
devBucket: this.devBucket,
|
|
87
|
+
studioKeyBucket: this.studioKeyBucket,
|
|
88
|
+
protocolFeeBucket: this.protocolFeeBucket
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
mintAsset(params) {
|
|
92
|
+
const assetDid = params.assetDid?.trim();
|
|
93
|
+
const ownerDid = params.ownerDid?.trim();
|
|
94
|
+
if (!assetDid || !ownerDid) throw new Error("assetDid and ownerDid are required");
|
|
95
|
+
if (this.assets.has(assetDid)) throw new Error(`DUPLICATE_ASSET_DID: ${assetDid} already minted`);
|
|
96
|
+
const quote = quoteBondingCurveMint(this.config, this.currentSupply);
|
|
97
|
+
this.currentSupply += 1n;
|
|
98
|
+
this.activeCirculatingCount += 1n;
|
|
99
|
+
this.reserveBucket += quote.reserveCut;
|
|
100
|
+
this.devBucket += quote.devCut;
|
|
101
|
+
this.studioKeyBucket += quote.studioKeyCut;
|
|
102
|
+
this.protocolFeeBucket += quote.protocolFeeCut;
|
|
103
|
+
const record = {
|
|
104
|
+
assetDid,
|
|
105
|
+
ownerDid,
|
|
106
|
+
supplyIndex: quote.supplyIndex,
|
|
107
|
+
lockedFloorReserve: quote.reserveCut,
|
|
108
|
+
burned: false
|
|
109
|
+
};
|
|
110
|
+
this.assets.set(assetDid, record);
|
|
111
|
+
return {
|
|
112
|
+
record: { ...record },
|
|
113
|
+
quote
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Burns an unmounted asset and releases its exact `lockedFloorReserve` from `reserveBucket`.
|
|
118
|
+
* Proves anti-rug conservation: `reserveBucket` always covers the sum of all unburned assets' `lockedFloorReserve`.
|
|
119
|
+
*/
|
|
120
|
+
redeemAssetFloor(params) {
|
|
121
|
+
const record = this.assets.get(params.assetDid?.trim());
|
|
122
|
+
if (!record) throw new Error(`ASSET_NOT_FOUND: ${params.assetDid}`);
|
|
123
|
+
if (record.burned) throw new Error(`ASSET_ALREADY_BURNED: ${record.assetDid}`);
|
|
124
|
+
const callerDid = params.callerDid?.trim();
|
|
125
|
+
if (record.ownerDid !== callerDid) throw new Error(`REDEMPTION_OWNER_MISMATCH: ${params.callerDid} does not own ${record.assetDid}`);
|
|
126
|
+
if (params.independentRedemptionFrozen) throw new Error(`ASSET_MOUNTED_FROZEN: ${record.assetDid} is currently mounted and cannot be burned`);
|
|
127
|
+
if (this.reserveBucket < record.lockedFloorReserve) throw new Error("RESERVE_SOLVENCY_VIOLATION: reserveBucket below lockedFloorReserve");
|
|
128
|
+
record.burned = true;
|
|
129
|
+
this.activeCirculatingCount -= 1n;
|
|
130
|
+
this.reserveBucket -= record.lockedFloorReserve;
|
|
131
|
+
return {
|
|
132
|
+
redeemedAmount: record.lockedFloorReserve,
|
|
133
|
+
remainingReserveBucket: this.reserveBucket
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const VALID_VIEW_FORMATS = new Set([
|
|
138
|
+
"2d-sprite",
|
|
139
|
+
"2d-board-ui",
|
|
140
|
+
"3d-gltf",
|
|
141
|
+
"3d-vrm",
|
|
142
|
+
"3d-voxel"
|
|
143
|
+
]);
|
|
144
|
+
/**
|
|
145
|
+
* Deterministically resolves multi-layer generative traits from `(templateId, assetDid, mintSeed)`
|
|
146
|
+
* and binds cross-game 2D/3D multi-view representations (`2d-sprite`, `2d-board-ui`, `3d-gltf`, `3d-vrm`, `3d-voxel`)
|
|
147
|
+
* into a canonical AUP Multi-View Asset Manifest (#1186).
|
|
148
|
+
*/
|
|
149
|
+
function buildAupMultiViewManifest(params) {
|
|
150
|
+
if (!params.templateId || !params.templateId.trim()) throw new Error("templateId is required");
|
|
151
|
+
if (!params.assetDid || !params.assetDid.trim()) throw new Error("assetDid is required");
|
|
152
|
+
if (!params.category || !params.category.trim()) throw new Error("category is required");
|
|
153
|
+
if (!params.mintSeed || !params.mintSeed.trim()) throw new Error("mintSeed is required");
|
|
154
|
+
if (!Array.isArray(params.views) || params.views.length === 0) throw new Error("At least one 2D/3D AssetViewDescriptor is required");
|
|
155
|
+
const seenViewKeys = /* @__PURE__ */ new Set();
|
|
156
|
+
for (const view of params.views) {
|
|
157
|
+
if (!VALID_VIEW_FORMATS.has(view.format)) throw new Error(`Unsupported view format: ${view.format}`);
|
|
158
|
+
if (!view.uri || !view.uri.trim()) throw new Error(`View ${view.format} requires a non-empty uri`);
|
|
159
|
+
if (!view.contentHash || !/^[0-9a-fA-F]{64}$/.test(view.contentHash.trim())) throw new Error(`View ${view.format} requires a 64-hex SHA-256 contentHash`);
|
|
160
|
+
if (view.lodLevel !== void 0 && (!Number.isSafeInteger(view.lodLevel) || view.lodLevel < 0)) throw new Error(`View ${view.format} has invalid lodLevel: must be a non-negative integer`);
|
|
161
|
+
const viewKey = `${view.format}:${view.lodLevel ?? 0}`;
|
|
162
|
+
if (seenViewKeys.has(viewKey)) throw new Error(`DUPLICATE_VIEW_DESCRIPTOR: ${viewKey}`);
|
|
163
|
+
seenViewKeys.add(viewKey);
|
|
164
|
+
}
|
|
165
|
+
const coreTraits = Object.create(null);
|
|
166
|
+
const seenLayerKeys = /* @__PURE__ */ new Set();
|
|
167
|
+
for (const layer of params.traitLayers) {
|
|
168
|
+
const layerKey = layer.layerKey?.trim();
|
|
169
|
+
if (!layerKey || layerKey === "__proto__" || layerKey === "constructor" || layerKey === "prototype") throw new Error(`Invalid trait layer ${layer.layerKey || "<unnamed>"}`);
|
|
170
|
+
if (seenLayerKeys.has(layerKey)) throw new Error(`DUPLICATE_TRAIT_LAYER: ${layerKey}`);
|
|
171
|
+
seenLayerKeys.add(layerKey);
|
|
172
|
+
if (!Array.isArray(layer.options) || layer.options.length === 0) throw new Error(`Invalid trait layer ${layerKey}`);
|
|
173
|
+
let totalWeight = 0n;
|
|
174
|
+
for (const opt of layer.options) {
|
|
175
|
+
if (!Number.isSafeInteger(opt.weight) || opt.weight <= 0) throw new Error(`Invalid weight for option ${opt.optionId} in layer ${layerKey}`);
|
|
176
|
+
if (typeof opt.traitValue === "number" && !Number.isFinite(opt.traitValue)) throw new Error(`Invalid numeric traitValue for option ${opt.optionId} in layer ${layerKey}`);
|
|
177
|
+
totalWeight += BigInt(opt.weight);
|
|
178
|
+
}
|
|
179
|
+
const layerEntropyHex = sha256Hex(JSON.stringify({
|
|
180
|
+
domain: "arcblock.aup.trait.v1",
|
|
181
|
+
templateId: params.templateId.trim(),
|
|
182
|
+
assetDid: params.assetDid.trim(),
|
|
183
|
+
mintSeed: params.mintSeed.trim(),
|
|
184
|
+
layerKey
|
|
185
|
+
}));
|
|
186
|
+
const roll = BigInt(`0x${layerEntropyHex}`) % totalWeight;
|
|
187
|
+
let cumulative = 0n;
|
|
188
|
+
let selected = layer.options[layer.options.length - 1];
|
|
189
|
+
for (const opt of layer.options) {
|
|
190
|
+
cumulative += BigInt(opt.weight);
|
|
191
|
+
if (roll < cumulative) {
|
|
192
|
+
selected = opt;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
coreTraits[layerKey] = selected.traitValue;
|
|
197
|
+
}
|
|
198
|
+
const sortedTraitKeys = Object.keys(coreTraits).sort();
|
|
199
|
+
const canonicalTraits = Object.create(null);
|
|
200
|
+
for (const k of sortedTraitKeys) canonicalTraits[k] = coreTraits[k];
|
|
201
|
+
const normalizedViews = params.views.map((v) => ({
|
|
202
|
+
format: v.format,
|
|
203
|
+
uri: v.uri.trim(),
|
|
204
|
+
contentHash: v.contentHash.trim().toLowerCase(),
|
|
205
|
+
...v.lodLevel !== void 0 ? { lodLevel: v.lodLevel } : {}
|
|
206
|
+
}));
|
|
207
|
+
const normalizedPresetId = params.applianceRulePresetId?.trim() || void 0;
|
|
208
|
+
const digestPayload = JSON.stringify({
|
|
209
|
+
schemaVersion: "aup.multiview.v1",
|
|
210
|
+
templateId: params.templateId.trim(),
|
|
211
|
+
assetDid: params.assetDid.trim(),
|
|
212
|
+
category: params.category.trim(),
|
|
213
|
+
coreTraits: canonicalTraits,
|
|
214
|
+
views: normalizedViews,
|
|
215
|
+
applianceRulePresetId: normalizedPresetId ?? null
|
|
216
|
+
});
|
|
217
|
+
return {
|
|
218
|
+
schemaVersion: "aup.multiview.v1",
|
|
219
|
+
templateId: params.templateId.trim(),
|
|
220
|
+
assetDid: params.assetDid.trim(),
|
|
221
|
+
category: params.category.trim(),
|
|
222
|
+
coreTraits: canonicalTraits,
|
|
223
|
+
views: normalizedViews,
|
|
224
|
+
...normalizedPresetId ? { applianceRulePresetId: normalizedPresetId } : {},
|
|
225
|
+
manifestDigest: sha256Hex(digestPayload)
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
//#endregion
|
|
230
|
+
export { BondingReserveVault, buildAupMultiViewManifest, quoteBondingCurveMint };
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
//#region src/composable-container.d.ts
|
|
2
|
+
type SlotMountMode = 'OWNED' | 'LEASED';
|
|
3
|
+
interface ContainerSlotDefinition {
|
|
4
|
+
slotKey: string;
|
|
5
|
+
allowedCategories: readonly string[];
|
|
6
|
+
allowedMountModes?: readonly SlotMountMode[];
|
|
7
|
+
required?: boolean;
|
|
8
|
+
}
|
|
9
|
+
interface LeaseMountTerms {
|
|
10
|
+
lessorDid: string;
|
|
11
|
+
lesseeHostDid: string;
|
|
12
|
+
hostBps: number;
|
|
13
|
+
leaseExpiresAt: number;
|
|
14
|
+
allowEarlyLessorRecall?: boolean;
|
|
15
|
+
}
|
|
16
|
+
interface MountedSlotAssignment {
|
|
17
|
+
slotKey: string;
|
|
18
|
+
childDid: string;
|
|
19
|
+
childCategory: string;
|
|
20
|
+
mountMode: SlotMountMode;
|
|
21
|
+
childFloorReserveValue: bigint;
|
|
22
|
+
mountedAt: number;
|
|
23
|
+
leaseTerms?: LeaseMountTerms;
|
|
24
|
+
}
|
|
25
|
+
interface ComposableAssetNode {
|
|
26
|
+
did: string;
|
|
27
|
+
ownerDid: string;
|
|
28
|
+
category: string;
|
|
29
|
+
baseFloorReserveValue: bigint;
|
|
30
|
+
aggregatedFloorReserveValue: bigint;
|
|
31
|
+
mountedInParentDid?: string | null;
|
|
32
|
+
independentRedemptionFrozen: boolean;
|
|
33
|
+
slotDefinitions: readonly ContainerSlotDefinition[];
|
|
34
|
+
mountedSlots: Record<string, MountedSlotAssignment>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Creates a new ComposableAssetNode with verified initial floor reserve invariants.
|
|
38
|
+
*/
|
|
39
|
+
declare function createComposableAssetNode(params: {
|
|
40
|
+
did: string;
|
|
41
|
+
ownerDid: string;
|
|
42
|
+
category: string;
|
|
43
|
+
baseFloorReserveValue: bigint | number | string;
|
|
44
|
+
slotDefinitions?: readonly ContainerSlotDefinition[];
|
|
45
|
+
}): ComposableAssetNode;
|
|
46
|
+
/**
|
|
47
|
+
* Checks ancestry and subtree depth in a registry of ComposableAssetNodes to prevent
|
|
48
|
+
* circular container mounting (`A -> B -> A`) and enforce `maxDepth` in both top-down
|
|
49
|
+
* and bottom-up mounting orders.
|
|
50
|
+
*/
|
|
51
|
+
declare function assertNoContainerCycle(parentDid: string, childDid: string, assetRegistry: Record<string, Pick<ComposableAssetNode, 'did' | 'mountedInParentDid'> & Partial<Pick<ComposableAssetNode, 'mountedSlots'>>>, maxDepth?: number): void;
|
|
52
|
+
/**
|
|
53
|
+
* Mounts a child NFT (e.g. a mecha part, furniture item, slot machine, or card game table)
|
|
54
|
+
* into a parent container NFT slot in either `OWNED` or `LEASED` mode.
|
|
55
|
+
*
|
|
56
|
+
* Security & Economic Invariants:
|
|
57
|
+
* - Enforces bottom-up mounting: `parent` itself must be unmounted (`!parent.mountedInParentDid && !parent.independentRedemptionFrozen`)
|
|
58
|
+
* so ancestor `aggregatedFloorReserveValue` can never be desynchronized.
|
|
59
|
+
* - `OWNED` mode: `parent.ownerDid === child.ownerDid === callerDid`. Freezes child's independent
|
|
60
|
+
* redemption and adds `child.aggregatedFloorReserveValue` into `parent.aggregatedFloorReserveValue`.
|
|
61
|
+
* Forbids mounting a child container that holds `LEASED` slots inside an outer container.
|
|
62
|
+
* - `LEASED` mode: `parent.ownerDid === leaseTerms.lesseeHostDid` and `child.ownerDid === leaseTerms.lessorDid`.
|
|
63
|
+
* Freezes child's independent floor burn while mounted, but does NOT merge the lessor's floor
|
|
64
|
+
* reserve into the host's container floor value (so the island host can never strip or burn
|
|
65
|
+
* a leased machine's bankroll).
|
|
66
|
+
*/
|
|
67
|
+
declare function mountContainerSlotItem(params: {
|
|
68
|
+
parent: ComposableAssetNode;
|
|
69
|
+
child: ComposableAssetNode;
|
|
70
|
+
slotKey: string;
|
|
71
|
+
mountMode: SlotMountMode;
|
|
72
|
+
callerDid: string;
|
|
73
|
+
timestamp: number;
|
|
74
|
+
leaseTerms?: LeaseMountTerms;
|
|
75
|
+
assetRegistry?: Record<string, Pick<ComposableAssetNode, 'did' | 'mountedInParentDid'> & Partial<Pick<ComposableAssetNode, 'mountedSlots'>>>;
|
|
76
|
+
maxDepth?: number;
|
|
77
|
+
}): {
|
|
78
|
+
parent: ComposableAssetNode;
|
|
79
|
+
child: ComposableAssetNode;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Unmounts a child NFT from a parent container slot and restores its independent redemption status.
|
|
83
|
+
*
|
|
84
|
+
* - Enforces top-down unmounting: `parent` itself must be unmounted (`!parent.mountedInParentDid && !parent.independentRedemptionFrozen`).
|
|
85
|
+
* - For `OWNED` mounts: only `parent.ownerDid` can unmount, and `childFloorReserveValue` is subtracted
|
|
86
|
+
* from `parent.aggregatedFloorReserveValue`.
|
|
87
|
+
* - For `LEASED` mounts: `lesseeHostDid` can unmount at any time; `lessorDid` can unmount once
|
|
88
|
+
* `timestamp >= leaseExpiresAt` (or anytime if `allowEarlyLessorRecall` is true).
|
|
89
|
+
*/
|
|
90
|
+
declare function unmountContainerSlotItem(params: {
|
|
91
|
+
parent: ComposableAssetNode;
|
|
92
|
+
child: ComposableAssetNode;
|
|
93
|
+
slotKey: string;
|
|
94
|
+
callerDid: string;
|
|
95
|
+
timestamp: number;
|
|
96
|
+
}): {
|
|
97
|
+
parent: ComposableAssetNode;
|
|
98
|
+
child: ComposableAssetNode;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Verifies whether an asset node is eligible for floor-burn redemption or transfer:
|
|
102
|
+
* - Mounted children (`independentRedemptionFrozen === true`) cannot be independently burned or transferred.
|
|
103
|
+
* - A parent container holding a `LEASED` child cannot be burned or transferred until all leased
|
|
104
|
+
* machines are unmounted and returned to their lessors.
|
|
105
|
+
*/
|
|
106
|
+
declare function assertAssetRedeemableOrTransferable(asset: ComposableAssetNode, operation: 'REDEEM_BURN' | 'TRANSFER'): void;
|
|
107
|
+
interface SynthesisRecipeRequirement {
|
|
108
|
+
category: string;
|
|
109
|
+
count: number;
|
|
110
|
+
}
|
|
111
|
+
interface SynthesisRecipe {
|
|
112
|
+
recipeId: string;
|
|
113
|
+
outputCategory: string;
|
|
114
|
+
requirements: readonly SynthesisRecipeRequirement[];
|
|
115
|
+
extraCatalystFeeReserve?: bigint;
|
|
116
|
+
protocolFeeBps?: number;
|
|
117
|
+
}
|
|
118
|
+
interface SynthesisExecutionResult {
|
|
119
|
+
outputAsset: ComposableAssetNode;
|
|
120
|
+
burnedInputDids: string[];
|
|
121
|
+
totalInputReserveConsumed: bigint;
|
|
122
|
+
protocolFeeReserve: bigint;
|
|
123
|
+
netOutputFloorReserve: bigint;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Executes a deterministic N-to-1 consumable alchemy synthesis (`synthesizeContainerRecipe`):
|
|
127
|
+
* - Verifies all ingredient assets belong to `callerDid`, are unmounted, and have no mounted slots.
|
|
128
|
+
* - Matches ingredient categories against `recipe.requirements` (rejecting duplicate category rules).
|
|
129
|
+
* - Conserves underlying floor reserve value:
|
|
130
|
+
* `netOutputFloorReserve + protocolFeeReserve === sum(input.aggregatedFloorReserveValue) + extraCatalystReserveAdded`.
|
|
131
|
+
*/
|
|
132
|
+
declare function synthesizeContainerRecipe(params: {
|
|
133
|
+
recipe: SynthesisRecipe;
|
|
134
|
+
ingredients: readonly ComposableAssetNode[];
|
|
135
|
+
outputDid: string;
|
|
136
|
+
callerDid: string;
|
|
137
|
+
extraCatalystReserveAdded?: bigint | number | string;
|
|
138
|
+
outputSlotDefinitions?: readonly ContainerSlotDefinition[];
|
|
139
|
+
}): SynthesisExecutionResult;
|
|
140
|
+
//#endregion
|
|
141
|
+
export { ComposableAssetNode, ContainerSlotDefinition, LeaseMountTerms, MountedSlotAssignment, SlotMountMode, SynthesisExecutionResult, SynthesisRecipe, SynthesisRecipeRequirement, assertAssetRedeemableOrTransferable, assertNoContainerCycle, createComposableAssetNode, mountContainerSlotItem, synthesizeContainerRecipe, unmountContainerSlotItem };
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
//#region src/composable-container.ts
|
|
2
|
+
function parseNonNegativeBigInt(value, label) {
|
|
3
|
+
let parsed;
|
|
4
|
+
if (typeof value === "bigint") parsed = value;
|
|
5
|
+
else if (typeof value === "number") {
|
|
6
|
+
if (!Number.isSafeInteger(value)) throw new Error(`Invalid ${label}: must be a safe integer`);
|
|
7
|
+
parsed = BigInt(value);
|
|
8
|
+
} else if (typeof value === "string") {
|
|
9
|
+
const trimmed = value.trim();
|
|
10
|
+
if (!/^-?\d+$/.test(trimmed)) throw new Error(`Invalid ${label}: must be a base-10 integer string`);
|
|
11
|
+
parsed = BigInt(trimmed);
|
|
12
|
+
} else throw new Error(`Invalid ${label}: must be an integer`);
|
|
13
|
+
if (parsed < 0n) throw new Error(`Invalid ${label}: must be non-negative`);
|
|
14
|
+
return parsed;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates a new ComposableAssetNode with verified initial floor reserve invariants.
|
|
18
|
+
*/
|
|
19
|
+
function createComposableAssetNode(params) {
|
|
20
|
+
if (!params.did || !params.did.trim()) throw new Error("Asset did is required");
|
|
21
|
+
if (!params.ownerDid || !params.ownerDid.trim()) throw new Error("Asset ownerDid is required");
|
|
22
|
+
if (!params.category || !params.category.trim()) throw new Error("Asset category is required");
|
|
23
|
+
const baseFloor = parseNonNegativeBigInt(params.baseFloorReserveValue, "baseFloorReserveValue");
|
|
24
|
+
const normalizedSlots = [];
|
|
25
|
+
if (params.slotDefinitions) {
|
|
26
|
+
const seenSlotKeys = /* @__PURE__ */ new Set();
|
|
27
|
+
for (const def of params.slotDefinitions) {
|
|
28
|
+
const slotKey = def.slotKey?.trim();
|
|
29
|
+
if (!slotKey) throw new Error("Slot definition requires a non-empty slotKey");
|
|
30
|
+
if (seenSlotKeys.has(slotKey)) throw new Error(`DUPLICATE_SLOT_KEY: duplicate slot definition ${slotKey}`);
|
|
31
|
+
seenSlotKeys.add(slotKey);
|
|
32
|
+
if (!Array.isArray(def.allowedCategories) || def.allowedCategories.length === 0) throw new Error(`Slot ${slotKey} requires at least one allowedCategory`);
|
|
33
|
+
normalizedSlots.push({
|
|
34
|
+
...def,
|
|
35
|
+
slotKey,
|
|
36
|
+
allowedCategories: def.allowedCategories.map((c) => c.trim()).filter(Boolean)
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
did: params.did.trim(),
|
|
42
|
+
ownerDid: params.ownerDid.trim(),
|
|
43
|
+
category: params.category.trim(),
|
|
44
|
+
baseFloorReserveValue: baseFloor,
|
|
45
|
+
aggregatedFloorReserveValue: baseFloor,
|
|
46
|
+
mountedInParentDid: null,
|
|
47
|
+
independentRedemptionFrozen: false,
|
|
48
|
+
slotDefinitions: normalizedSlots,
|
|
49
|
+
mountedSlots: {}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Checks ancestry and subtree depth in a registry of ComposableAssetNodes to prevent
|
|
54
|
+
* circular container mounting (`A -> B -> A`) and enforce `maxDepth` in both top-down
|
|
55
|
+
* and bottom-up mounting orders.
|
|
56
|
+
*/
|
|
57
|
+
function assertNoContainerCycle(parentDid, childDid, assetRegistry, maxDepth = 8) {
|
|
58
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 1) throw new Error("Invalid maxDepth: must be a positive integer");
|
|
59
|
+
if (parentDid === childDid) throw new Error(`CONTAINER_CYCLE_DETECTED: asset ${parentDid} cannot be mounted into itself`);
|
|
60
|
+
let cursor = parentDid;
|
|
61
|
+
let upwardDepth = 0;
|
|
62
|
+
const visited = new Set([childDid]);
|
|
63
|
+
while (cursor) {
|
|
64
|
+
if (visited.has(cursor)) throw new Error(`CONTAINER_CYCLE_DETECTED: mounting ${childDid} into ${parentDid} creates a cycle at ${cursor}`);
|
|
65
|
+
visited.add(cursor);
|
|
66
|
+
upwardDepth += 1;
|
|
67
|
+
if (upwardDepth > maxDepth) throw new Error(`MAX_CONTAINER_DEPTH_EXCEEDED: container hierarchy exceeds maxDepth ${maxDepth}`);
|
|
68
|
+
cursor = Object.hasOwn(assetRegistry, cursor) ? assetRegistry[cursor]?.mountedInParentDid ?? null : null;
|
|
69
|
+
}
|
|
70
|
+
const measureSubtreeHeight = (did, pathSeen) => {
|
|
71
|
+
const node = Object.hasOwn(assetRegistry, did) ? assetRegistry[did] : void 0;
|
|
72
|
+
if (!node?.mountedSlots) return 0;
|
|
73
|
+
let maxChildHeight = 0;
|
|
74
|
+
for (const slot of Object.values(node.mountedSlots)) {
|
|
75
|
+
if (pathSeen.has(slot.childDid)) throw new Error(`CONTAINER_CYCLE_DETECTED: cycle detected in child subtree at ${slot.childDid}`);
|
|
76
|
+
const nextSeen = new Set(pathSeen);
|
|
77
|
+
nextSeen.add(slot.childDid);
|
|
78
|
+
const h = 1 + measureSubtreeHeight(slot.childDid, nextSeen);
|
|
79
|
+
if (h > maxChildHeight) maxChildHeight = h;
|
|
80
|
+
}
|
|
81
|
+
return maxChildHeight;
|
|
82
|
+
};
|
|
83
|
+
const childSubtreeHeight = measureSubtreeHeight(childDid, visited);
|
|
84
|
+
if (upwardDepth + childSubtreeHeight > maxDepth) throw new Error(`MAX_CONTAINER_DEPTH_EXCEEDED: container hierarchy exceeds maxDepth ${maxDepth}`);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Mounts a child NFT (e.g. a mecha part, furniture item, slot machine, or card game table)
|
|
88
|
+
* into a parent container NFT slot in either `OWNED` or `LEASED` mode.
|
|
89
|
+
*
|
|
90
|
+
* Security & Economic Invariants:
|
|
91
|
+
* - Enforces bottom-up mounting: `parent` itself must be unmounted (`!parent.mountedInParentDid && !parent.independentRedemptionFrozen`)
|
|
92
|
+
* so ancestor `aggregatedFloorReserveValue` can never be desynchronized.
|
|
93
|
+
* - `OWNED` mode: `parent.ownerDid === child.ownerDid === callerDid`. Freezes child's independent
|
|
94
|
+
* redemption and adds `child.aggregatedFloorReserveValue` into `parent.aggregatedFloorReserveValue`.
|
|
95
|
+
* Forbids mounting a child container that holds `LEASED` slots inside an outer container.
|
|
96
|
+
* - `LEASED` mode: `parent.ownerDid === leaseTerms.lesseeHostDid` and `child.ownerDid === leaseTerms.lessorDid`.
|
|
97
|
+
* Freezes child's independent floor burn while mounted, but does NOT merge the lessor's floor
|
|
98
|
+
* reserve into the host's container floor value (so the island host can never strip or burn
|
|
99
|
+
* a leased machine's bankroll).
|
|
100
|
+
*/
|
|
101
|
+
function mountContainerSlotItem(params) {
|
|
102
|
+
const { parent, child, slotKey, mountMode, callerDid, timestamp } = params;
|
|
103
|
+
if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("timestamp must be a non-negative integer");
|
|
104
|
+
const registry = {
|
|
105
|
+
...params.assetRegistry ?? {},
|
|
106
|
+
[parent.did]: parent,
|
|
107
|
+
[child.did]: child
|
|
108
|
+
};
|
|
109
|
+
assertNoContainerCycle(parent.did, child.did, registry, params.maxDepth ?? 8);
|
|
110
|
+
if (parent.mountedInParentDid || parent.independentRedemptionFrozen) throw new Error(`PARENT_ALREADY_MOUNTED: container ${parent.did} is currently mounted in ${parent.mountedInParentDid ?? "another container"} and cannot mount child items until unmounted`);
|
|
111
|
+
if (child.mountedInParentDid || child.independentRedemptionFrozen) throw new Error(`CHILD_ALREADY_MOUNTED: asset ${child.did} is already mounted in ${child.mountedInParentDid}`);
|
|
112
|
+
for (const childSlot of Object.values(child.mountedSlots)) if (childSlot.mountMode === "LEASED") throw new Error(`CHILD_HAS_LEASED_SLOTS: child container ${child.did} holds leased item ${childSlot.childDid} and cannot be mounted into ${parent.did}`);
|
|
113
|
+
const slotDef = parent.slotDefinitions.find((s) => s.slotKey === slotKey);
|
|
114
|
+
if (!slotDef) throw new Error(`SLOT_NOT_FOUND: slot ${slotKey} is not defined on container ${parent.did}`);
|
|
115
|
+
if (Object.hasOwn(parent.mountedSlots, slotKey)) throw new Error(`SLOT_OCCUPIED: slot ${slotKey} on container ${parent.did} is already occupied`);
|
|
116
|
+
if (!slotDef.allowedCategories.includes(child.category)) throw new Error(`SLOT_CATEGORY_MISMATCH: child category ${child.category} is not allowed in slot ${slotKey} (expected ${slotDef.allowedCategories.join(", ")})`);
|
|
117
|
+
if (!(slotDef.allowedMountModes ?? ["OWNED", "LEASED"]).includes(mountMode)) throw new Error(`SLOT_MOUNT_MODE_FORBIDDEN: mountMode ${mountMode} is not permitted on slot ${slotKey}`);
|
|
118
|
+
if (mountMode === "OWNED") {
|
|
119
|
+
if (parent.ownerDid !== callerDid || child.ownerDid !== callerDid) throw new Error("OWNERSHIP_MISMATCH: OWNED mount requires callerDid to own both parent container and child item");
|
|
120
|
+
} else {
|
|
121
|
+
const terms = params.leaseTerms;
|
|
122
|
+
if (!terms) throw new Error("LEASE_TERMS_REQUIRED: LEASED mount requires leaseTerms");
|
|
123
|
+
if (terms.lesseeHostDid !== parent.ownerDid || terms.lessorDid !== child.ownerDid) throw new Error("LEASE_PARTY_MISMATCH: lesseeHostDid must own parent container and lessorDid must own child NFT");
|
|
124
|
+
if (callerDid !== terms.lesseeHostDid && callerDid !== terms.lessorDid) throw new Error("LEASE_UNAUTHORIZED: callerDid must be either lessorDid or lesseeHostDid");
|
|
125
|
+
if (!Number.isSafeInteger(terms.hostBps) || terms.hostBps < 0 || terms.hostBps > 1e4) throw new Error("Invalid leaseTerms.hostBps: must be an integer between 0 and 10000");
|
|
126
|
+
if (!Number.isSafeInteger(terms.leaseExpiresAt) || terms.leaseExpiresAt <= timestamp) throw new Error("Invalid leaseTerms.leaseExpiresAt: must be greater than mount timestamp");
|
|
127
|
+
}
|
|
128
|
+
const assignment = {
|
|
129
|
+
slotKey,
|
|
130
|
+
childDid: child.did,
|
|
131
|
+
childCategory: child.category,
|
|
132
|
+
mountMode,
|
|
133
|
+
childFloorReserveValue: child.aggregatedFloorReserveValue,
|
|
134
|
+
mountedAt: timestamp,
|
|
135
|
+
leaseTerms: mountMode === "LEASED" ? { ...params.leaseTerms } : void 0
|
|
136
|
+
};
|
|
137
|
+
const nextParentAggregatedFloor = mountMode === "OWNED" ? parent.aggregatedFloorReserveValue + child.aggregatedFloorReserveValue : parent.aggregatedFloorReserveValue;
|
|
138
|
+
return {
|
|
139
|
+
parent: {
|
|
140
|
+
...parent,
|
|
141
|
+
aggregatedFloorReserveValue: nextParentAggregatedFloor,
|
|
142
|
+
mountedSlots: {
|
|
143
|
+
...parent.mountedSlots,
|
|
144
|
+
[slotKey]: assignment
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
child: {
|
|
148
|
+
...child,
|
|
149
|
+
mountedInParentDid: parent.did,
|
|
150
|
+
independentRedemptionFrozen: true
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Unmounts a child NFT from a parent container slot and restores its independent redemption status.
|
|
156
|
+
*
|
|
157
|
+
* - Enforces top-down unmounting: `parent` itself must be unmounted (`!parent.mountedInParentDid && !parent.independentRedemptionFrozen`).
|
|
158
|
+
* - For `OWNED` mounts: only `parent.ownerDid` can unmount, and `childFloorReserveValue` is subtracted
|
|
159
|
+
* from `parent.aggregatedFloorReserveValue`.
|
|
160
|
+
* - For `LEASED` mounts: `lesseeHostDid` can unmount at any time; `lessorDid` can unmount once
|
|
161
|
+
* `timestamp >= leaseExpiresAt` (or anytime if `allowEarlyLessorRecall` is true).
|
|
162
|
+
*/
|
|
163
|
+
function unmountContainerSlotItem(params) {
|
|
164
|
+
const { parent, child, slotKey, callerDid, timestamp } = params;
|
|
165
|
+
if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("timestamp must be a non-negative integer");
|
|
166
|
+
if (parent.mountedInParentDid || parent.independentRedemptionFrozen) throw new Error(`PARENT_ALREADY_MOUNTED: container ${parent.did} is currently mounted in ${parent.mountedInParentDid ?? "another container"} and cannot unmount child items until unmounted first`);
|
|
167
|
+
const assignment = Object.hasOwn(parent.mountedSlots, slotKey) ? parent.mountedSlots[slotKey] : void 0;
|
|
168
|
+
if (!assignment || assignment.childDid !== child.did) throw new Error(`SLOT_CHILD_MISMATCH: child ${child.did} is not mounted in slot ${slotKey} of ${parent.did}`);
|
|
169
|
+
if (assignment.mountMode === "OWNED") {
|
|
170
|
+
if (callerDid !== parent.ownerDid) throw new Error("UNMOUNT_UNAUTHORIZED: only parent container owner can unmount OWNED slot item");
|
|
171
|
+
} else {
|
|
172
|
+
const terms = assignment.leaseTerms;
|
|
173
|
+
const isLessee = callerDid === terms.lesseeHostDid;
|
|
174
|
+
const isLessor = callerDid === terms.lessorDid;
|
|
175
|
+
if (!isLessee && !isLessor) throw new Error("UNMOUNT_UNAUTHORIZED: only lessor or lessee host can unmount LEASED slot item");
|
|
176
|
+
if (isLessor && !isLessee && !terms.allowEarlyLessorRecall && !(timestamp >= terms.leaseExpiresAt)) throw new Error(`LEASE_NOT_EXPIRED: lessor ${callerDid} cannot recall leased machine before ${terms.leaseExpiresAt}`);
|
|
177
|
+
}
|
|
178
|
+
const nextMountedSlots = { ...parent.mountedSlots };
|
|
179
|
+
delete nextMountedSlots[slotKey];
|
|
180
|
+
const nextParentAggregatedFloor = assignment.mountMode === "OWNED" ? parent.aggregatedFloorReserveValue - assignment.childFloorReserveValue : parent.aggregatedFloorReserveValue;
|
|
181
|
+
return {
|
|
182
|
+
parent: {
|
|
183
|
+
...parent,
|
|
184
|
+
aggregatedFloorReserveValue: nextParentAggregatedFloor,
|
|
185
|
+
mountedSlots: nextMountedSlots
|
|
186
|
+
},
|
|
187
|
+
child: {
|
|
188
|
+
...child,
|
|
189
|
+
mountedInParentDid: null,
|
|
190
|
+
independentRedemptionFrozen: false
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Verifies whether an asset node is eligible for floor-burn redemption or transfer:
|
|
196
|
+
* - Mounted children (`independentRedemptionFrozen === true`) cannot be independently burned or transferred.
|
|
197
|
+
* - A parent container holding a `LEASED` child cannot be burned or transferred until all leased
|
|
198
|
+
* machines are unmounted and returned to their lessors.
|
|
199
|
+
*/
|
|
200
|
+
function assertAssetRedeemableOrTransferable(asset, operation) {
|
|
201
|
+
if (asset.independentRedemptionFrozen || asset.mountedInParentDid) throw new Error(`ASSET_MOUNTED_FROZEN: asset ${asset.did} is currently mounted in ${asset.mountedInParentDid} and cannot perform ${operation}`);
|
|
202
|
+
for (const assignment of Object.values(asset.mountedSlots)) if (assignment.mountMode === "LEASED") throw new Error(`CONTAINER_HAS_LEASED_SLOTS: container ${asset.did} has leased item ${assignment.childDid} in slot ${assignment.slotKey} and cannot perform ${operation}`);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Executes a deterministic N-to-1 consumable alchemy synthesis (`synthesizeContainerRecipe`):
|
|
206
|
+
* - Verifies all ingredient assets belong to `callerDid`, are unmounted, and have no mounted slots.
|
|
207
|
+
* - Matches ingredient categories against `recipe.requirements` (rejecting duplicate category rules).
|
|
208
|
+
* - Conserves underlying floor reserve value:
|
|
209
|
+
* `netOutputFloorReserve + protocolFeeReserve === sum(input.aggregatedFloorReserveValue) + extraCatalystReserveAdded`.
|
|
210
|
+
*/
|
|
211
|
+
function synthesizeContainerRecipe(params) {
|
|
212
|
+
const { recipe, ingredients, outputDid, callerDid } = params;
|
|
213
|
+
if (!Array.isArray(ingredients) || ingredients.length === 0) throw new Error("Synthesis requires at least one ingredient asset");
|
|
214
|
+
if (!Array.isArray(recipe.requirements) || recipe.requirements.length === 0) throw new Error("Synthesis recipe requires at least one requirement");
|
|
215
|
+
const extraReserve = params.extraCatalystReserveAdded !== void 0 ? parseNonNegativeBigInt(params.extraCatalystReserveAdded, "extraCatalystReserveAdded") : 0n;
|
|
216
|
+
const requiredExtra = recipe.extraCatalystFeeReserve !== void 0 ? parseNonNegativeBigInt(recipe.extraCatalystFeeReserve, "recipe.extraCatalystFeeReserve") : 0n;
|
|
217
|
+
if (extraReserve < requiredExtra) throw new Error(`INSUFFICIENT_CATALYST_RESERVE: recipe requires at least ${requiredExtra.toString()} extra reserve`);
|
|
218
|
+
const seenDids = /* @__PURE__ */ new Set();
|
|
219
|
+
const categoryCounts = Object.create(null);
|
|
220
|
+
let totalInputReserve = 0n;
|
|
221
|
+
for (const item of ingredients) {
|
|
222
|
+
if (seenDids.has(item.did)) throw new Error(`DUPLICATE_INGREDIENT: asset ${item.did} supplied multiple times`);
|
|
223
|
+
seenDids.add(item.did);
|
|
224
|
+
if (item.ownerDid !== callerDid) throw new Error(`INGREDIENT_OWNER_MISMATCH: caller ${callerDid} does not own ingredient ${item.did}`);
|
|
225
|
+
assertAssetRedeemableOrTransferable(item, "REDEEM_BURN");
|
|
226
|
+
if (Object.keys(item.mountedSlots).length > 0) throw new Error(`INGREDIENT_HAS_MOUNTED_SLOTS: ingredient ${item.did} has mounted items and must be emptied before synthesis`);
|
|
227
|
+
categoryCounts[item.category] = (categoryCounts[item.category] ?? 0) + 1;
|
|
228
|
+
totalInputReserve += item.aggregatedFloorReserveValue;
|
|
229
|
+
}
|
|
230
|
+
if (outputDid && seenDids.has(outputDid.trim())) throw new Error(`OUTPUT_DID_COLLISION: outputDid ${outputDid} collides with an input ingredient DID`);
|
|
231
|
+
let totalRequiredCount = 0;
|
|
232
|
+
const seenCategories = /* @__PURE__ */ new Set();
|
|
233
|
+
for (const req of recipe.requirements) {
|
|
234
|
+
const category = req.category?.trim();
|
|
235
|
+
if (!category) throw new Error("Requirement category is required");
|
|
236
|
+
if (seenCategories.has(category)) throw new Error(`DUPLICATE_RECIPE_CATEGORY: duplicate requirement category ${category}`);
|
|
237
|
+
seenCategories.add(category);
|
|
238
|
+
if (!Number.isSafeInteger(req.count) || req.count <= 0) throw new Error(`Invalid requirement count for category ${category}`);
|
|
239
|
+
totalRequiredCount += req.count;
|
|
240
|
+
if ((categoryCounts[category] ?? 0) !== req.count) throw new Error(`RECIPE_REQUIREMENT_MISMATCH: expected ${req.count} of ${category}, got ${categoryCounts[category] ?? 0}`);
|
|
241
|
+
}
|
|
242
|
+
if (ingredients.length !== totalRequiredCount) throw new Error("RECIPE_EXTRA_INGREDIENTS: unexpected ingredient categories supplied");
|
|
243
|
+
const protocolFeeBps = recipe.protocolFeeBps ?? 0;
|
|
244
|
+
if (!Number.isSafeInteger(protocolFeeBps) || protocolFeeBps < 0 || protocolFeeBps > 5e3) throw new Error("Invalid recipe.protocolFeeBps: must be an integer between 0 and 5000");
|
|
245
|
+
const combinedReserve = totalInputReserve + extraReserve;
|
|
246
|
+
const protocolFeeReserve = combinedReserve * BigInt(protocolFeeBps) / 10000n;
|
|
247
|
+
const netOutputFloorReserve = combinedReserve - protocolFeeReserve;
|
|
248
|
+
return {
|
|
249
|
+
outputAsset: createComposableAssetNode({
|
|
250
|
+
did: outputDid,
|
|
251
|
+
ownerDid: callerDid,
|
|
252
|
+
category: recipe.outputCategory,
|
|
253
|
+
baseFloorReserveValue: netOutputFloorReserve,
|
|
254
|
+
slotDefinitions: params.outputSlotDefinitions
|
|
255
|
+
}),
|
|
256
|
+
burnedInputDids: ingredients.map((i) => i.did),
|
|
257
|
+
totalInputReserveConsumed: totalInputReserve,
|
|
258
|
+
protocolFeeReserve,
|
|
259
|
+
netOutputFloorReserve
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
//#endregion
|
|
264
|
+
export { assertAssetRedeemableOrTransferable, assertNoContainerCycle, createComposableAssetNode, mountContainerSlotItem, synthesizeContainerRecipe, unmountContainerSlotItem };
|