@ocap/util 1.30.26 → 1.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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
package/lib/arcade.d.cts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
//#region src/arcade.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Verifies a single step of an inverted SHA-256 commit-reveal hash chain:
|
|
4
|
+
* `sha256Hex(serverSeedPreimage) === expectedCommitHash`.
|
|
5
|
+
*/
|
|
6
|
+
declare function verifyHashChainStep(serverSeedPreimage: string, expectedCommitHash: string): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Generates an inverted SHA-256 hash chain of length `steps` from a terminal seed.
|
|
9
|
+
* Element `0` is the terminal secret (`seed_N`), and element `steps - 1` is the initial
|
|
10
|
+
* public commitment (`commit_0 = H^(steps-1)(seed_N)`).
|
|
11
|
+
*/
|
|
12
|
+
declare function generateHashChain(terminalSeed: string, steps: number): string[];
|
|
13
|
+
interface ProvablyFairRollInput {
|
|
14
|
+
/** Preimage revealed by the arcade/table for the current hash-chain index */
|
|
15
|
+
serverSeedPreimage: string;
|
|
16
|
+
/** Committed hash stored on-chain before the player's receipt was locked */
|
|
17
|
+
expectedCommitHash: string;
|
|
18
|
+
/** Canonical ForeignReceipt ID or on-chain transaction hash locking the bet */
|
|
19
|
+
receiptId: string;
|
|
20
|
+
/** Player-supplied client seed (entropy bound in the play request) */
|
|
21
|
+
clientSeed: string;
|
|
22
|
+
/** Strictly monotonic per-machine or per-player play nonce */
|
|
23
|
+
playNonce: bigint | number | string;
|
|
24
|
+
/** Upper bound (exclusive) for the uniform roll, defaults to 10_000 (basis points) */
|
|
25
|
+
modulus?: bigint | number | string;
|
|
26
|
+
}
|
|
27
|
+
interface ProvablyFairRollResult {
|
|
28
|
+
entropyHex: string;
|
|
29
|
+
nextCommitHash: string;
|
|
30
|
+
roll: bigint;
|
|
31
|
+
modulus: bigint;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Receipt-then-Reveal Provably Fair Randomness derivation:
|
|
35
|
+
* 1. Verifies `sha256(serverSeedPreimage) === expectedCommitHash`
|
|
36
|
+
* 2. Combines `(serverSeedPreimage, receiptId, clientSeed, playNonce)` via domain-separated SHA-256
|
|
37
|
+
* 3. Extracts an unbiased 256-bit integer modulo `modulus`
|
|
38
|
+
*/
|
|
39
|
+
declare function deriveProvablyFairRoll(input: ProvablyFairRollInput): ProvablyFairRollResult;
|
|
40
|
+
interface LootTableTier {
|
|
41
|
+
tierId: string;
|
|
42
|
+
weight: number;
|
|
43
|
+
payoutMultiplierBps: number;
|
|
44
|
+
}
|
|
45
|
+
interface PityConfig {
|
|
46
|
+
/** Number of consecutive non-high-tier rolls before pity triggers (e.g., 50) */
|
|
47
|
+
pityThreshold: number;
|
|
48
|
+
/** The tierId guaranteed when `currentPityCount + 1 >= pityThreshold` */
|
|
49
|
+
guaranteedTierId: string;
|
|
50
|
+
/** Tier IDs that reset the pity counter when hit naturally */
|
|
51
|
+
highTierIds: string[];
|
|
52
|
+
}
|
|
53
|
+
interface LootTableResolution {
|
|
54
|
+
selectedTier: LootTableTier;
|
|
55
|
+
pityTriggered: boolean;
|
|
56
|
+
nextPityCount: number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolves a weighted loot table roll with an optional deterministic pity counter.
|
|
60
|
+
*/
|
|
61
|
+
declare function resolveWeightedLootTable(tiers: readonly LootTableTier[], entropyValue: bigint | number | string, currentPityCount?: number, pityConfig?: PityConfig): LootTableResolution;
|
|
62
|
+
interface ArcadeMachineBankroll {
|
|
63
|
+
machineDid: string;
|
|
64
|
+
totalReserve: bigint;
|
|
65
|
+
lockedPendingPayouts: bigint;
|
|
66
|
+
maxSinglePayoutBps: number;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Verifies that an arcade/board-game machine's available reserve can cover `maxPossiblePayout`
|
|
70
|
+
* without violating `maxSinglePayoutBps` of its available bankroll.
|
|
71
|
+
*/
|
|
72
|
+
declare function assertMachineBankrollSolvency(bankroll: ArcadeMachineBankroll, maxPossiblePayout: bigint | number | string): {
|
|
73
|
+
availableReserve: bigint;
|
|
74
|
+
maxAllowedSinglePayout: bigint;
|
|
75
|
+
};
|
|
76
|
+
interface ArcadeFourWaySplitConfig {
|
|
77
|
+
/** Basis points allocated to the machine's prize reserve bucket */
|
|
78
|
+
reserveBps: number;
|
|
79
|
+
/** Basis points allocated to the machine/game creator (royalty) */
|
|
80
|
+
creatorBps: number;
|
|
81
|
+
/** Basis points allocated to the machine NFT owner/investor pool */
|
|
82
|
+
ownerBps: number;
|
|
83
|
+
/** Basis points allocated to the island/venue host container where the machine is mounted */
|
|
84
|
+
hostBps: number;
|
|
85
|
+
}
|
|
86
|
+
interface ArcadeRtpMetrics {
|
|
87
|
+
playCount: bigint;
|
|
88
|
+
totalBet: bigint;
|
|
89
|
+
totalPayout: bigint;
|
|
90
|
+
realizedRtpBps: number;
|
|
91
|
+
}
|
|
92
|
+
interface ArcadePlaySettlementResult {
|
|
93
|
+
betAmount: bigint;
|
|
94
|
+
payoutAmount: bigint;
|
|
95
|
+
reserveCut: bigint;
|
|
96
|
+
creatorCut: bigint;
|
|
97
|
+
ownerCut: bigint;
|
|
98
|
+
hostCut: bigint;
|
|
99
|
+
nextReserveBalance: bigint;
|
|
100
|
+
metrics: ArcadeRtpMetrics;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Atomically settles a single play on a mounted Arcade / Board-Game Machine NFT:
|
|
104
|
+
* - Splits `betAmount` into `(reserveCut, creatorCut, ownerCut, hostCut)` with exact conservation
|
|
105
|
+
* (any integer rounding remainder is retained in `reserveCut` so prize solvency never leaks).
|
|
106
|
+
* - Verifies `currentReserve + reserveCut >= payoutAmount`.
|
|
107
|
+
* - Updates public verifiable RTP / PnL metrics (`playCount`, `totalBet`, `totalPayout`, `realizedRtpBps`).
|
|
108
|
+
*/
|
|
109
|
+
declare function settleArcadeMachinePlay(params: {
|
|
110
|
+
betAmount: bigint | number | string;
|
|
111
|
+
payoutAmount: bigint | number | string;
|
|
112
|
+
currentReserve: bigint | number | string;
|
|
113
|
+
splitConfig: ArcadeFourWaySplitConfig;
|
|
114
|
+
maxPossiblePayout?: bigint | number | string;
|
|
115
|
+
previousMetrics?: ArcadeRtpMetrics;
|
|
116
|
+
}): ArcadePlaySettlementResult;
|
|
117
|
+
interface SplitRecipientEdge {
|
|
118
|
+
recipientDid: string;
|
|
119
|
+
shareBps: number;
|
|
120
|
+
}
|
|
121
|
+
type SplitGraphNodes = Record<string, readonly SplitRecipientEdge[]>;
|
|
122
|
+
/**
|
|
123
|
+
* Resolves a multi-level nested revenue-sharing DAG (e.g. an Island NFT co-owned by a Guild NFT
|
|
124
|
+
* and multiple partners, or a Game Machine NFT co-invested by a Syndicate NFT and angel investors).
|
|
125
|
+
*
|
|
126
|
+
* Enforces:
|
|
127
|
+
* - Acyclic graph invariant (`CYCLE_DETECTED` if `A -> B -> A` occurs)
|
|
128
|
+
* - Bounded recursion depth (`MAX_DEPTH_EXCEEDED` if nesting exceeds `maxDepth`)
|
|
129
|
+
* - Exact integer conservation at every internal node (rounding remainder is assigned to the first recipient edge)
|
|
130
|
+
* so that `sum(leafAllocations) === totalAmount` with zero dust loss.
|
|
131
|
+
*/
|
|
132
|
+
declare function resolveHierarchicalSplitDag(params: {
|
|
133
|
+
rootNodeDid: string;
|
|
134
|
+
totalAmount: bigint | number | string;
|
|
135
|
+
nodes: SplitGraphNodes;
|
|
136
|
+
maxDepth?: number;
|
|
137
|
+
}): Record<string, bigint>;
|
|
138
|
+
interface ShareHolderPosition {
|
|
139
|
+
holderDid: string;
|
|
140
|
+
shares: bigint;
|
|
141
|
+
rewardDebt: bigint;
|
|
142
|
+
accruedUnclaimed: bigint;
|
|
143
|
+
totalClaimed: bigint;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* O(1) Cumulative Dividend-Per-Share Pool (`accRewardPerShare`) for fractional/multi-investor
|
|
147
|
+
* Machine NFTs, Card Game Tables, and Co-Owned Islands.
|
|
148
|
+
*
|
|
149
|
+
* Supports:
|
|
150
|
+
* - O(1) revenue inflows (`distributeRevenue`) regardless of shareholder count
|
|
151
|
+
* - Ex-dividend checkpoint settlement on share transfers (`transferShares`) so sellers retain all
|
|
152
|
+
* dividends accrued prior to sale and buyers earn future cashflows from the transfer block onward
|
|
153
|
+
* - Exact unscaled fractional remainder preservation (`accruedScaled`) preventing Sybil share-splitting
|
|
154
|
+
* debt truncation attacks
|
|
155
|
+
* - On-chain DCF / NPV valuation (`estimateNpv`) combining trailing revenue cashflows and hard reserve floor
|
|
156
|
+
*/
|
|
157
|
+
declare class RevenueSharePool {
|
|
158
|
+
readonly assetDid: string;
|
|
159
|
+
private totalShares;
|
|
160
|
+
private accRewardPerShare;
|
|
161
|
+
private carryRemainder;
|
|
162
|
+
private totalRevenueDistributed;
|
|
163
|
+
private readonly positions;
|
|
164
|
+
constructor(assetDid: string, initialHolders?: ReadonlyArray<{
|
|
165
|
+
holderDid: string;
|
|
166
|
+
shares: bigint | number | string;
|
|
167
|
+
}>);
|
|
168
|
+
getTotalShares(): bigint;
|
|
169
|
+
getAccRewardPerShare(): bigint;
|
|
170
|
+
getTotalRevenueDistributed(): bigint;
|
|
171
|
+
private toPublicPosition;
|
|
172
|
+
private settlePosition;
|
|
173
|
+
mintShares(holderDid: string, amount: bigint | number | string): ShareHolderPosition;
|
|
174
|
+
/**
|
|
175
|
+
* Distributes new cashflow into the equity pool in O(1) time.
|
|
176
|
+
*/
|
|
177
|
+
distributeRevenue(inflowAmount: bigint | number | string): {
|
|
178
|
+
accRewardPerShare: bigint;
|
|
179
|
+
totalRevenueDistributed: bigint;
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Returns total claimable dividends for `holderDid` without mutating state.
|
|
183
|
+
*/
|
|
184
|
+
pendingDividend(holderDid: string): bigint;
|
|
185
|
+
/**
|
|
186
|
+
* Atomically settles both seller and buyer dividend checkpoints before transferring `shareAmount`
|
|
187
|
+
* so the seller can sell their equity token for NPV while retaining all prior unpaid dividends,
|
|
188
|
+
* and the buyer earns 100% of future cashflows on the transferred shares.
|
|
189
|
+
*/
|
|
190
|
+
transferShares(fromDid: string, toDid: string, shareAmount: bigint | number | string): {
|
|
191
|
+
fromPosition: ShareHolderPosition;
|
|
192
|
+
toPosition: ShareHolderPosition;
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Claims all accrued dividends for `holderDid`.
|
|
196
|
+
*/
|
|
197
|
+
claimDividend(holderDid: string): bigint;
|
|
198
|
+
/**
|
|
199
|
+
* Computes deterministic on-chain NPV (Net Present Value) valuation for a given share count
|
|
200
|
+
* based on trailing/projected periodic net cashflow, discount rate in basis points, horizon periods,
|
|
201
|
+
* and optional hard reserve floor backing the asset.
|
|
202
|
+
*/
|
|
203
|
+
estimateShareNpv(params: {
|
|
204
|
+
sharesToValue: bigint | number | string;
|
|
205
|
+
expectedPeriodRevenue: bigint | number | string;
|
|
206
|
+
discountRateBpsPerPeriod: number;
|
|
207
|
+
horizonPeriods: number;
|
|
208
|
+
reserveFloorTotal?: bigint | number | string;
|
|
209
|
+
}): {
|
|
210
|
+
totalPoolNpv: bigint;
|
|
211
|
+
shareNpv: bigint;
|
|
212
|
+
dcfPresentValueTotal: bigint;
|
|
213
|
+
reserveFloorTotal: bigint;
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
export { ArcadeFourWaySplitConfig, ArcadeMachineBankroll, ArcadePlaySettlementResult, ArcadeRtpMetrics, LootTableResolution, LootTableTier, PityConfig, ProvablyFairRollInput, ProvablyFairRollResult, RevenueSharePool, ShareHolderPosition, SplitGraphNodes, SplitRecipientEdge, assertMachineBankrollSolvency, deriveProvablyFairRoll, generateHashChain, resolveHierarchicalSplitDag, resolveWeightedLootTable, settleArcadeMachinePlay, verifyHashChainStep };
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
const require_sha2 = require('./node_modules/@noble/hashes/sha2.cjs');
|
|
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(require_sha2.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
|
+
exports.BondingReserveVault = BondingReserveVault;
|
|
231
|
+
exports.buildAupMultiViewManifest = buildAupMultiViewManifest;
|
|
232
|
+
exports.quoteBondingCurveMint = quoteBondingCurveMint;
|
|
@@ -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 };
|