@ocap/util 1.30.25 → 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/esm/url.mjs +17 -8
- 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/lib/url.cjs +17 -8
- package/package.json +2 -2
package/esm/arcade.mjs
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import { sha256 } from "./node_modules/@noble/hashes/sha2.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/arcade.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
|
+
if (typeof value === "number") {
|
|
15
|
+
if (!Number.isSafeInteger(value)) throw new Error(`Invalid ${label}: must be a safe integer`);
|
|
16
|
+
if (value < 0) throw new Error(`Invalid ${label}: must be non-negative`);
|
|
17
|
+
return BigInt(value);
|
|
18
|
+
}
|
|
19
|
+
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
|
+
const parsed = BigInt(trimmed);
|
|
23
|
+
if (parsed < 0n) throw new Error(`Invalid ${label}: must be non-negative`);
|
|
24
|
+
return parsed;
|
|
25
|
+
}
|
|
26
|
+
if (typeof value === "bigint") {
|
|
27
|
+
if (value < 0n) throw new Error(`Invalid ${label}: must be non-negative`);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
throw new Error(`Invalid ${label}: must be an integer`);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Verifies a single step of an inverted SHA-256 commit-reveal hash chain:
|
|
34
|
+
* `sha256Hex(serverSeedPreimage) === expectedCommitHash`.
|
|
35
|
+
*/
|
|
36
|
+
function verifyHashChainStep(serverSeedPreimage, expectedCommitHash) {
|
|
37
|
+
if (!serverSeedPreimage || typeof serverSeedPreimage !== "string") return false;
|
|
38
|
+
if (!expectedCommitHash || typeof expectedCommitHash !== "string") return false;
|
|
39
|
+
return sha256Hex(serverSeedPreimage) === expectedCommitHash.trim().toLowerCase();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Generates an inverted SHA-256 hash chain of length `steps` from a terminal seed.
|
|
43
|
+
* Element `0` is the terminal secret (`seed_N`), and element `steps - 1` is the initial
|
|
44
|
+
* public commitment (`commit_0 = H^(steps-1)(seed_N)`).
|
|
45
|
+
*/
|
|
46
|
+
function generateHashChain(terminalSeed, steps) {
|
|
47
|
+
if (!terminalSeed || typeof terminalSeed !== "string") throw new Error("terminalSeed must be a non-empty string");
|
|
48
|
+
if (!Number.isInteger(steps) || steps < 1 || steps > 1e5) throw new Error("steps must be an integer between 1 and 100000");
|
|
49
|
+
const chain = [terminalSeed];
|
|
50
|
+
let current = terminalSeed;
|
|
51
|
+
for (let i = 1; i < steps; i++) {
|
|
52
|
+
current = sha256Hex(current);
|
|
53
|
+
chain.push(current);
|
|
54
|
+
}
|
|
55
|
+
return chain;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Receipt-then-Reveal Provably Fair Randomness derivation:
|
|
59
|
+
* 1. Verifies `sha256(serverSeedPreimage) === expectedCommitHash`
|
|
60
|
+
* 2. Combines `(serverSeedPreimage, receiptId, clientSeed, playNonce)` via domain-separated SHA-256
|
|
61
|
+
* 3. Extracts an unbiased 256-bit integer modulo `modulus`
|
|
62
|
+
*/
|
|
63
|
+
function deriveProvablyFairRoll(input) {
|
|
64
|
+
if (!verifyHashChainStep(input.serverSeedPreimage, input.expectedCommitHash)) throw new Error("COMMIT_REVEAL_MISMATCH: serverSeedPreimage does not hash to expectedCommitHash");
|
|
65
|
+
if (!input.receiptId || !input.receiptId.trim()) throw new Error("receiptId is required for Receipt-then-Reveal binding");
|
|
66
|
+
const nonce = parseNonNegativeBigInt(input.playNonce, "playNonce");
|
|
67
|
+
const modulus = input.modulus !== void 0 ? parseNonNegativeBigInt(input.modulus, "modulus") : 10000n;
|
|
68
|
+
if (modulus <= 0n || modulus > 2n ** 64n) throw new Error("modulus must be between 1 and 2^64");
|
|
69
|
+
const entropyHex = sha256Hex(JSON.stringify({
|
|
70
|
+
domain: "arcblock.vledger.arcade.roll.v1",
|
|
71
|
+
serverSeedPreimage: input.serverSeedPreimage,
|
|
72
|
+
receiptId: input.receiptId.trim(),
|
|
73
|
+
clientSeed: (input.clientSeed ?? "").trim(),
|
|
74
|
+
playNonce: nonce.toString(10)
|
|
75
|
+
}));
|
|
76
|
+
const entropyBigInt = BigInt(`0x${entropyHex}`);
|
|
77
|
+
return {
|
|
78
|
+
entropyHex,
|
|
79
|
+
nextCommitHash: input.serverSeedPreimage,
|
|
80
|
+
roll: entropyBigInt % modulus,
|
|
81
|
+
modulus
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Resolves a weighted loot table roll with an optional deterministic pity counter.
|
|
86
|
+
*/
|
|
87
|
+
function resolveWeightedLootTable(tiers, entropyValue, currentPityCount = 0, pityConfig) {
|
|
88
|
+
if (!Array.isArray(tiers) || tiers.length === 0) throw new Error("Loot table must contain at least one tier");
|
|
89
|
+
if (!Number.isInteger(currentPityCount) || currentPityCount < 0) throw new Error("currentPityCount must be a non-negative integer");
|
|
90
|
+
let totalWeight = 0n;
|
|
91
|
+
for (const tier of tiers) {
|
|
92
|
+
if (!tier.tierId || !Number.isInteger(tier.weight) || tier.weight <= 0) throw new Error(`Invalid loot tier weight for ${tier.tierId || "<unnamed>"}`);
|
|
93
|
+
if (!Number.isInteger(tier.payoutMultiplierBps) || tier.payoutMultiplierBps < 0) throw new Error(`Invalid payoutMultiplierBps for ${tier.tierId}`);
|
|
94
|
+
totalWeight += BigInt(tier.weight);
|
|
95
|
+
}
|
|
96
|
+
let guaranteedTier;
|
|
97
|
+
if (pityConfig) {
|
|
98
|
+
if (!Number.isInteger(pityConfig.pityThreshold) || pityConfig.pityThreshold <= 0) throw new Error("pityConfig.pityThreshold must be a positive integer");
|
|
99
|
+
guaranteedTier = tiers.find((t) => t.tierId === pityConfig.guaranteedTierId);
|
|
100
|
+
if (!guaranteedTier) throw new Error(`Guaranteed pity tier ${pityConfig.guaranteedTierId} not found in loot table`);
|
|
101
|
+
}
|
|
102
|
+
const target = parseNonNegativeBigInt(entropyValue, "entropyValue") % totalWeight;
|
|
103
|
+
let cumulative = 0n;
|
|
104
|
+
let chosen = tiers[tiers.length - 1];
|
|
105
|
+
for (const tier of tiers) {
|
|
106
|
+
cumulative += BigInt(tier.weight);
|
|
107
|
+
if (target < cumulative) {
|
|
108
|
+
chosen = tier;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (pityConfig && guaranteedTier && currentPityCount + 1 >= pityConfig.pityThreshold) {
|
|
113
|
+
if (chosen.payoutMultiplierBps > guaranteedTier.payoutMultiplierBps) return {
|
|
114
|
+
selectedTier: chosen,
|
|
115
|
+
pityTriggered: false,
|
|
116
|
+
nextPityCount: 0
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
selectedTier: guaranteedTier,
|
|
120
|
+
pityTriggered: true,
|
|
121
|
+
nextPityCount: 0
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
const isHighTier = pityConfig ? pityConfig.highTierIds.includes(chosen.tierId) : false;
|
|
125
|
+
return {
|
|
126
|
+
selectedTier: chosen,
|
|
127
|
+
pityTriggered: false,
|
|
128
|
+
nextPityCount: pityConfig ? isHighTier ? 0 : currentPityCount + 1 : 0
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Verifies that an arcade/board-game machine's available reserve can cover `maxPossiblePayout`
|
|
133
|
+
* without violating `maxSinglePayoutBps` of its available bankroll.
|
|
134
|
+
*/
|
|
135
|
+
function assertMachineBankrollSolvency(bankroll, maxPossiblePayout) {
|
|
136
|
+
const payout = parseNonNegativeBigInt(maxPossiblePayout, "maxPossiblePayout");
|
|
137
|
+
const totalReserve = parseNonNegativeBigInt(bankroll.totalReserve, "totalReserve");
|
|
138
|
+
const lockedPendingPayouts = parseNonNegativeBigInt(bankroll.lockedPendingPayouts, "lockedPendingPayouts");
|
|
139
|
+
if (totalReserve < lockedPendingPayouts) throw new Error("BANKROLL_INSOLVENT: lockedPendingPayouts exceeds totalReserve");
|
|
140
|
+
if (!Number.isInteger(bankroll.maxSinglePayoutBps) || bankroll.maxSinglePayoutBps <= 0 || bankroll.maxSinglePayoutBps > 1e4) throw new Error("Invalid maxSinglePayoutBps: must be in 1..10000");
|
|
141
|
+
const availableReserve = totalReserve - lockedPendingPayouts;
|
|
142
|
+
const maxAllowedSinglePayout = availableReserve * BigInt(bankroll.maxSinglePayoutBps) / 10000n;
|
|
143
|
+
if (payout > availableReserve || payout > maxAllowedSinglePayout) throw new Error(`MAX_EXPOSURE_EXCEEDED: maxPossiblePayout ${payout.toString()} exceeds maxAllowedSinglePayout ${maxAllowedSinglePayout.toString()}`);
|
|
144
|
+
return {
|
|
145
|
+
availableReserve,
|
|
146
|
+
maxAllowedSinglePayout
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Atomically settles a single play on a mounted Arcade / Board-Game Machine NFT:
|
|
151
|
+
* - Splits `betAmount` into `(reserveCut, creatorCut, ownerCut, hostCut)` with exact conservation
|
|
152
|
+
* (any integer rounding remainder is retained in `reserveCut` so prize solvency never leaks).
|
|
153
|
+
* - Verifies `currentReserve + reserveCut >= payoutAmount`.
|
|
154
|
+
* - Updates public verifiable RTP / PnL metrics (`playCount`, `totalBet`, `totalPayout`, `realizedRtpBps`).
|
|
155
|
+
*/
|
|
156
|
+
function settleArcadeMachinePlay(params) {
|
|
157
|
+
const bet = parseNonNegativeBigInt(params.betAmount, "betAmount");
|
|
158
|
+
if (bet <= 0n) throw new Error("betAmount must be positive");
|
|
159
|
+
const payout = parseNonNegativeBigInt(params.payoutAmount, "payoutAmount");
|
|
160
|
+
const maxPossiblePayout = params.maxPossiblePayout !== void 0 ? parseNonNegativeBigInt(params.maxPossiblePayout, "maxPossiblePayout") : payout;
|
|
161
|
+
if (payout > maxPossiblePayout) throw new Error("payoutAmount cannot exceed maxPossiblePayout");
|
|
162
|
+
const currentReserve = parseNonNegativeBigInt(params.currentReserve, "currentReserve");
|
|
163
|
+
const { reserveBps, creatorBps, ownerBps, hostBps } = params.splitConfig;
|
|
164
|
+
if (!Number.isInteger(reserveBps) || reserveBps <= 0 || reserveBps > 1e4) throw new Error("Invalid reserveBps: must be an integer between 1 and 10000");
|
|
165
|
+
for (const [name, val] of [
|
|
166
|
+
["creatorBps", creatorBps],
|
|
167
|
+
["ownerBps", ownerBps],
|
|
168
|
+
["hostBps", hostBps]
|
|
169
|
+
]) if (!Number.isInteger(val) || val < 0 || val > 1e4) throw new Error(`Invalid ${name}: must be an integer between 0 and 10000`);
|
|
170
|
+
if (reserveBps + creatorBps + ownerBps + hostBps !== 1e4) throw new Error("ArcadeFourWaySplitConfig bps must sum to 10000");
|
|
171
|
+
const creatorCut = bet * BigInt(creatorBps) / 10000n;
|
|
172
|
+
const ownerCut = bet * BigInt(ownerBps) / 10000n;
|
|
173
|
+
const hostCut = bet * BigInt(hostBps) / 10000n;
|
|
174
|
+
const reserveCut = bet - creatorCut - ownerCut - hostCut;
|
|
175
|
+
const poolAfterInflow = currentReserve + reserveCut;
|
|
176
|
+
const requiredCover = maxPossiblePayout > payout ? maxPossiblePayout : payout;
|
|
177
|
+
if (requiredCover > poolAfterInflow) throw new Error(`INSUFFICIENT_MACHINE_RESERVE: required cover ${requiredCover.toString()} exceeds reserve ${poolAfterInflow.toString()}`);
|
|
178
|
+
const nextReserveBalance = poolAfterInflow - payout;
|
|
179
|
+
const prev = params.previousMetrics ?? {
|
|
180
|
+
playCount: 0n,
|
|
181
|
+
totalBet: 0n,
|
|
182
|
+
totalPayout: 0n,
|
|
183
|
+
realizedRtpBps: 0
|
|
184
|
+
};
|
|
185
|
+
const nextPlayCount = prev.playCount + 1n;
|
|
186
|
+
const nextTotalBet = prev.totalBet + bet;
|
|
187
|
+
const nextTotalPayout = prev.totalPayout + payout;
|
|
188
|
+
return {
|
|
189
|
+
betAmount: bet,
|
|
190
|
+
payoutAmount: payout,
|
|
191
|
+
reserveCut,
|
|
192
|
+
creatorCut,
|
|
193
|
+
ownerCut,
|
|
194
|
+
hostCut,
|
|
195
|
+
nextReserveBalance,
|
|
196
|
+
metrics: {
|
|
197
|
+
playCount: nextPlayCount,
|
|
198
|
+
totalBet: nextTotalBet,
|
|
199
|
+
totalPayout: nextTotalPayout,
|
|
200
|
+
realizedRtpBps: nextTotalBet > 0n ? Number(nextTotalPayout * 10000n / nextTotalBet) : 0
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Resolves a multi-level nested revenue-sharing DAG (e.g. an Island NFT co-owned by a Guild NFT
|
|
206
|
+
* and multiple partners, or a Game Machine NFT co-invested by a Syndicate NFT and angel investors).
|
|
207
|
+
*
|
|
208
|
+
* Enforces:
|
|
209
|
+
* - Acyclic graph invariant (`CYCLE_DETECTED` if `A -> B -> A` occurs)
|
|
210
|
+
* - Bounded recursion depth (`MAX_DEPTH_EXCEEDED` if nesting exceeds `maxDepth`)
|
|
211
|
+
* - Exact integer conservation at every internal node (rounding remainder is assigned to the first recipient edge)
|
|
212
|
+
* so that `sum(leafAllocations) === totalAmount` with zero dust loss.
|
|
213
|
+
*/
|
|
214
|
+
function resolveHierarchicalSplitDag(params) {
|
|
215
|
+
const totalAmount = parseNonNegativeBigInt(params.totalAmount, "totalAmount");
|
|
216
|
+
const maxDepth = params.maxDepth ?? 8;
|
|
217
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > 32) throw new Error("maxDepth must be an integer between 1 and 32");
|
|
218
|
+
if (!params.rootNodeDid || !params.rootNodeDid.trim()) throw new Error("rootNodeDid is required");
|
|
219
|
+
const rootId = params.rootNodeDid.trim();
|
|
220
|
+
const normalizedNodes = /* @__PURE__ */ new Map();
|
|
221
|
+
for (const [rawNodeDid, edges] of Object.entries(params.nodes)) {
|
|
222
|
+
const nodeDid = rawNodeDid.trim();
|
|
223
|
+
if (!nodeDid) throw new Error("Split node DID cannot be empty");
|
|
224
|
+
if (normalizedNodes.has(nodeDid)) throw new Error(`Duplicate split node key after trimming: ${nodeDid}`);
|
|
225
|
+
if (!Array.isArray(edges) || edges.length === 0) throw new Error(`Split node ${nodeDid} must have at least one recipient edge`);
|
|
226
|
+
let sumBps = 0;
|
|
227
|
+
const seenRecipients = /* @__PURE__ */ new Set();
|
|
228
|
+
const normalizedEdges = [];
|
|
229
|
+
for (const edge of edges) {
|
|
230
|
+
if (!edge.recipientDid || !edge.recipientDid.trim()) throw new Error(`Split node ${nodeDid} contains an empty recipientDid`);
|
|
231
|
+
const recipientDid = edge.recipientDid.trim();
|
|
232
|
+
if (seenRecipients.has(recipientDid)) throw new Error(`Duplicate recipientDid ${recipientDid} in split node ${nodeDid}`);
|
|
233
|
+
seenRecipients.add(recipientDid);
|
|
234
|
+
if (!Number.isInteger(edge.shareBps) || edge.shareBps <= 0 || edge.shareBps > 1e4) throw new Error(`Invalid shareBps for ${recipientDid} in node ${nodeDid}`);
|
|
235
|
+
sumBps += edge.shareBps;
|
|
236
|
+
normalizedEdges.push({
|
|
237
|
+
recipientDid,
|
|
238
|
+
shareBps: edge.shareBps
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
if (sumBps !== 1e4) throw new Error(`Split node ${nodeDid} shareBps must sum to 10000 (got ${sumBps})`);
|
|
242
|
+
normalizedNodes.set(nodeDid, normalizedEdges);
|
|
243
|
+
}
|
|
244
|
+
const visitState = /* @__PURE__ */ new Map();
|
|
245
|
+
const maxRemainingHeight = /* @__PURE__ */ new Map();
|
|
246
|
+
const postOrder = [];
|
|
247
|
+
function analyzeGraph(nodeDid) {
|
|
248
|
+
const edges = normalizedNodes.get(nodeDid);
|
|
249
|
+
if (!edges) return 0;
|
|
250
|
+
const state = visitState.get(nodeDid);
|
|
251
|
+
if (state === "visiting") throw new Error(`CYCLE_DETECTED: circular revenue share reference involving ${nodeDid}`);
|
|
252
|
+
if (state === "visited") return maxRemainingHeight.get(nodeDid);
|
|
253
|
+
visitState.set(nodeDid, "visiting");
|
|
254
|
+
let maxChildHeight = 0;
|
|
255
|
+
for (const edge of edges) {
|
|
256
|
+
const childHeight = analyzeGraph(edge.recipientDid);
|
|
257
|
+
if (childHeight > maxChildHeight) maxChildHeight = childHeight;
|
|
258
|
+
}
|
|
259
|
+
const height = 1 + maxChildHeight;
|
|
260
|
+
visitState.set(nodeDid, "visited");
|
|
261
|
+
maxRemainingHeight.set(nodeDid, height);
|
|
262
|
+
postOrder.push(nodeDid);
|
|
263
|
+
return height;
|
|
264
|
+
}
|
|
265
|
+
const totalGraphDepth = analyzeGraph(rootId);
|
|
266
|
+
if (totalGraphDepth > maxDepth) throw new Error(`MAX_DEPTH_EXCEEDED: revenue share nesting depth ${totalGraphDepth} exceeded maxDepth ${maxDepth}`);
|
|
267
|
+
const topoOrder = postOrder.reverse();
|
|
268
|
+
const nodeBalances = /* @__PURE__ */ new Map();
|
|
269
|
+
nodeBalances.set(rootId, totalAmount);
|
|
270
|
+
const leafBalances = Object.create(null);
|
|
271
|
+
if (!normalizedNodes.has(rootId)) {
|
|
272
|
+
leafBalances[rootId] = totalAmount;
|
|
273
|
+
return { ...leafBalances };
|
|
274
|
+
}
|
|
275
|
+
for (const nodeDid of topoOrder) {
|
|
276
|
+
const amount = nodeBalances.get(nodeDid) ?? 0n;
|
|
277
|
+
if (amount <= 0n) continue;
|
|
278
|
+
const edges = normalizedNodes.get(nodeDid);
|
|
279
|
+
let allocated = 0n;
|
|
280
|
+
const childAmounts = [];
|
|
281
|
+
for (let i = 0; i < edges.length; i++) {
|
|
282
|
+
const cut = amount * BigInt(edges[i].shareBps) / 10000n;
|
|
283
|
+
childAmounts.push(cut);
|
|
284
|
+
allocated += cut;
|
|
285
|
+
}
|
|
286
|
+
const remainder = amount - allocated;
|
|
287
|
+
if (remainder > 0n) childAmounts[0] += remainder;
|
|
288
|
+
for (let i = 0; i < edges.length; i++) {
|
|
289
|
+
const childCut = childAmounts[i];
|
|
290
|
+
if (childCut <= 0n) continue;
|
|
291
|
+
const targetDid = edges[i].recipientDid;
|
|
292
|
+
if (normalizedNodes.has(targetDid)) nodeBalances.set(targetDid, (nodeBalances.get(targetDid) ?? 0n) + childCut);
|
|
293
|
+
else leafBalances[targetDid] = (leafBalances[targetDid] ?? 0n) + childCut;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { ...leafBalances };
|
|
297
|
+
}
|
|
298
|
+
const ACC_PRECISION = 1000000000000000000n;
|
|
299
|
+
/**
|
|
300
|
+
* O(1) Cumulative Dividend-Per-Share Pool (`accRewardPerShare`) for fractional/multi-investor
|
|
301
|
+
* Machine NFTs, Card Game Tables, and Co-Owned Islands.
|
|
302
|
+
*
|
|
303
|
+
* Supports:
|
|
304
|
+
* - O(1) revenue inflows (`distributeRevenue`) regardless of shareholder count
|
|
305
|
+
* - Ex-dividend checkpoint settlement on share transfers (`transferShares`) so sellers retain all
|
|
306
|
+
* dividends accrued prior to sale and buyers earn future cashflows from the transfer block onward
|
|
307
|
+
* - Exact unscaled fractional remainder preservation (`accruedScaled`) preventing Sybil share-splitting
|
|
308
|
+
* debt truncation attacks
|
|
309
|
+
* - On-chain DCF / NPV valuation (`estimateNpv`) combining trailing revenue cashflows and hard reserve floor
|
|
310
|
+
*/
|
|
311
|
+
var RevenueSharePool = class {
|
|
312
|
+
constructor(assetDid, initialHolders) {
|
|
313
|
+
this.totalShares = 0n;
|
|
314
|
+
this.accRewardPerShare = 0n;
|
|
315
|
+
this.carryRemainder = 0n;
|
|
316
|
+
this.totalRevenueDistributed = 0n;
|
|
317
|
+
this.positions = /* @__PURE__ */ new Map();
|
|
318
|
+
if (!assetDid || !assetDid.trim()) throw new Error("assetDid is required");
|
|
319
|
+
this.assetDid = assetDid.trim();
|
|
320
|
+
if (initialHolders) for (const item of initialHolders) this.mintShares(item.holderDid, item.shares);
|
|
321
|
+
}
|
|
322
|
+
getTotalShares() {
|
|
323
|
+
return this.totalShares;
|
|
324
|
+
}
|
|
325
|
+
getAccRewardPerShare() {
|
|
326
|
+
return this.accRewardPerShare;
|
|
327
|
+
}
|
|
328
|
+
getTotalRevenueDistributed() {
|
|
329
|
+
return this.totalRevenueDistributed;
|
|
330
|
+
}
|
|
331
|
+
toPublicPosition(pos) {
|
|
332
|
+
return {
|
|
333
|
+
holderDid: pos.holderDid,
|
|
334
|
+
shares: pos.shares,
|
|
335
|
+
rewardDebt: pos.rewardDebt,
|
|
336
|
+
accruedUnclaimed: pos.accruedUnclaimed,
|
|
337
|
+
totalClaimed: pos.totalClaimed
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
settlePosition(pos) {
|
|
341
|
+
const deltaAcc = this.accRewardPerShare - pos.lastAccRewardPerShare;
|
|
342
|
+
if (pos.shares > 0n && deltaAcc > 0n) pos.accruedScaled += pos.shares * deltaAcc;
|
|
343
|
+
pos.lastAccRewardPerShare = this.accRewardPerShare;
|
|
344
|
+
const wholeTokens = pos.accruedScaled / ACC_PRECISION;
|
|
345
|
+
if (wholeTokens > 0n) {
|
|
346
|
+
pos.accruedUnclaimed += wholeTokens;
|
|
347
|
+
pos.accruedScaled %= ACC_PRECISION;
|
|
348
|
+
}
|
|
349
|
+
pos.rewardDebt = pos.shares * this.accRewardPerShare / ACC_PRECISION;
|
|
350
|
+
}
|
|
351
|
+
mintShares(holderDid, amount) {
|
|
352
|
+
if (!holderDid || !holderDid.trim()) throw new Error("holderDid is required");
|
|
353
|
+
const delta = parseNonNegativeBigInt(amount, "shares");
|
|
354
|
+
if (delta <= 0n) throw new Error("shares to mint must be positive");
|
|
355
|
+
const id = holderDid.trim();
|
|
356
|
+
let pos = this.positions.get(id);
|
|
357
|
+
if (!pos) {
|
|
358
|
+
pos = {
|
|
359
|
+
holderDid: id,
|
|
360
|
+
shares: 0n,
|
|
361
|
+
rewardDebt: 0n,
|
|
362
|
+
accruedUnclaimed: 0n,
|
|
363
|
+
totalClaimed: 0n,
|
|
364
|
+
lastAccRewardPerShare: this.accRewardPerShare,
|
|
365
|
+
accruedScaled: 0n
|
|
366
|
+
};
|
|
367
|
+
this.positions.set(id, pos);
|
|
368
|
+
} else this.settlePosition(pos);
|
|
369
|
+
pos.shares += delta;
|
|
370
|
+
this.totalShares += delta;
|
|
371
|
+
pos.rewardDebt = pos.shares * this.accRewardPerShare / ACC_PRECISION;
|
|
372
|
+
return this.toPublicPosition(pos);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Distributes new cashflow into the equity pool in O(1) time.
|
|
376
|
+
*/
|
|
377
|
+
distributeRevenue(inflowAmount) {
|
|
378
|
+
const inflow = parseNonNegativeBigInt(inflowAmount, "inflowAmount");
|
|
379
|
+
if (inflow === 0n) return {
|
|
380
|
+
accRewardPerShare: this.accRewardPerShare,
|
|
381
|
+
totalRevenueDistributed: this.totalRevenueDistributed
|
|
382
|
+
};
|
|
383
|
+
if (this.totalShares <= 0n) throw new Error("NO_ACTIVE_SHARES: cannot distribute revenue when totalShares is 0");
|
|
384
|
+
const scaled = inflow * ACC_PRECISION + this.carryRemainder;
|
|
385
|
+
const deltaAcc = scaled / this.totalShares;
|
|
386
|
+
this.carryRemainder = scaled % this.totalShares;
|
|
387
|
+
this.accRewardPerShare += deltaAcc;
|
|
388
|
+
this.totalRevenueDistributed += inflow;
|
|
389
|
+
return {
|
|
390
|
+
accRewardPerShare: this.accRewardPerShare,
|
|
391
|
+
totalRevenueDistributed: this.totalRevenueDistributed
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Returns total claimable dividends for `holderDid` without mutating state.
|
|
396
|
+
*/
|
|
397
|
+
pendingDividend(holderDid) {
|
|
398
|
+
const pos = this.positions.get(holderDid.trim());
|
|
399
|
+
if (!pos) return 0n;
|
|
400
|
+
const deltaAcc = this.accRewardPerShare - pos.lastAccRewardPerShare;
|
|
401
|
+
const totalScaled = pos.accruedScaled + (pos.shares > 0n && deltaAcc > 0n ? pos.shares * deltaAcc : 0n);
|
|
402
|
+
return pos.accruedUnclaimed + totalScaled / ACC_PRECISION;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Atomically settles both seller and buyer dividend checkpoints before transferring `shareAmount`
|
|
406
|
+
* so the seller can sell their equity token for NPV while retaining all prior unpaid dividends,
|
|
407
|
+
* and the buyer earns 100% of future cashflows on the transferred shares.
|
|
408
|
+
*/
|
|
409
|
+
transferShares(fromDid, toDid, shareAmount) {
|
|
410
|
+
const fromId = fromDid.trim();
|
|
411
|
+
const toId = toDid.trim();
|
|
412
|
+
if (!fromId || !toId || fromId === toId) throw new Error("fromDid and toDid must be distinct non-empty DIDs");
|
|
413
|
+
const delta = parseNonNegativeBigInt(shareAmount, "shareAmount");
|
|
414
|
+
if (delta <= 0n) throw new Error("shareAmount must be positive");
|
|
415
|
+
const fromPos = this.positions.get(fromId);
|
|
416
|
+
if (!fromPos || fromPos.shares < delta) throw new Error(`INSUFFICIENT_SHARES: ${fromId} does not hold ${delta.toString()} shares`);
|
|
417
|
+
let toPos = this.positions.get(toId);
|
|
418
|
+
if (!toPos) {
|
|
419
|
+
toPos = {
|
|
420
|
+
holderDid: toId,
|
|
421
|
+
shares: 0n,
|
|
422
|
+
rewardDebt: 0n,
|
|
423
|
+
accruedUnclaimed: 0n,
|
|
424
|
+
totalClaimed: 0n,
|
|
425
|
+
lastAccRewardPerShare: this.accRewardPerShare,
|
|
426
|
+
accruedScaled: 0n
|
|
427
|
+
};
|
|
428
|
+
this.positions.set(toId, toPos);
|
|
429
|
+
}
|
|
430
|
+
this.settlePosition(fromPos);
|
|
431
|
+
this.settlePosition(toPos);
|
|
432
|
+
fromPos.shares -= delta;
|
|
433
|
+
fromPos.rewardDebt = fromPos.shares * this.accRewardPerShare / ACC_PRECISION;
|
|
434
|
+
toPos.shares += delta;
|
|
435
|
+
toPos.rewardDebt = toPos.shares * this.accRewardPerShare / ACC_PRECISION;
|
|
436
|
+
return {
|
|
437
|
+
fromPosition: this.toPublicPosition(fromPos),
|
|
438
|
+
toPosition: this.toPublicPosition(toPos)
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Claims all accrued dividends for `holderDid`.
|
|
443
|
+
*/
|
|
444
|
+
claimDividend(holderDid) {
|
|
445
|
+
const pos = this.positions.get(holderDid.trim());
|
|
446
|
+
if (!pos) return 0n;
|
|
447
|
+
this.settlePosition(pos);
|
|
448
|
+
const claimable = pos.accruedUnclaimed;
|
|
449
|
+
pos.accruedUnclaimed = 0n;
|
|
450
|
+
pos.totalClaimed += claimable;
|
|
451
|
+
return claimable;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Computes deterministic on-chain NPV (Net Present Value) valuation for a given share count
|
|
455
|
+
* based on trailing/projected periodic net cashflow, discount rate in basis points, horizon periods,
|
|
456
|
+
* and optional hard reserve floor backing the asset.
|
|
457
|
+
*/
|
|
458
|
+
estimateShareNpv(params) {
|
|
459
|
+
if (this.totalShares <= 0n) throw new Error("Cannot value shares when totalShares is 0");
|
|
460
|
+
const sharesToValue = parseNonNegativeBigInt(params.sharesToValue, "sharesToValue");
|
|
461
|
+
if (sharesToValue > this.totalShares) throw new Error("sharesToValue cannot exceed totalShares");
|
|
462
|
+
const periodRevenue = parseNonNegativeBigInt(params.expectedPeriodRevenue, "expectedPeriodRevenue");
|
|
463
|
+
const reserveFloorTotal = params.reserveFloorTotal !== void 0 ? parseNonNegativeBigInt(params.reserveFloorTotal, "reserveFloorTotal") : 0n;
|
|
464
|
+
if (!Number.isInteger(params.discountRateBpsPerPeriod) || params.discountRateBpsPerPeriod <= 0 || params.discountRateBpsPerPeriod > 1e4) throw new Error("discountRateBpsPerPeriod must be an integer between 1 and 10000");
|
|
465
|
+
if (!Number.isInteger(params.horizonPeriods) || params.horizonPeriods < 1 || params.horizonPeriods > 360) throw new Error("horizonPeriods must be an integer between 1 and 360");
|
|
466
|
+
let dcfPresentValueTotal = 0n;
|
|
467
|
+
let discountDenom = ACC_PRECISION;
|
|
468
|
+
const rateFactor = 10000n + BigInt(params.discountRateBpsPerPeriod);
|
|
469
|
+
for (let t = 1; t <= params.horizonPeriods; t++) {
|
|
470
|
+
discountDenom = discountDenom * rateFactor / 10000n;
|
|
471
|
+
dcfPresentValueTotal += periodRevenue * ACC_PRECISION / discountDenom;
|
|
472
|
+
}
|
|
473
|
+
const totalPoolNpv = dcfPresentValueTotal + reserveFloorTotal;
|
|
474
|
+
return {
|
|
475
|
+
totalPoolNpv,
|
|
476
|
+
shareNpv: totalPoolNpv * sharesToValue / this.totalShares,
|
|
477
|
+
dcfPresentValueTotal,
|
|
478
|
+
reserveFloorTotal
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
//#endregion
|
|
484
|
+
export { RevenueSharePool, assertMachineBankrollSolvency, deriveProvablyFairRoll, generateHashChain, resolveHierarchicalSplitDag, resolveWeightedLootTable, settleArcadeMachinePlay, verifyHashChainStep };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
//#region src/bonding-reserve-aup.d.ts
|
|
2
|
+
interface BondingCurveMintConfig {
|
|
3
|
+
factoryDid: string;
|
|
4
|
+
/** Starting base price for supply index 0 (must be > 0n) */
|
|
5
|
+
basePrice: bigint | number | string;
|
|
6
|
+
/** Linear price increment per minted unit (`price(s) = basePrice + slope * s`) */
|
|
7
|
+
linearSlope: bigint | number | string;
|
|
8
|
+
/** Basis points locked in `reserveBucket` to back floor burn redemptions (must be > 0) */
|
|
9
|
+
reserveBps: number;
|
|
10
|
+
/** Basis points routed to the game studio / developer */
|
|
11
|
+
devBps: number;
|
|
12
|
+
/** Basis points routed to Studio Key / Equity Share holders */
|
|
13
|
+
studioKeyBps: number;
|
|
14
|
+
/** Basis points routed to protocol treasury */
|
|
15
|
+
protocolFeeBps: number;
|
|
16
|
+
}
|
|
17
|
+
interface BondingMintQuote {
|
|
18
|
+
supplyIndex: bigint;
|
|
19
|
+
grossPrice: bigint;
|
|
20
|
+
reserveCut: bigint;
|
|
21
|
+
devCut: bigint;
|
|
22
|
+
studioKeyCut: bigint;
|
|
23
|
+
protocolFeeCut: bigint;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Quotes the deterministic bonding curve mint price at `supplyIndex` and computes the exact
|
|
27
|
+
* 4-bucket split (`reserveCut + devCut + studioKeyCut + protocolFeeCut === grossPrice`).
|
|
28
|
+
* Any integer rounding remainder is retained in `reserveCut` so floor solvency never leaks.
|
|
29
|
+
*/
|
|
30
|
+
declare function quoteBondingCurveMint(config: BondingCurveMintConfig, supplyIndex: bigint | number | string): BondingMintQuote;
|
|
31
|
+
interface ReserveBackedAssetRecord {
|
|
32
|
+
assetDid: string;
|
|
33
|
+
ownerDid: string;
|
|
34
|
+
supplyIndex: bigint;
|
|
35
|
+
lockedFloorReserve: bigint;
|
|
36
|
+
burned: boolean;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Stateful Reserve Vault for Bonding-Curve Asset Factories (#1185):
|
|
40
|
+
* - Isolates `reserveBucket` (strictly backing asset floor redemptions; developer can never withdraw it)
|
|
41
|
+
* from `devBucket`, `studioKeyBucket`, and `protocolFeeBucket`.
|
|
42
|
+
* - Supports guaranteed floor burn redemption (`redeemAssetFloor`), returning the asset's locked
|
|
43
|
+
* floor reserve (plus any mounted owned child reserves) upon burn.
|
|
44
|
+
*/
|
|
45
|
+
declare class BondingReserveVault {
|
|
46
|
+
readonly config: BondingCurveMintConfig;
|
|
47
|
+
private currentSupply;
|
|
48
|
+
private activeCirculatingCount;
|
|
49
|
+
private reserveBucket;
|
|
50
|
+
private devBucket;
|
|
51
|
+
private studioKeyBucket;
|
|
52
|
+
private protocolFeeBucket;
|
|
53
|
+
private readonly assets;
|
|
54
|
+
constructor(config: BondingCurveMintConfig);
|
|
55
|
+
getBuckets(): {
|
|
56
|
+
currentSupply: bigint;
|
|
57
|
+
activeCirculatingCount: bigint;
|
|
58
|
+
reserveBucket: bigint;
|
|
59
|
+
devBucket: bigint;
|
|
60
|
+
studioKeyBucket: bigint;
|
|
61
|
+
protocolFeeBucket: bigint;
|
|
62
|
+
};
|
|
63
|
+
mintAsset(params: {
|
|
64
|
+
assetDid: string;
|
|
65
|
+
ownerDid: string;
|
|
66
|
+
}): {
|
|
67
|
+
record: ReserveBackedAssetRecord;
|
|
68
|
+
quote: BondingMintQuote;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Burns an unmounted asset and releases its exact `lockedFloorReserve` from `reserveBucket`.
|
|
72
|
+
* Proves anti-rug conservation: `reserveBucket` always covers the sum of all unburned assets' `lockedFloorReserve`.
|
|
73
|
+
*/
|
|
74
|
+
redeemAssetFloor(params: {
|
|
75
|
+
assetDid: string;
|
|
76
|
+
callerDid: string;
|
|
77
|
+
independentRedemptionFrozen?: boolean;
|
|
78
|
+
}): {
|
|
79
|
+
redeemedAmount: bigint;
|
|
80
|
+
remainingReserveBucket: bigint;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
type AssetViewFormat = '2d-sprite' | '2d-board-ui' | '3d-gltf' | '3d-vrm' | '3d-voxel';
|
|
84
|
+
interface AssetViewDescriptor {
|
|
85
|
+
format: AssetViewFormat;
|
|
86
|
+
uri: string;
|
|
87
|
+
contentHash: string;
|
|
88
|
+
lodLevel?: number;
|
|
89
|
+
}
|
|
90
|
+
interface GenerativeLayerOption {
|
|
91
|
+
optionId: string;
|
|
92
|
+
weight: number;
|
|
93
|
+
traitValue: string | number;
|
|
94
|
+
layerAssetUri?: string;
|
|
95
|
+
}
|
|
96
|
+
interface GenerativeTraitLayerSpec {
|
|
97
|
+
layerKey: string;
|
|
98
|
+
options: readonly GenerativeLayerOption[];
|
|
99
|
+
}
|
|
100
|
+
interface AupMultiViewAssetManifest {
|
|
101
|
+
schemaVersion: 'aup.multiview.v1';
|
|
102
|
+
templateId: string;
|
|
103
|
+
assetDid: string;
|
|
104
|
+
category: string;
|
|
105
|
+
coreTraits: Record<string, string | number>;
|
|
106
|
+
views: readonly AssetViewDescriptor[];
|
|
107
|
+
applianceRulePresetId?: string;
|
|
108
|
+
manifestDigest: string;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Deterministically resolves multi-layer generative traits from `(templateId, assetDid, mintSeed)`
|
|
112
|
+
* and binds cross-game 2D/3D multi-view representations (`2d-sprite`, `2d-board-ui`, `3d-gltf`, `3d-vrm`, `3d-voxel`)
|
|
113
|
+
* into a canonical AUP Multi-View Asset Manifest (#1186).
|
|
114
|
+
*/
|
|
115
|
+
declare function buildAupMultiViewManifest(params: {
|
|
116
|
+
templateId: string;
|
|
117
|
+
assetDid: string;
|
|
118
|
+
category: string;
|
|
119
|
+
mintSeed: string;
|
|
120
|
+
traitLayers: readonly GenerativeTraitLayerSpec[];
|
|
121
|
+
views: readonly AssetViewDescriptor[];
|
|
122
|
+
applianceRulePresetId?: string;
|
|
123
|
+
}): AupMultiViewAssetManifest;
|
|
124
|
+
//#endregion
|
|
125
|
+
export { AssetViewDescriptor, AssetViewFormat, AupMultiViewAssetManifest, BondingCurveMintConfig, BondingMintQuote, BondingReserveVault, GenerativeLayerOption, GenerativeTraitLayerSpec, ReserveBackedAssetRecord, buildAupMultiViewManifest, quoteBondingCurveMint };
|