@ocap/tx-pipeline 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.
Files changed (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +43 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +53 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +34 -0
  32. package/esm/pipes/pre-flight-waf.mjs +603 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +43 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +52 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +616 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +34 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,1257 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
3
+ let node_crypto = require("node:crypto");
4
+
5
+ //#region src/super-suites-foundation.ts
6
+ const ErrorCode = {
7
+ InvalidSuperSuite: "INVALID_SUPER_SUITE_PRIMITIVE",
8
+ ForbiddenSuperSuite: "FORBIDDEN_SUPER_SUITE_OPERATION",
9
+ ConservationViolation: "CONSERVATION_INVARIANT_VIOLATION"
10
+ };
11
+ const DEFAULT_ABT_TOKEN_ADDRESS = "z35n6UoHSi9s4232bd3832948239482394823";
12
+ const IBO_DIVIDEND_PRECISION = 10n ** 18n;
13
+ const BPS_DENOMINATOR = 10000n;
14
+ const MAX_PREPAID_CARD_ALLOWED_PROVIDERS = 64;
15
+ const MAX_IBO_TOTAL_FEE_SPLIT_BPS = 9e3;
16
+ const MAX_ARCADE_HOUSE_SPLIT_BPS = 5e3;
17
+ const MIN_ARCADE_HOUSE_SPLIT_BPS = 100;
18
+ const MAX_ARCADE_WINNERS_PER_ROUND = 50;
19
+ const MAX_STICKER_ROYALTY_BPS = 2500;
20
+ const MAX_SPACE_DISPLAYED_STICKERS = 100;
21
+ const MAX_SPACE_PLACED_MACHINES = 32;
22
+ const MIN_ATTENTION_STAMP_ABT = 1000000000000000n;
23
+ const MAX_ATTENTION_STAMP_TTL_EPOCHS = 90;
24
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
25
+ const FORBIDDEN_IDS = new Set([
26
+ "__proto__",
27
+ "constructor",
28
+ "prototype"
29
+ ]);
30
+ function assertCleanDidOrId(value, label) {
31
+ if (typeof value !== "string" || value.trim().length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be a non-empty string`);
32
+ const trimmed = value.trim();
33
+ if (trimmed !== value || FORBIDDEN_IDS.has(trimmed) || /[\s/\\?#%]|::|->/.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} contains unsafe characters`);
34
+ return trimmed;
35
+ }
36
+ function assertPositiveBigInt(value, label) {
37
+ if (typeof value !== "bigint" || value <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be a positive bigint`);
38
+ return value;
39
+ }
40
+ function assertNonNegativeBigInt(value, label) {
41
+ if (typeof value !== "bigint" || value < 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be a non-negative bigint`);
42
+ return value;
43
+ }
44
+ function assertValidEpoch(epochIndex, label = "epochIndex") {
45
+ if (typeof epochIndex !== "number" || !Number.isSafeInteger(epochIndex) || epochIndex < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be a non-negative safe integer`);
46
+ return epochIndex;
47
+ }
48
+ function assertValidBps(bps, label, maxBps = 1e4) {
49
+ if (typeof bps !== "number" || !Number.isSafeInteger(bps) || bps < 0 || bps > maxBps) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be an integer between 0 and ${maxBps}`);
50
+ return bps;
51
+ }
52
+ function assertBytes32Hex(value, label) {
53
+ if (typeof value !== "string" || !BYTES32_HEX_REGEX.test(value)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SuperSuites: ${label} must be a 32-byte 0x hex digest`);
54
+ return value.toLowerCase();
55
+ }
56
+ function sha256Hex(payload) {
57
+ return `0x${(0, node_crypto.createHash)("sha256").update(payload, "utf8").digest("hex")}`;
58
+ }
59
+ /**
60
+ * Compute deterministic 32-byte Merkle/manifest commitment for an ArcSpace room (#1277).
61
+ */
62
+ function computeSpaceManifestRootDigest(input) {
63
+ return sha256Hex(JSON.stringify({
64
+ domain: "OCAP_ARCSPACE_ROOM_MANIFEST_V1",
65
+ spaceDid: input.spaceDid,
66
+ roomOwnerDid: input.roomOwnerDid,
67
+ version: input.version,
68
+ displayedStickerDids: [...input.displayedStickerDids],
69
+ placedMachineDids: [...input.placedMachineDids],
70
+ offChainLayoutCommitmentDigest: input.offChainLayoutCommitmentDigest.toLowerCase(),
71
+ epochIndex: input.epochIndex
72
+ }));
73
+ }
74
+ /**
75
+ * Compute deterministic commit-reveal digest for an ArcadeMachine instant jackpot round (#1276).
76
+ */
77
+ function computeArcadeCommitDigest(houseSecretHex, roundId, machineDid) {
78
+ const cleanSecret = assertBytes32Hex(houseSecretHex, "houseSecretHex");
79
+ const cleanRound = assertCleanDidOrId(roundId, "roundId");
80
+ return sha256Hex(`OCAP_ARCADE_COMMIT_V1:${assertCleanDidOrId(machineDid, "machineDid")}:${cleanRound}:${cleanSecret}`);
81
+ }
82
+ /**
83
+ * Master Engine implementing Issues #1273, #1275, #1276, and #1277 (closing Master Epic #1272):
84
+ * - #1273: Lazy Shared `SponsorBudgetPool` & `PrepaidBudgetCard` NFT
85
+ * - #1275: `IboPartnerEngine` (`ArcKey` equity decoupled from flat consumer ticket + tiered holder commission + O(1) dividend pool)
86
+ * - #1276: `(A,B,C,n,m)` `ArcadeMachinePool` conservation engine + 10 ABT `StickerOfferAndRoyalty` escrow
87
+ * - #1277: `SpaceManifestAnchor` ownership/delegation verifier + `AttentionStampEscrow` anti-spam micro-ABT stamp
88
+ */
89
+ var OcapSuperSuitesFoundationEngine = class {
90
+ constructor() {
91
+ this.sponsorPools = /* @__PURE__ */ new Map();
92
+ this.prepaidCards = /* @__PURE__ */ new Map();
93
+ this.consumedRedemptionIds = /* @__PURE__ */ new Set();
94
+ this.iboOrgs = /* @__PURE__ */ new Map();
95
+ this.iboPositions = /* @__PURE__ */ new Map();
96
+ this.consumedCheckoutIds = /* @__PURE__ */ new Set();
97
+ this.arcadeMachines = /* @__PURE__ */ new Map();
98
+ this.arcadeRoundPlayers = /* @__PURE__ */ new Map();
99
+ this.arcadeRoundCommits = /* @__PURE__ */ new Map();
100
+ this.settledArcadeRounds = /* @__PURE__ */ new Set();
101
+ this.consumedPlayIds = /* @__PURE__ */ new Set();
102
+ this.stickers = /* @__PURE__ */ new Map();
103
+ this.stickerOffers = /* @__PURE__ */ new Map();
104
+ this.spaceDelegations = /* @__PURE__ */ new Map();
105
+ this.spaceManifests = /* @__PURE__ */ new Map();
106
+ this.attentionStamps = /* @__PURE__ */ new Map();
107
+ }
108
+ createSponsorBudgetPool(input) {
109
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing createSponsorBudgetPool input");
110
+ const poolDid = assertCleanDidOrId(input.poolDid, "poolDid");
111
+ const sponsorDid = assertCleanDidOrId(input.sponsorDid, "sponsorDid");
112
+ const tokenAddress = assertCleanDidOrId(input.tokenAddress ?? DEFAULT_ABT_TOKEN_ADDRESS, "tokenAddress");
113
+ const initialFundedAbt = assertPositiveBigInt(input.initialFundedAbt, "initialFundedAbt");
114
+ const epochIndex = assertValidEpoch(input.epochIndex);
115
+ if (this.sponsorPools.has(poolDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SponsorBudgetPool ${poolDid} already exists`);
116
+ const state = {
117
+ poolDid,
118
+ sponsorDid,
119
+ tokenAddress,
120
+ totalFundedAbt: initialFundedAbt,
121
+ totalDrainedAbt: 0n,
122
+ totalReclaimedAbt: 0n,
123
+ availableBalanceAbt: initialFundedAbt,
124
+ issuedCardCount: 0,
125
+ active: true,
126
+ createdAtEpoch: epochIndex
127
+ };
128
+ this.sponsorPools.set(poolDid, state);
129
+ return { ...state };
130
+ }
131
+ topUpSponsorBudgetPool(poolDid, callerDid, addAmountAbt) {
132
+ const cleanPoolDid = assertCleanDidOrId(poolDid, "poolDid");
133
+ const cleanCallerDid = assertCleanDidOrId(callerDid, "callerDid");
134
+ const amount = assertPositiveBigInt(addAmountAbt, "addAmountAbt");
135
+ const pool = this.sponsorPools.get(cleanPoolDid);
136
+ if (!pool) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown SponsorBudgetPool: ${cleanPoolDid}`);
137
+ if (pool.sponsorDid !== cleanCallerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only pool sponsorDid can top up SponsorBudgetPool");
138
+ pool.totalFundedAbt += amount;
139
+ pool.availableBalanceAbt += amount;
140
+ pool.active = true;
141
+ return { ...pool };
142
+ }
143
+ reclaimUnusedSponsorBudgetPool(poolDid, callerDid, reclaimAmountAbt) {
144
+ const cleanPoolDid = assertCleanDidOrId(poolDid, "poolDid");
145
+ const cleanCallerDid = assertCleanDidOrId(callerDid, "callerDid");
146
+ const amount = assertPositiveBigInt(reclaimAmountAbt, "reclaimAmountAbt");
147
+ const pool = this.sponsorPools.get(cleanPoolDid);
148
+ if (!pool) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown SponsorBudgetPool: ${cleanPoolDid}`);
149
+ if (pool.sponsorDid !== cleanCallerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only pool sponsorDid can reclaim unused SponsorBudgetPool balance");
150
+ if (amount > pool.availableBalanceAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Reclaim amount (${amount}) exceeds available pool balance (${pool.availableBalanceAbt})`);
151
+ pool.availableBalanceAbt -= amount;
152
+ pool.totalReclaimedAbt += amount;
153
+ return { ...pool };
154
+ }
155
+ issuePrepaidBudgetCard(input) {
156
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing issuePrepaidBudgetCard input");
157
+ const cardDid = assertCleanDidOrId(input.cardDid, "cardDid");
158
+ const poolDid = assertCleanDidOrId(input.poolDid, "poolDid");
159
+ const callerDid = assertCleanDidOrId(input.callerDid, "callerDid");
160
+ const recipientHolderDid = assertCleanDidOrId(input.recipientHolderDid, "recipientHolderDid");
161
+ const maxAllowanceAbt = assertPositiveBigInt(input.maxAllowanceAbt, "maxAllowanceAbt");
162
+ const dailyLimitAbt = assertPositiveBigInt(input.dailyLimitAbt, "dailyLimitAbt");
163
+ const issuedAtEpoch = assertValidEpoch(input.issuedAtEpoch, "issuedAtEpoch");
164
+ const expiresAtEpoch = assertValidEpoch(input.expiresAtEpoch, "expiresAtEpoch");
165
+ if (this.prepaidCards.has(cardDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `PrepaidBudgetCard ${cardDid} already exists`);
166
+ if (dailyLimitAbt > maxAllowanceAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "dailyLimitAbt cannot exceed maxAllowanceAbt");
167
+ if (expiresAtEpoch < issuedAtEpoch) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "expiresAtEpoch must be >= issuedAtEpoch");
168
+ const pool = this.sponsorPools.get(poolDid);
169
+ if (!pool || !pool.active) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `SponsorBudgetPool ${poolDid} does not exist or is inactive`);
170
+ if (pool.sponsorDid !== callerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only the SponsorBudgetPool owner can issue PrepaidBudgetCard NFTs");
171
+ if (recipientHolderDid === pool.sponsorDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "recipientHolderDid must be distinct from sponsorDid to prevent circular wash redemptions");
172
+ if (!Array.isArray(input.allowedProviderDids) || input.allowedProviderDids.length === 0 || input.allowedProviderDids.length > MAX_PREPAID_CARD_ALLOWED_PROVIDERS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `allowedProviderDids must contain 1..${MAX_PREPAID_CARD_ALLOWED_PROVIDERS} whitelisted service provider DIDs`);
173
+ const dedupProviders = Array.from(new Set(input.allowedProviderDids.map((p, idx) => assertCleanDidOrId(p, `allowedProviderDids[${idx}]`))));
174
+ for (const pDid of dedupProviders) if (pDid === recipientHolderDid || pDid === pool.sponsorDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "allowedProviderDids cannot include recipientHolderDid or sponsorDid (cashout prohibition)");
175
+ pool.issuedCardCount += 1;
176
+ const card = {
177
+ cardDid,
178
+ poolDid,
179
+ sponsorDid: pool.sponsorDid,
180
+ holderDid: recipientHolderDid,
181
+ maxAllowanceAbt,
182
+ consumedAbt: 0n,
183
+ dailyLimitAbt,
184
+ dailyConsumedByDay: {},
185
+ allowedProviderDids: dedupProviders,
186
+ issuedAtEpoch,
187
+ expiresAtEpoch,
188
+ transferable: false,
189
+ cashoutAllowed: false,
190
+ revoked: false
191
+ };
192
+ this.prepaidCards.set(cardDid, card);
193
+ return {
194
+ ...card,
195
+ dailyConsumedByDay: { ...card.dailyConsumedByDay },
196
+ allowedProviderDids: [...card.allowedProviderDids]
197
+ };
198
+ }
199
+ redeemPrepaidBudgetCard(input) {
200
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing redeemPrepaidBudgetCard input");
201
+ const redemptionId = assertCleanDidOrId(input.redemptionId, "redemptionId");
202
+ const cardDid = assertCleanDidOrId(input.cardDid, "cardDid");
203
+ const callerDid = assertCleanDidOrId(input.callerDid, "callerDid");
204
+ const providerDid = assertCleanDidOrId(input.providerDid, "providerDid");
205
+ const serviceRefId = assertCleanDidOrId(input.serviceRefId, "serviceRefId");
206
+ const redeemAmountAbt = assertPositiveBigInt(input.redeemAmountAbt, "redeemAmountAbt");
207
+ const epochIndex = assertValidEpoch(input.epochIndex, "epochIndex");
208
+ const dayIndex = input.dayIndex !== void 0 ? assertValidEpoch(input.dayIndex, "dayIndex") : epochIndex;
209
+ if (dayIndex !== epochIndex) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `dayIndex (${dayIndex}) must match canonical epochIndex (${epochIndex}) to prevent dailyLimitAbt bypass`);
210
+ if (this.consumedRedemptionIds.has(redemptionId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Duplicate prepaid card redemptionId: ${redemptionId}`);
211
+ const card = this.prepaidCards.get(cardDid);
212
+ if (!card) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown PrepaidBudgetCard: ${cardDid}`);
213
+ if (card.holderDid !== callerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "PrepaidBudgetCard is non-transferable and can only be redeemed by its holderDid");
214
+ if (card.revoked) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `PrepaidBudgetCard ${cardDid} has been revoked`);
215
+ if (epochIndex < card.issuedAtEpoch || epochIndex > card.expiresAtEpoch) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `PrepaidBudgetCard ${cardDid} is outside valid epoch window (${card.issuedAtEpoch}..${card.expiresAtEpoch}) at epoch ${epochIndex}`);
216
+ if (providerDid === card.holderDid || providerDid === card.sponsorDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "PrepaidBudgetCard cannot be redeemed to holderDid or sponsorDid (cashout forbidden)");
217
+ if (!card.allowedProviderDids.includes(providerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Provider ${providerDid} is not whitelisted on PrepaidBudgetCard ${cardDid}`);
218
+ const remainingCardAllowance = card.maxAllowanceAbt - card.consumedAbt;
219
+ if (redeemAmountAbt > remainingCardAllowance) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Redemption (${redeemAmountAbt}) exceeds remaining card allowance (${remainingCardAllowance})`);
220
+ const consumedToday = card.dailyConsumedByDay[dayIndex] ?? 0n;
221
+ const remainingDailyAllowance = card.dailyLimitAbt - consumedToday;
222
+ if (redeemAmountAbt > remainingDailyAllowance) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Redemption (${redeemAmountAbt}) exceeds remaining daily limit (${remainingDailyAllowance}) for day ${dayIndex}`);
223
+ const pool = this.sponsorPools.get(card.poolDid);
224
+ if (!pool || !pool.active) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `SponsorBudgetPool ${card.poolDid} is inactive`);
225
+ if (redeemAmountAbt > pool.availableBalanceAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `SponsorBudgetPool ${card.poolDid} has insufficient available ABT (${pool.availableBalanceAbt} < ${redeemAmountAbt})`);
226
+ this.consumedRedemptionIds.add(redemptionId);
227
+ card.consumedAbt += redeemAmountAbt;
228
+ card.dailyConsumedByDay[dayIndex] = consumedToday + redeemAmountAbt;
229
+ pool.availableBalanceAbt -= redeemAmountAbt;
230
+ pool.totalDrainedAbt += redeemAmountAbt;
231
+ const statements = [{
232
+ type: "transfer_v3",
233
+ typeUrl: "fg:t:transfer_v3",
234
+ from: pool.poolDid,
235
+ itx: {
236
+ to: providerDid,
237
+ tokens: [{
238
+ address: pool.tokenAddress,
239
+ value: redeemAmountAbt.toString(10)
240
+ }],
241
+ data: {
242
+ type: "json",
243
+ value: JSON.stringify({
244
+ primitive: "PREPAID_BUDGET_CARD_REDEMPTION",
245
+ redemptionId,
246
+ cardDid,
247
+ holderDid: card.holderDid,
248
+ serviceRefId,
249
+ epochIndex,
250
+ dayIndex
251
+ })
252
+ }
253
+ }
254
+ }];
255
+ const postConditions = {
256
+ signer: pool.poolDid,
257
+ maxTokenOutflow: { [pool.tokenAddress]: redeemAmountAbt.toString(10) },
258
+ strictZeroUnlistedOutflow: true
259
+ };
260
+ return {
261
+ redemptionId,
262
+ cardDid,
263
+ poolDid: pool.poolDid,
264
+ holderDid: card.holderDid,
265
+ providerDid,
266
+ serviceRefId,
267
+ drainedAbt: redeemAmountAbt,
268
+ remainingCardAllowanceAbt: card.maxAllowanceAbt - card.consumedAbt,
269
+ remainingDailyAllowanceAbt: card.dailyLimitAbt - card.dailyConsumedByDay[dayIndex],
270
+ remainingPoolAvailableAbt: pool.availableBalanceAbt,
271
+ capitalFrozenAtMintAbt: 0n,
272
+ statements,
273
+ postConditions
274
+ };
275
+ }
276
+ getSponsorBudgetPool(poolDid) {
277
+ const p = this.sponsorPools.get(poolDid);
278
+ return p ? { ...p } : void 0;
279
+ }
280
+ getPrepaidBudgetCard(cardDid) {
281
+ const c = this.prepaidCards.get(cardDid);
282
+ return c ? {
283
+ ...c,
284
+ dailyConsumedByDay: { ...c.dailyConsumedByDay },
285
+ allowedProviderDids: [...c.allowedProviderDids]
286
+ } : void 0;
287
+ }
288
+ registerIboOrganization(input) {
289
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing registerIboOrganization input");
290
+ const orgDid = assertCleanDidOrId(input.orgDid, "orgDid");
291
+ const creatorDid = assertCleanDidOrId(input.creatorDid, "creatorDid");
292
+ const computeProviderDid = assertCleanDidOrId(input.computeProviderDid, "computeProviderDid");
293
+ const tokenAddress = assertCleanDidOrId(input.tokenAddress ?? DEFAULT_ABT_TOKEN_ADDRESS, "tokenAddress");
294
+ const baseAffiliateBps = assertValidBps(input.baseAffiliateBps, "baseAffiliateBps", 5e3);
295
+ const holderAffiliateBps = assertValidBps(input.holderAffiliateBps, "holderAffiliateBps", 5e3);
296
+ const dividendPoolBps = assertValidBps(input.dividendPoolBps, "dividendPoolBps", 5e3);
297
+ const computeSplitBps = assertValidBps(input.computeSplitBps, "computeSplitBps", 5e3);
298
+ const minPartnerKeyBalance = assertPositiveBigInt(input.minPartnerKeyBalance, "minPartnerKeyBalance");
299
+ const epochIndex = assertValidEpoch(input.epochIndex);
300
+ if (this.iboOrgs.has(orgDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `IBO Organization ${orgDid} already exists`);
301
+ if (holderAffiliateBps < baseAffiliateBps) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "holderAffiliateBps must be >= baseAffiliateBps to incentivize ArcKey partner ownership");
302
+ const maxNonCreatorBps = holderAffiliateBps + dividendPoolBps + computeSplitBps;
303
+ if (maxNonCreatorBps > MAX_IBO_TOTAL_FEE_SPLIT_BPS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `holderAffiliateBps + dividendPoolBps + computeSplitBps (${maxNonCreatorBps}) cannot exceed ${MAX_IBO_TOTAL_FEE_SPLIT_BPS} bps`);
304
+ const posMap = /* @__PURE__ */ new Map();
305
+ let totalKeys = 0n;
306
+ if (Array.isArray(input.initialPartners)) for (let i = 0; i < input.initialPartners.length; i += 1) {
307
+ const entry = input.initialPartners[i];
308
+ const partnerDid = assertCleanDidOrId(entry.partnerDid, `initialPartners[${i}].partnerDid`);
309
+ const keyBalance = assertPositiveBigInt(entry.keyBalance, `initialPartners[${i}].keyBalance`);
310
+ if (posMap.has(partnerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Duplicate initial partnerDid: ${partnerDid}`);
311
+ posMap.set(partnerDid, {
312
+ orgDid,
313
+ partnerDid,
314
+ keyBalance,
315
+ rewardDebtScaled: 0n,
316
+ pendingUnclaimedAbt: 0n,
317
+ cumulativeClaimedAbt: 0n
318
+ });
319
+ totalKeys += keyBalance;
320
+ }
321
+ const state = {
322
+ orgDid,
323
+ creatorDid,
324
+ computeProviderDid,
325
+ tokenAddress,
326
+ baseAffiliateBps,
327
+ holderAffiliateBps,
328
+ dividendPoolBps,
329
+ computeSplitBps,
330
+ minPartnerKeyBalance,
331
+ totalPartnerKeysSupply: totalKeys,
332
+ accDividendPerKeyScaled: 0n,
333
+ undistributedDividendRemainderScaled: 0n,
334
+ totalGrossVolumeAbt: 0n,
335
+ totalAffiliatePaidAbt: 0n,
336
+ totalDividendsDistributedAbt: 0n,
337
+ totalDividendClaimedAbt: 0n,
338
+ totalComputePaidAbt: 0n,
339
+ totalCreatorNetAbt: 0n,
340
+ createdAtEpoch: epochIndex
341
+ };
342
+ this.iboOrgs.set(orgDid, state);
343
+ this.iboPositions.set(orgDid, posMap);
344
+ return { ...state };
345
+ }
346
+ settlePartnerPendingReward(org, pos) {
347
+ const accumulatedScaled = pos.keyBalance * org.accDividendPerKeyScaled;
348
+ if (accumulatedScaled > pos.rewardDebtScaled) {
349
+ const newlyEarnedAbt = (accumulatedScaled - pos.rewardDebtScaled) / IBO_DIVIDEND_PRECISION;
350
+ pos.pendingUnclaimedAbt += newlyEarnedAbt;
351
+ }
352
+ pos.rewardDebtScaled = pos.keyBalance * org.accDividendPerKeyScaled;
353
+ }
354
+ updatePartnerKeyBalance(orgDid, callerDid, partnerDid, newKeyBalance) {
355
+ const cleanOrgDid = assertCleanDidOrId(orgDid, "orgDid");
356
+ const cleanCallerDid = assertCleanDidOrId(callerDid, "callerDid");
357
+ const cleanPartnerDid = assertCleanDidOrId(partnerDid, "partnerDid");
358
+ const balance = assertNonNegativeBigInt(newKeyBalance, "newKeyBalance");
359
+ const org = this.iboOrgs.get(cleanOrgDid);
360
+ const posMap = this.iboPositions.get(cleanOrgDid);
361
+ if (!org || !posMap) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown IBO Organization: ${cleanOrgDid}`);
362
+ if (cleanCallerDid !== org.creatorDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only IBO Organization creatorDid is authorized to update partner key balances");
363
+ let pos = posMap.get(cleanPartnerDid);
364
+ if (!pos) {
365
+ pos = {
366
+ orgDid: cleanOrgDid,
367
+ partnerDid: cleanPartnerDid,
368
+ keyBalance: 0n,
369
+ rewardDebtScaled: 0n,
370
+ pendingUnclaimedAbt: 0n,
371
+ cumulativeClaimedAbt: 0n
372
+ };
373
+ posMap.set(cleanPartnerDid, pos);
374
+ } else this.settlePartnerPendingReward(org, pos);
375
+ org.totalPartnerKeysSupply = org.totalPartnerKeysSupply - pos.keyBalance + balance;
376
+ pos.keyBalance = balance;
377
+ pos.rewardDebtScaled = pos.keyBalance * org.accDividendPerKeyScaled;
378
+ return { ...pos };
379
+ }
380
+ settleIboServiceCheckout(input) {
381
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing settleIboServiceCheckout input");
382
+ const checkoutId = assertCleanDidOrId(input.checkoutId, "checkoutId");
383
+ const orgDid = assertCleanDidOrId(input.orgDid, "orgDid");
384
+ const buyerDid = assertCleanDidOrId(input.buyerDid, "buyerDid");
385
+ const serviceId = assertCleanDidOrId(input.serviceId, "serviceId");
386
+ const ticketPriceAbt = assertPositiveBigInt(input.ticketPriceAbt, "ticketPriceAbt");
387
+ const epochIndex = assertValidEpoch(input.epochIndex);
388
+ if (this.consumedCheckoutIds.has(checkoutId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Duplicate IBO checkoutId: ${checkoutId}`);
389
+ const org = this.iboOrgs.get(orgDid);
390
+ const posMap = this.iboPositions.get(orgDid);
391
+ if (!org || !posMap) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown IBO Organization: ${orgDid}`);
392
+ let referrerDid;
393
+ let referrerIsPartnerHolder = false;
394
+ let appliedAffiliateBps = 0;
395
+ if (input.referrerDid !== void 0) {
396
+ referrerDid = assertCleanDidOrId(input.referrerDid, "referrerDid");
397
+ if (referrerDid === buyerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Self-referral is strictly forbidden in IBO checkout (referrerDid === buyerDid)");
398
+ const refPos = posMap.get(referrerDid);
399
+ referrerIsPartnerHolder = (refPos ? refPos.keyBalance : 0n) >= org.minPartnerKeyBalance;
400
+ appliedAffiliateBps = referrerIsPartnerHolder ? org.holderAffiliateBps : org.baseAffiliateBps;
401
+ }
402
+ let payerDid = buyerDid;
403
+ let fundedViaPrepaidCardDid;
404
+ if (input.prepaidCardRedemption) {
405
+ if (referrerDid !== void 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "PrepaidBudgetCard redemptions cannot pay external affiliate commissions (cashout prohibition)");
406
+ const cleanCardDid = assertCleanDidOrId(input.prepaidCardRedemption.cardDid, "prepaidCardRedemption.cardDid");
407
+ const card = this.prepaidCards.get(cleanCardDid);
408
+ if (!card) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown PrepaidBudgetCard: ${cleanCardDid}`);
409
+ if (buyerDid === org.creatorDid || buyerDid === org.computeProviderDid || card.sponsorDid === org.creatorDid || card.sponsorDid === org.computeProviderDid || (posMap.get(buyerDid)?.keyBalance ?? 0n) > 0n || (posMap.get(card.sponsorDid)?.keyBalance ?? 0n) > 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "PrepaidBudgetCard holder or sponsor cannot be IBO creator, compute provider, or ArcKey partner (wash-cashout prohibition)");
410
+ if (!card.allowedProviderDids.includes(orgDid) || !card.allowedProviderDids.includes(org.creatorDid) || org.computeSplitBps > 0 && !card.allowedProviderDids.includes(org.computeProviderDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "All IBO checkout split recipients (orgDid, creatorDid, computeProviderDid) must be whitelisted in PrepaidBudgetCard allowedProviderDids");
411
+ const cardRedeem = this.redeemPrepaidBudgetCard({
412
+ redemptionId: `ibo-redeem-${checkoutId}`,
413
+ cardDid: cleanCardDid,
414
+ callerDid: buyerDid,
415
+ providerDid: orgDid,
416
+ serviceRefId: serviceId,
417
+ redeemAmountAbt: ticketPriceAbt,
418
+ epochIndex,
419
+ dayIndex: input.prepaidCardRedemption.dayIndex
420
+ });
421
+ payerDid = cardRedeem.poolDid;
422
+ fundedViaPrepaidCardDid = cardRedeem.cardDid;
423
+ }
424
+ this.consumedCheckoutIds.add(checkoutId);
425
+ const affiliateAbt = ticketPriceAbt * BigInt(appliedAffiliateBps) / BPS_DENOMINATOR;
426
+ const dividendAbt = org.totalPartnerKeysSupply > 0n ? ticketPriceAbt * BigInt(org.dividendPoolBps) / BPS_DENOMINATOR : 0n;
427
+ const computeAbt = ticketPriceAbt * BigInt(org.computeSplitBps) / BPS_DENOMINATOR;
428
+ const creatorNetAbt = ticketPriceAbt - affiliateAbt - dividendAbt - computeAbt;
429
+ if (affiliateAbt + dividendAbt + computeAbt + creatorNetAbt !== ticketPriceAbt || creatorNetAbt < 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, "IBO checkout split failed conservation check");
430
+ if (dividendAbt > 0n && org.totalPartnerKeysSupply > 0n) {
431
+ const totalScaledDividend = dividendAbt * IBO_DIVIDEND_PRECISION + org.undistributedDividendRemainderScaled;
432
+ const deltaPerKeyScaled = totalScaledDividend / org.totalPartnerKeysSupply;
433
+ org.accDividendPerKeyScaled += deltaPerKeyScaled;
434
+ org.undistributedDividendRemainderScaled = totalScaledDividend % org.totalPartnerKeysSupply;
435
+ }
436
+ org.totalGrossVolumeAbt += ticketPriceAbt;
437
+ org.totalAffiliatePaidAbt += affiliateAbt;
438
+ org.totalDividendsDistributedAbt += dividendAbt;
439
+ org.totalComputePaidAbt += computeAbt;
440
+ org.totalCreatorNetAbt += creatorNetAbt;
441
+ const statements = [];
442
+ const pushSplitTransfer = (toDid, amount, splitRole) => {
443
+ if (amount <= 0n) return;
444
+ statements.push({
445
+ type: "transfer_v3",
446
+ typeUrl: "fg:t:transfer_v3",
447
+ from: payerDid,
448
+ itx: {
449
+ to: toDid,
450
+ tokens: [{
451
+ address: org.tokenAddress,
452
+ value: amount.toString(10)
453
+ }],
454
+ data: {
455
+ type: "json",
456
+ value: JSON.stringify({
457
+ primitive: "IBO_SERVICE_CHECKOUT_SPLIT",
458
+ checkoutId,
459
+ orgDid,
460
+ buyerDid,
461
+ serviceId,
462
+ splitRole,
463
+ fundedViaPrepaidCardDid
464
+ })
465
+ }
466
+ }
467
+ });
468
+ };
469
+ if (referrerDid && affiliateAbt > 0n) pushSplitTransfer(referrerDid, affiliateAbt, referrerIsPartnerHolder ? "PARTNER_HOLDER_AFFILIATE" : "BASE_AFFILIATE");
470
+ pushSplitTransfer(orgDid, dividendAbt, "IBO_PARTNER_DIVIDEND_POOL");
471
+ pushSplitTransfer(org.computeProviderDid, computeAbt, "ARC_COMPUTE_SPLIT");
472
+ pushSplitTransfer(org.creatorDid, creatorNetAbt, "CREATOR_NET_REVENUE");
473
+ const postConditions = {
474
+ signer: payerDid,
475
+ maxTokenOutflow: { [org.tokenAddress]: ticketPriceAbt.toString(10) },
476
+ strictZeroUnlistedOutflow: true
477
+ };
478
+ return {
479
+ checkoutId,
480
+ orgDid,
481
+ buyerDid,
482
+ payerDid,
483
+ fundedViaPrepaidCardDid,
484
+ ticketPriceAbt,
485
+ referrerDid,
486
+ referrerIsPartnerHolder,
487
+ appliedAffiliateBps,
488
+ affiliateAbt,
489
+ dividendAbt,
490
+ computeAbt,
491
+ creatorNetAbt,
492
+ conservationVerified: true,
493
+ statements,
494
+ postConditions
495
+ };
496
+ }
497
+ claimIboPartnerDividend(orgDid, partnerDid) {
498
+ const cleanOrgDid = assertCleanDidOrId(orgDid, "orgDid");
499
+ const cleanPartnerDid = assertCleanDidOrId(partnerDid, "partnerDid");
500
+ const org = this.iboOrgs.get(cleanOrgDid);
501
+ const posMap = this.iboPositions.get(cleanOrgDid);
502
+ if (!org || !posMap) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown IBO Organization: ${cleanOrgDid}`);
503
+ const pos = posMap.get(cleanPartnerDid);
504
+ if (!pos) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Partner ${cleanPartnerDid} has no position in ${cleanOrgDid}`);
505
+ this.settlePartnerPendingReward(org, pos);
506
+ const claimable = pos.pendingUnclaimedAbt;
507
+ if (claimable <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Partner ${cleanPartnerDid} has 0 claimable dividend ABT`);
508
+ if (claimable > org.totalDividendsDistributedAbt - org.totalDividendClaimedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, "Dividend claim exceeds available IBO dividend pool");
509
+ pos.pendingUnclaimedAbt = 0n;
510
+ pos.cumulativeClaimedAbt += claimable;
511
+ org.totalDividendClaimedAbt += claimable;
512
+ return {
513
+ orgDid: cleanOrgDid,
514
+ partnerDid: cleanPartnerDid,
515
+ claimedAbt: claimable,
516
+ cumulativeClaimedAbt: pos.cumulativeClaimedAbt,
517
+ statements: [{
518
+ type: "transfer_v3",
519
+ typeUrl: "fg:t:transfer_v3",
520
+ from: cleanOrgDid,
521
+ itx: {
522
+ to: cleanPartnerDid,
523
+ tokens: [{
524
+ address: org.tokenAddress,
525
+ value: claimable.toString(10)
526
+ }],
527
+ data: {
528
+ type: "json",
529
+ value: JSON.stringify({
530
+ primitive: "IBO_PARTNER_DIVIDEND_CLAIM",
531
+ orgDid: cleanOrgDid,
532
+ partnerDid: cleanPartnerDid
533
+ })
534
+ }
535
+ }
536
+ }]
537
+ };
538
+ }
539
+ getIboOrganization(orgDid) {
540
+ const o = this.iboOrgs.get(orgDid);
541
+ return o ? { ...o } : void 0;
542
+ }
543
+ registerArcadeMachine(input) {
544
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing registerArcadeMachine input");
545
+ const machineDid = assertCleanDidOrId(input.machineDid, "machineDid");
546
+ const gameCreatorDid = assertCleanDidOrId(input.gameCreatorDid, "gameCreatorDid");
547
+ const stickerArtistDid = assertCleanDidOrId(input.stickerArtistDid, "stickerArtistDid");
548
+ const roomHostDid = assertCleanDidOrId(input.roomHostDid, "roomHostDid");
549
+ const protocolTreasuryDid = assertCleanDidOrId(input.protocolTreasuryDid, "protocolTreasuryDid");
550
+ const tokenAddress = assertCleanDidOrId(input.tokenAddress ?? DEFAULT_ABT_TOKEN_ADDRESS, "tokenAddress");
551
+ const ticketPriceAbt = assertPositiveBigInt(input.ticketPriceAbt, "ticketPriceAbt");
552
+ const epochIndex = assertValidEpoch(input.epochIndex);
553
+ if (this.arcadeMachines.has(machineDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `ArcadeMachine ${machineDid} already exists`);
554
+ const creatorSplitBps = assertValidBps(input.creatorSplitBps, "creatorSplitBps", MAX_ARCADE_HOUSE_SPLIT_BPS);
555
+ const artistSplitBps = assertValidBps(input.artistSplitBps, "artistSplitBps", MAX_ARCADE_HOUSE_SPLIT_BPS);
556
+ const roomHostSplitBps = assertValidBps(input.roomHostSplitBps, "roomHostSplitBps", MAX_ARCADE_HOUSE_SPLIT_BPS);
557
+ const referrerSplitBps = assertValidBps(input.referrerSplitBps, "referrerSplitBps", MAX_ARCADE_HOUSE_SPLIT_BPS);
558
+ const protocolSplitBps = assertValidBps(input.protocolSplitBps, "protocolSplitBps", MAX_ARCADE_HOUSE_SPLIT_BPS);
559
+ const totalHouseSplitBps = creatorSplitBps + artistSplitBps + roomHostSplitBps + referrerSplitBps + protocolSplitBps;
560
+ if (totalHouseSplitBps < MIN_ARCADE_HOUSE_SPLIT_BPS || totalHouseSplitBps > MAX_ARCADE_HOUSE_SPLIT_BPS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Total house split B (${totalHouseSplitBps} bps) must be between ${MIN_ARCADE_HOUSE_SPLIT_BPS} and ${MAX_ARCADE_HOUSE_SPLIT_BPS} bps so Pool C receives >= 50%`);
561
+ if (input.settlementMode !== "COMMIT_REVEAL_INSTANT_JACKPOT" && input.settlementMode !== "TABLE_MATCH_SETTLEMENT" && input.settlementMode !== "EPOCH_HIGH_SCORE_LEADERBOARD") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unsupported settlementMode: ${String(input.settlementMode)}`);
562
+ const state = {
563
+ machineDid,
564
+ gameCreatorDid,
565
+ stickerArtistDid,
566
+ roomHostDid,
567
+ protocolTreasuryDid,
568
+ tokenAddress,
569
+ ticketPriceAbt,
570
+ creatorSplitBps,
571
+ artistSplitBps,
572
+ roomHostSplitBps,
573
+ referrerSplitBps,
574
+ protocolSplitBps,
575
+ totalHouseSplitBps,
576
+ prizePoolContributionBps: 1e4 - totalHouseSplitBps,
577
+ settlementMode: input.settlementMode,
578
+ poolBalanceAbt: 0n,
579
+ totalTicketsPlayed: 0,
580
+ totalGrossInflowAbt: 0n,
581
+ totalSplitBPaidAbt: 0n,
582
+ totalPoolCAddedAbt: 0n,
583
+ totalPayoutsDistributedAbt: 0n,
584
+ createdAtEpoch: epochIndex
585
+ };
586
+ this.arcadeMachines.set(machineDid, state);
587
+ return { ...state };
588
+ }
589
+ playArcadeMachineTicket(input) {
590
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing playArcadeMachineTicket input");
591
+ const playId = assertCleanDidOrId(input.playId, "playId");
592
+ const roundId = assertCleanDidOrId(input.roundId, "roundId");
593
+ const machineDid = assertCleanDidOrId(input.machineDid, "machineDid");
594
+ const playerDid = assertCleanDidOrId(input.playerDid, "playerDid");
595
+ assertValidEpoch(input.epochIndex);
596
+ if (this.consumedPlayIds.has(playId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Duplicate arcade playId: ${playId}`);
597
+ const machine = this.arcadeMachines.get(machineDid);
598
+ if (!machine) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown ArcadeMachine: ${machineDid}`);
599
+ const roundKey = `${machineDid}::${roundId}`;
600
+ if (this.settledArcadeRounds.has(roundKey)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Arcade round ${roundKey} has already been settled`);
601
+ let validatedCommitDigest;
602
+ if (machine.settlementMode === "COMMIT_REVEAL_INSTANT_JACKPOT") {
603
+ validatedCommitDigest = assertBytes32Hex(input.houseCommitDigest ?? "", "houseCommitDigest");
604
+ const existingCommit = this.arcadeRoundCommits.get(roundKey);
605
+ if (existingCommit && existingCommit !== validatedCommitDigest) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Conflicting houseCommitDigest for round ${roundKey}`);
606
+ }
607
+ let referrerDid;
608
+ if (input.referrerDid !== void 0) {
609
+ referrerDid = assertCleanDidOrId(input.referrerDid, "referrerDid");
610
+ if (referrerDid === playerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Self-referral is strictly forbidden in ArcadeMachine play (referrerDid === playerDid)");
611
+ }
612
+ const payerDid = playerDid;
613
+ const fundedViaPrepaidCardDid = void 0;
614
+ if (input.prepaidCardRedemption) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "PrepaidBudgetCard (cashoutAllowed: false) cannot fund cash-payout ArcadeMachine tickets");
615
+ if (validatedCommitDigest) this.arcadeRoundCommits.set(roundKey, validatedCommitDigest);
616
+ this.consumedPlayIds.add(playId);
617
+ let playersInRound = this.arcadeRoundPlayers.get(roundKey);
618
+ if (!playersInRound) {
619
+ playersInRound = /* @__PURE__ */ new Set();
620
+ this.arcadeRoundPlayers.set(roundKey, playersInRound);
621
+ }
622
+ playersInRound.add(playerDid);
623
+ const A = machine.ticketPriceAbt;
624
+ const creatorAbt = A * BigInt(machine.creatorSplitBps) / BPS_DENOMINATOR;
625
+ const artistAbt = A * BigInt(machine.artistSplitBps) / BPS_DENOMINATOR;
626
+ const roomHostAbt = A * BigInt(machine.roomHostSplitBps) / BPS_DENOMINATOR;
627
+ const referrerAbt = referrerDid ? A * BigInt(machine.referrerSplitBps) / BPS_DENOMINATOR : 0n;
628
+ const protocolAbt = A * BigInt(machine.protocolSplitBps) / BPS_DENOMINATOR;
629
+ const totalBAbt = creatorAbt + artistAbt + roomHostAbt + referrerAbt + protocolAbt;
630
+ const poolCAddedAbt = A - totalBAbt;
631
+ if (totalBAbt + poolCAddedAbt !== A || poolCAddedAbt <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, "ArcadeMachine (A = B + C) conservation equation violated");
632
+ machine.poolBalanceAbt += poolCAddedAbt;
633
+ machine.totalTicketsPlayed += 1;
634
+ machine.totalGrossInflowAbt += A;
635
+ machine.totalSplitBPaidAbt += totalBAbt;
636
+ machine.totalPoolCAddedAbt += poolCAddedAbt;
637
+ const statements = [];
638
+ const pushSplit = (toDid, amount, role) => {
639
+ if (amount <= 0n) return;
640
+ statements.push({
641
+ type: "transfer_v3",
642
+ typeUrl: "fg:t:transfer_v3",
643
+ from: payerDid,
644
+ itx: {
645
+ to: toDid,
646
+ tokens: [{
647
+ address: machine.tokenAddress,
648
+ value: amount.toString(10)
649
+ }],
650
+ data: {
651
+ type: "json",
652
+ value: JSON.stringify({
653
+ primitive: "ARCADE_MACHINE_TICKET_SPLIT",
654
+ playId,
655
+ roundId,
656
+ machineDid,
657
+ playerDid,
658
+ role
659
+ })
660
+ }
661
+ }
662
+ });
663
+ };
664
+ pushSplit(machine.gameCreatorDid, creatorAbt, "B_GAME_CREATOR");
665
+ pushSplit(machine.stickerArtistDid, artistAbt, "B_STICKER_ARTIST");
666
+ pushSplit(machine.roomHostDid, roomHostAbt, "B_SANDBOX_ROOM_HOST");
667
+ if (referrerDid && referrerAbt > 0n) pushSplit(referrerDid, referrerAbt, "B_REFERRER");
668
+ pushSplit(machine.protocolTreasuryDid, protocolAbt, "B_PROTOCOL_FEE");
669
+ pushSplit(machineDid, poolCAddedAbt, "C_CONSERVATION_PRIZE_POOL");
670
+ const postConditions = {
671
+ signer: payerDid,
672
+ maxTokenOutflow: { [machine.tokenAddress]: A.toString(10) },
673
+ strictZeroUnlistedOutflow: true
674
+ };
675
+ return {
676
+ playId,
677
+ roundId,
678
+ machineDid,
679
+ playerDid,
680
+ payerDid,
681
+ fundedViaPrepaidCardDid,
682
+ ticketPriceAbt: A,
683
+ splitB: {
684
+ creatorAbt,
685
+ artistAbt,
686
+ roomHostAbt,
687
+ referrerAbt,
688
+ protocolAbt,
689
+ totalBAbt
690
+ },
691
+ poolCAddedAbt,
692
+ newPoolBalanceAbt: machine.poolBalanceAbt,
693
+ conservationVerified: true,
694
+ statements,
695
+ postConditions
696
+ };
697
+ }
698
+ settleArcadeMachineWinners(input) {
699
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing settleArcadeMachineWinners input");
700
+ const settlementId = assertCleanDidOrId(input.settlementId, "settlementId");
701
+ const roundId = assertCleanDidOrId(input.roundId, "roundId");
702
+ const machineDid = assertCleanDidOrId(input.machineDid, "machineDid");
703
+ const callerDid = assertCleanDidOrId(input.callerDid, "callerDid");
704
+ assertValidEpoch(input.epochIndex);
705
+ const machine = this.arcadeMachines.get(machineDid);
706
+ if (!machine) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown ArcadeMachine: ${machineDid}`);
707
+ if (callerDid !== machine.gameCreatorDid && callerDid !== machine.roomHostDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only gameCreatorDid or roomHostDid can trigger ArcadeMachine round settlement");
708
+ if (input.mode !== machine.settlementMode) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Settlement mode (${input.mode}) does not match machine mode (${machine.settlementMode})`);
709
+ const roundKey = `${machineDid}::${roundId}`;
710
+ if (this.settledArcadeRounds.has(roundKey)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Arcade round ${roundKey} is already settled`);
711
+ const playersInRound = this.arcadeRoundPlayers.get(roundKey);
712
+ if (!playersInRound || playersInRound.size === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `No ticket plays recorded for round ${roundKey}`);
713
+ if (!Array.isArray(input.winners) || input.winners.length === 0 || input.winners.length > MAX_ARCADE_WINNERS_PER_ROUND) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `winners must contain 1..${MAX_ARCADE_WINNERS_PER_ROUND} entries`);
714
+ let deterministicRollBps;
715
+ if (input.mode === "COMMIT_REVEAL_INSTANT_JACKPOT") {
716
+ if (!input.commitRevealProof) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing commitRevealProof for instant jackpot mode");
717
+ const expectedCommit = this.arcadeRoundCommits.get(roundKey);
718
+ const recomputedCommit = computeArcadeCommitDigest(input.commitRevealProof.houseSecretHex, roundId, machineDid);
719
+ if (!expectedCommit || expectedCommit !== recomputedCommit) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Commit-reveal preimage does not match committed houseCommitDigest");
720
+ const playerSeed = assertBytes32Hex(input.commitRevealProof.playerSeedHex, "playerSeedHex");
721
+ const thresholdBps = assertValidBps(input.commitRevealProof.winningThresholdRollBps, "winningThresholdRollBps", 1e4);
722
+ const combinedHash = sha256Hex(`${recomputedCommit}:${playerSeed}:${roundId}`);
723
+ const rollInt = Number(BigInt(combinedHash) % BPS_DENOMINATOR);
724
+ deterministicRollBps = rollInt;
725
+ if (rollInt >= thresholdBps) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Deterministic roll (${rollInt} bps) did not beat winningThresholdRollBps (${thresholdBps} bps)`);
726
+ } else assertBytes32Hex(input.replayVerificationDigest ?? "", "replayVerificationDigest");
727
+ const poolBalanceBeforeAbt = machine.poolBalanceAbt;
728
+ if (poolBalanceBeforeAbt <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "ArcadeMachine Pool C has 0 balance");
729
+ let totalShareBps = 0;
730
+ const seenWinners = /* @__PURE__ */ new Set();
731
+ const winnerPayouts = [];
732
+ let totalPayoutAbt = 0n;
733
+ for (let i = 0; i < input.winners.length; i += 1) {
734
+ const w = input.winners[i];
735
+ const winnerDid = assertCleanDidOrId(w.winnerDid, `winners[${i}].winnerDid`);
736
+ const shareBps = assertValidBps(w.payoutShareOfPoolBps, `winners[${i}].payoutShareOfPoolBps`, 1e4);
737
+ if (shareBps <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "payoutShareOfPoolBps must be > 0");
738
+ if (seenWinners.has(winnerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Duplicate winnerDid in round settlement: ${winnerDid}`);
739
+ if (!playersInRound.has(winnerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Winner ${winnerDid} did not purchase a ticket in round ${roundKey}`);
740
+ seenWinners.add(winnerDid);
741
+ totalShareBps += shareBps;
742
+ const amountAbt = poolBalanceBeforeAbt * BigInt(shareBps) / BPS_DENOMINATOR;
743
+ winnerPayouts.push({
744
+ winnerDid,
745
+ amountAbt
746
+ });
747
+ totalPayoutAbt += amountAbt;
748
+ }
749
+ if (totalShareBps > 1e4 || totalPayoutAbt > poolBalanceBeforeAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, `Total winner payout (${totalPayoutAbt}) cannot exceed Pool C balance (${poolBalanceBeforeAbt})`);
750
+ this.settledArcadeRounds.add(roundKey);
751
+ machine.poolBalanceAbt -= totalPayoutAbt;
752
+ machine.totalPayoutsDistributedAbt += totalPayoutAbt;
753
+ const statements = winnerPayouts.filter((w) => w.amountAbt > 0n).map((w) => ({
754
+ type: "transfer_v3",
755
+ typeUrl: "fg:t:transfer_v3",
756
+ from: machineDid,
757
+ itx: {
758
+ to: w.winnerDid,
759
+ tokens: [{
760
+ address: machine.tokenAddress,
761
+ value: w.amountAbt.toString(10)
762
+ }],
763
+ data: {
764
+ type: "json",
765
+ value: JSON.stringify({
766
+ primitive: "ARCADE_MACHINE_POOL_C_PAYOUT",
767
+ settlementId,
768
+ roundId,
769
+ machineDid,
770
+ mode: input.mode
771
+ })
772
+ }
773
+ }
774
+ }));
775
+ const postConditions = {
776
+ signer: machineDid,
777
+ maxTokenOutflow: { [machine.tokenAddress]: totalPayoutAbt.toString(10) },
778
+ strictZeroUnlistedOutflow: true
779
+ };
780
+ return {
781
+ settlementId,
782
+ roundId,
783
+ machineDid,
784
+ mode: input.mode,
785
+ poolBalanceBeforeAbt,
786
+ totalPayoutAbt,
787
+ poolBalanceAfterAbt: machine.poolBalanceAbt,
788
+ winnerPayouts,
789
+ deterministicRollBps,
790
+ zeroPonziMintingVerified: true,
791
+ statements,
792
+ postConditions
793
+ };
794
+ }
795
+ getArcadeMachine(machineDid) {
796
+ const m = this.arcadeMachines.get(machineDid);
797
+ return m ? { ...m } : void 0;
798
+ }
799
+ registerStickerNft(input) {
800
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing registerStickerNft input");
801
+ const stickerDid = assertCleanDidOrId(input.stickerDid, "stickerDid");
802
+ const creatorDid = assertCleanDidOrId(input.creatorDid, "creatorDid");
803
+ const initialHolderDid = assertCleanDidOrId(input.initialHolderDid, "initialHolderDid");
804
+ const primaryPriceAbt = assertPositiveBigInt(input.primaryPriceAbt, "primaryPriceAbt");
805
+ const royaltyBps = assertValidBps(input.royaltyBps, "royaltyBps", MAX_STICKER_ROYALTY_BPS);
806
+ const payloadCommitmentDigest = assertBytes32Hex(input.payloadCommitmentDigest, "payloadCommitmentDigest");
807
+ const epochIndex = assertValidEpoch(input.epochIndex);
808
+ if (this.stickers.has(stickerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Sticker NFT ${stickerDid} already exists`);
809
+ let iboOrgDid;
810
+ let iboRoyaltyShareBps = 0;
811
+ if (input.iboOrgDid !== void 0) {
812
+ iboOrgDid = assertCleanDidOrId(input.iboOrgDid, "iboOrgDid");
813
+ if (!this.iboOrgs.has(iboOrgDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Referenced iboOrgDid ${iboOrgDid} does not exist`);
814
+ iboRoyaltyShareBps = assertValidBps(input.iboRoyaltyShareBps ?? 5e3, "iboRoyaltyShareBps", 1e4);
815
+ }
816
+ const record = {
817
+ stickerDid,
818
+ creatorDid,
819
+ holderDid: initialHolderDid,
820
+ primaryPriceAbt,
821
+ royaltyBps,
822
+ iboOrgDid,
823
+ iboRoyaltyShareBps,
824
+ payloadCommitmentDigest,
825
+ totalSecondarySalesCount: 0,
826
+ totalSecondaryVolumeAbt: 0n,
827
+ createdAtEpoch: epochIndex
828
+ };
829
+ this.stickers.set(stickerDid, record);
830
+ return { ...record };
831
+ }
832
+ makeStickerOffer(input) {
833
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing makeStickerOffer input");
834
+ const offerId = assertCleanDidOrId(input.offerId, "offerId");
835
+ const stickerDid = assertCleanDidOrId(input.stickerDid, "stickerDid");
836
+ const buyerDid = assertCleanDidOrId(input.buyerDid, "buyerDid");
837
+ const offerAmountAbt = assertPositiveBigInt(input.offerAmountAbt, "offerAmountAbt");
838
+ const epochIndex = assertValidEpoch(input.epochIndex);
839
+ const expiresAtEpoch = assertValidEpoch(input.expiresAtEpoch, "expiresAtEpoch");
840
+ if (this.stickerOffers.has(offerId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Sticker offer ${offerId} already exists`);
841
+ if (expiresAtEpoch <= epochIndex) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "expiresAtEpoch must be strictly after epochIndex");
842
+ const sticker = this.stickers.get(stickerDid);
843
+ if (!sticker) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown Sticker NFT: ${stickerDid}`);
844
+ if (sticker.holderDid === buyerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Current sticker holder cannot bid on their own sticker");
845
+ const offer = {
846
+ offerId,
847
+ stickerDid,
848
+ buyerDid,
849
+ offerAmountAbt,
850
+ createdAtEpoch: epochIndex,
851
+ expiresAtEpoch,
852
+ status: "OPEN_ESCROWED"
853
+ };
854
+ this.stickerOffers.set(offerId, offer);
855
+ return { ...offer };
856
+ }
857
+ cancelStickerOffer(offerId, callerDid) {
858
+ const cleanOfferId = assertCleanDidOrId(offerId, "offerId");
859
+ const cleanCaller = assertCleanDidOrId(callerDid, "callerDid");
860
+ const offer = this.stickerOffers.get(cleanOfferId);
861
+ if (!offer) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown Sticker offer: ${cleanOfferId}`);
862
+ if (offer.buyerDid !== cleanCaller) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only offer buyerDid can cancel their escrowed offer");
863
+ if (offer.status !== "OPEN_ESCROWED") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Sticker offer ${cleanOfferId} is not OPEN_ESCROWED`);
864
+ offer.status = "CANCELLED_REFUNDED";
865
+ return { ...offer };
866
+ }
867
+ acceptStickerOffer(input) {
868
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing acceptStickerOffer input");
869
+ const offerId = assertCleanDidOrId(input.offerId, "offerId");
870
+ const sellerDid = assertCleanDidOrId(input.sellerDid, "sellerDid");
871
+ const epochIndex = assertValidEpoch(input.epochIndex);
872
+ const offer = this.stickerOffers.get(offerId);
873
+ if (!offer) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown Sticker offer: ${offerId}`);
874
+ if (offer.status !== "OPEN_ESCROWED") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Sticker offer ${offerId} is no longer OPEN_ESCROWED`);
875
+ if (epochIndex > offer.expiresAtEpoch) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Sticker offer ${offerId} expired at epoch ${offer.expiresAtEpoch}`);
876
+ const sticker = this.stickers.get(offer.stickerDid);
877
+ if (!sticker) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown Sticker NFT: ${offer.stickerDid}`);
878
+ if (sticker.holderDid !== sellerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only current sticker holderDid can accept an offer");
879
+ if (offer.buyerDid === sellerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Cannot accept self-offer");
880
+ const grossOfferAbt = offer.offerAmountAbt;
881
+ const totalRoyaltyAbt = grossOfferAbt * BigInt(sticker.royaltyBps) / BPS_DENOMINATOR;
882
+ let iboDividendRoyaltyAbt = 0n;
883
+ if (sticker.iboOrgDid && totalRoyaltyAbt > 0n) {
884
+ const iboOrg = this.iboOrgs.get(sticker.iboOrgDid);
885
+ if (iboOrg && iboOrg.totalPartnerKeysSupply > 0n) {
886
+ iboDividendRoyaltyAbt = totalRoyaltyAbt * BigInt(sticker.iboRoyaltyShareBps) / BPS_DENOMINATOR;
887
+ if (iboDividendRoyaltyAbt > 0n) {
888
+ const totalScaled = iboDividendRoyaltyAbt * IBO_DIVIDEND_PRECISION + iboOrg.undistributedDividendRemainderScaled;
889
+ iboOrg.accDividendPerKeyScaled += totalScaled / iboOrg.totalPartnerKeysSupply;
890
+ iboOrg.undistributedDividendRemainderScaled = totalScaled % iboOrg.totalPartnerKeysSupply;
891
+ iboOrg.totalDividendsDistributedAbt += iboDividendRoyaltyAbt;
892
+ }
893
+ }
894
+ }
895
+ const creatorRoyaltyAbt = totalRoyaltyAbt - iboDividendRoyaltyAbt;
896
+ const sellerNetAbt = grossOfferAbt - creatorRoyaltyAbt - iboDividendRoyaltyAbt;
897
+ if (creatorRoyaltyAbt + iboDividendRoyaltyAbt + sellerNetAbt !== grossOfferAbt || sellerNetAbt < 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, "Sticker offer settlement failed conservation check");
898
+ offer.status = "ACCEPTED";
899
+ sticker.holderDid = offer.buyerDid;
900
+ sticker.totalSecondarySalesCount += 1;
901
+ sticker.totalSecondaryVolumeAbt += grossOfferAbt;
902
+ const statements = [{
903
+ type: "transfer_v3",
904
+ typeUrl: "fg:t:transfer_v3",
905
+ from: sellerDid,
906
+ itx: {
907
+ to: offer.buyerDid,
908
+ assets: [sticker.stickerDid]
909
+ }
910
+ }, {
911
+ type: "transfer_v3",
912
+ typeUrl: "fg:t:transfer_v3",
913
+ from: offer.buyerDid,
914
+ itx: {
915
+ to: sellerDid,
916
+ tokens: [{
917
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
918
+ value: sellerNetAbt.toString(10)
919
+ }]
920
+ }
921
+ }];
922
+ if (creatorRoyaltyAbt > 0n) statements.push({
923
+ type: "transfer_v3",
924
+ typeUrl: "fg:t:transfer_v3",
925
+ from: offer.buyerDid,
926
+ itx: {
927
+ to: sticker.creatorDid,
928
+ tokens: [{
929
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
930
+ value: creatorRoyaltyAbt.toString(10)
931
+ }]
932
+ }
933
+ });
934
+ if (sticker.iboOrgDid && iboDividendRoyaltyAbt > 0n) statements.push({
935
+ type: "transfer_v3",
936
+ typeUrl: "fg:t:transfer_v3",
937
+ from: offer.buyerDid,
938
+ itx: {
939
+ to: sticker.iboOrgDid,
940
+ tokens: [{
941
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
942
+ value: iboDividendRoyaltyAbt.toString(10)
943
+ }]
944
+ }
945
+ });
946
+ const postConditions = {
947
+ signer: offer.buyerDid,
948
+ maxTokenOutflow: { [DEFAULT_ABT_TOKEN_ADDRESS]: grossOfferAbt.toString(10) },
949
+ mustOwnAssetsAfter: { [offer.buyerDid]: [sticker.stickerDid] },
950
+ strictZeroUnlistedOutflow: true
951
+ };
952
+ return {
953
+ offerId,
954
+ stickerDid: sticker.stickerDid,
955
+ sellerDid,
956
+ buyerDid: offer.buyerDid,
957
+ grossOfferAbt,
958
+ creatorRoyaltyAbt,
959
+ iboDividendRoyaltyAbt,
960
+ sellerNetAbt,
961
+ conservationVerified: true,
962
+ statements,
963
+ postConditions
964
+ };
965
+ }
966
+ getStickerNft(stickerDid) {
967
+ const s = this.stickers.get(stickerDid);
968
+ return s ? { ...s } : void 0;
969
+ }
970
+ grantSpaceAssetDelegation(input) {
971
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing grantSpaceAssetDelegation input");
972
+ const grantId = assertCleanDidOrId(input.grantId, "grantId");
973
+ const assetDid = assertCleanDidOrId(input.assetDid, "assetDid");
974
+ const ownerDid = assertCleanDidOrId(input.ownerDid, "ownerDid");
975
+ const delegateRoomOwnerDid = assertCleanDidOrId(input.delegateRoomOwnerDid, "delegateRoomOwnerDid");
976
+ const epochIndex = assertValidEpoch(input.epochIndex);
977
+ const expiresAtEpoch = assertValidEpoch(input.expiresAtEpoch, "expiresAtEpoch");
978
+ if (this.spaceDelegations.has(grantId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Delegation grant ${grantId} already exists`);
979
+ if (expiresAtEpoch <= epochIndex) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "expiresAtEpoch must be strictly after epochIndex");
980
+ if (input.assetKind === "STICKER_NFT") {
981
+ const sticker = this.stickers.get(assetDid);
982
+ if (!sticker || sticker.holderDid !== ownerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Caller ${ownerDid} does not own Sticker ${assetDid}`);
983
+ } else if (input.assetKind === "ARCADE_MACHINE") {
984
+ const machine = this.arcadeMachines.get(assetDid);
985
+ if (!machine || machine.roomHostDid !== ownerDid && machine.gameCreatorDid !== ownerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Caller ${ownerDid} does not control ArcadeMachine ${assetDid}`);
986
+ } else throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Invalid assetKind: ${String(input.assetKind)}`);
987
+ const grant = {
988
+ grantId,
989
+ assetDid,
990
+ assetKind: input.assetKind,
991
+ ownerDid,
992
+ delegateRoomOwnerDid,
993
+ grantedAtEpoch: epochIndex,
994
+ expiresAtEpoch,
995
+ revoked: false
996
+ };
997
+ this.spaceDelegations.set(grantId, grant);
998
+ return { ...grant };
999
+ }
1000
+ hasActiveSpaceAssetAuthorization(roomOwnerDid, assetDid, assetKind, epochIndex) {
1001
+ if (assetKind === "STICKER_NFT") {
1002
+ const sticker = this.stickers.get(assetDid);
1003
+ if (!sticker) return false;
1004
+ if (sticker.holderDid === roomOwnerDid) return true;
1005
+ for (const grant of this.spaceDelegations.values()) if (!grant.revoked && grant.assetKind === "STICKER_NFT" && grant.assetDid === assetDid && grant.ownerDid === sticker.holderDid && grant.delegateRoomOwnerDid === roomOwnerDid && epochIndex >= grant.grantedAtEpoch && epochIndex <= grant.expiresAtEpoch) return true;
1006
+ return false;
1007
+ }
1008
+ const machine = this.arcadeMachines.get(assetDid);
1009
+ if (!machine) return false;
1010
+ if (machine.roomHostDid === roomOwnerDid || machine.gameCreatorDid === roomOwnerDid) return true;
1011
+ for (const grant of this.spaceDelegations.values()) if (!grant.revoked && grant.assetKind === "ARCADE_MACHINE" && grant.assetDid === assetDid && (grant.ownerDid === machine.roomHostDid || grant.ownerDid === machine.gameCreatorDid) && grant.delegateRoomOwnerDid === roomOwnerDid && epochIndex >= grant.grantedAtEpoch && epochIndex <= grant.expiresAtEpoch) return true;
1012
+ return false;
1013
+ }
1014
+ anchorSpaceManifest(input) {
1015
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing anchorSpaceManifest input");
1016
+ const spaceDid = assertCleanDidOrId(input.spaceDid, "spaceDid");
1017
+ const roomOwnerDid = assertCleanDidOrId(input.roomOwnerDid, "roomOwnerDid");
1018
+ const offChainLayoutCommitmentDigest = assertBytes32Hex(input.offChainLayoutCommitmentDigest, "offChainLayoutCommitmentDigest");
1019
+ const epochIndex = assertValidEpoch(input.epochIndex);
1020
+ if (!Array.isArray(input.displayedStickerDids) || input.displayedStickerDids.length > MAX_SPACE_DISPLAYED_STICKERS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `displayedStickerDids must be an array of at most ${MAX_SPACE_DISPLAYED_STICKERS} Sticker DIDs`);
1021
+ if (!Array.isArray(input.placedMachineDids) || input.placedMachineDids.length > MAX_SPACE_PLACED_MACHINES) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `placedMachineDids must be an array of at most ${MAX_SPACE_PLACED_MACHINES} ArcadeMachine DIDs`);
1022
+ const cleanStickers = input.displayedStickerDids.map((s, i) => assertCleanDidOrId(s, `displayedStickerDids[${i}]`));
1023
+ if (new Set(cleanStickers).size !== cleanStickers.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "displayedStickerDids cannot contain duplicate Sticker DIDs");
1024
+ const cleanMachines = input.placedMachineDids.map((m, i) => assertCleanDidOrId(m, `placedMachineDids[${i}]`));
1025
+ if (new Set(cleanMachines).size !== cleanMachines.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "placedMachineDids cannot contain duplicate ArcadeMachine DIDs");
1026
+ for (const stickerDid of cleanStickers) if (!this.hasActiveSpaceAssetAuthorization(roomOwnerDid, stickerDid, "STICKER_NFT", epochIndex)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `UNAUTHORIZED_SPACE_ASSET_MOUNT: Room owner ${roomOwnerDid} neither owns nor holds an active delegation for Sticker ${stickerDid}`);
1027
+ for (const machineDid of cleanMachines) if (!this.hasActiveSpaceAssetAuthorization(roomOwnerDid, machineDid, "ARCADE_MACHINE", epochIndex)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `UNAUTHORIZED_SPACE_ASSET_MOUNT: Room owner ${roomOwnerDid} neither controls nor holds an active delegation for ArcadeMachine ${machineDid}`);
1028
+ const existing = this.spaceManifests.get(spaceDid);
1029
+ if (existing && existing.roomOwnerDid !== roomOwnerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `Space ${spaceDid} is owned by ${existing.roomOwnerDid}`);
1030
+ const nextVersion = existing ? existing.version + 1 : 1;
1031
+ const record = {
1032
+ spaceDid,
1033
+ roomOwnerDid,
1034
+ version: nextVersion,
1035
+ displayedStickerDids: cleanStickers,
1036
+ placedMachineDids: cleanMachines,
1037
+ offChainLayoutCommitmentDigest,
1038
+ manifestRootDigest: computeSpaceManifestRootDigest({
1039
+ spaceDid,
1040
+ roomOwnerDid,
1041
+ version: nextVersion,
1042
+ displayedStickerDids: cleanStickers,
1043
+ placedMachineDids: cleanMachines,
1044
+ offChainLayoutCommitmentDigest,
1045
+ epochIndex
1046
+ }),
1047
+ anchoredAtEpoch: epochIndex,
1048
+ onChainPayloadFootprint: "PROOF_ONLY_32B"
1049
+ };
1050
+ this.spaceManifests.set(spaceDid, record);
1051
+ return {
1052
+ ...record,
1053
+ displayedStickerDids: [...record.displayedStickerDids],
1054
+ placedMachineDids: [...record.placedMachineDids]
1055
+ };
1056
+ }
1057
+ lockAttentionStamp(input) {
1058
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing lockAttentionStamp input");
1059
+ const stampId = assertCleanDidOrId(input.stampId, "stampId");
1060
+ const senderDid = assertCleanDidOrId(input.senderDid, "senderDid");
1061
+ const recipientDid = assertCleanDidOrId(input.recipientDid, "recipientDid");
1062
+ const spamSinkDid = assertCleanDidOrId(input.spamSinkDid, "spamSinkDid");
1063
+ const stampAmountAbt = assertPositiveBigInt(input.stampAmountAbt, "stampAmountAbt");
1064
+ const messageCommitmentDigest = assertBytes32Hex(input.messageCommitmentDigest, "messageCommitmentDigest");
1065
+ const epochIndex = assertValidEpoch(input.epochIndex);
1066
+ const expiresAtEpoch = assertValidEpoch(input.expiresAtEpoch, "expiresAtEpoch");
1067
+ if (this.attentionStamps.has(stampId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `AttentionStamp ${stampId} already exists`);
1068
+ if (senderDid === recipientDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "senderDid and recipientDid must be distinct");
1069
+ if (spamSinkDid === senderDid || spamSinkDid === recipientDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "spamSinkDid must be an independent public-goods/treasury sink distinct from senderDid and recipientDid");
1070
+ if (stampAmountAbt < MIN_ATTENTION_STAMP_ABT) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `stampAmountAbt (${stampAmountAbt}) is below MIN_ATTENTION_STAMP_ABT (${MIN_ATTENTION_STAMP_ABT})`);
1071
+ if (expiresAtEpoch <= epochIndex || expiresAtEpoch - epochIndex > MAX_ATTENTION_STAMP_TTL_EPOCHS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `expiresAtEpoch must be within 1..${MAX_ATTENTION_STAMP_TTL_EPOCHS} epochs after epochIndex`);
1072
+ let referrerDid;
1073
+ let referrerBps = 0;
1074
+ if (input.referrerDid !== void 0) {
1075
+ referrerDid = assertCleanDidOrId(input.referrerDid, "referrerDid");
1076
+ if (referrerDid === senderDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "referrerDid cannot be senderDid");
1077
+ referrerBps = assertValidBps(input.referrerBps ?? 1e3, "referrerBps", 5e3);
1078
+ }
1079
+ let protocolTreasuryDid;
1080
+ let protocolFeeBps = 0;
1081
+ if (input.protocolTreasuryDid !== void 0) {
1082
+ protocolTreasuryDid = assertCleanDidOrId(input.protocolTreasuryDid, "protocolTreasuryDid");
1083
+ protocolFeeBps = assertValidBps(input.protocolFeeBps ?? 500, "protocolFeeBps", 2e3);
1084
+ }
1085
+ const record = {
1086
+ stampId,
1087
+ senderDid,
1088
+ recipientDid,
1089
+ stampAmountAbt,
1090
+ messageCommitmentDigest,
1091
+ referrerDid,
1092
+ referrerBps,
1093
+ protocolTreasuryDid,
1094
+ protocolFeeBps,
1095
+ spamSinkDid,
1096
+ createdAtEpoch: epochIndex,
1097
+ expiresAtEpoch,
1098
+ status: "ESCROWED"
1099
+ };
1100
+ this.attentionStamps.set(stampId, record);
1101
+ return { ...record };
1102
+ }
1103
+ resolveAttentionStamp(input) {
1104
+ if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, "Missing resolveAttentionStamp input");
1105
+ const stampId = assertCleanDidOrId(input.stampId, "stampId");
1106
+ const callerDid = assertCleanDidOrId(input.callerDid, "callerDid");
1107
+ const replyOrSpamEvidenceDigest = assertBytes32Hex(input.replyOrSpamEvidenceDigest, "replyOrSpamEvidenceDigest");
1108
+ const epochIndex = assertValidEpoch(input.epochIndex);
1109
+ const stamp = this.attentionStamps.get(stampId);
1110
+ if (!stamp) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown AttentionStamp: ${stampId}`);
1111
+ if (stamp.status !== "ESCROWED") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `AttentionStamp ${stampId} is already resolved (${stamp.status})`);
1112
+ if (stamp.recipientDid !== callerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only recipientDid can resolve an AttentionStamp");
1113
+ if (epochIndex > stamp.expiresAtEpoch) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `AttentionStamp ${stampId} has already expired`);
1114
+ let senderRefundAbt = 0n;
1115
+ let recipientNetAbt = 0n;
1116
+ let referrerAbt = 0n;
1117
+ let protocolFeeAbt = 0n;
1118
+ let spamSinkAbt = 0n;
1119
+ const statements = [];
1120
+ if (input.mode === "REFUND_ON_READ_OR_REPLY") {
1121
+ senderRefundAbt = stamp.stampAmountAbt;
1122
+ stamp.status = "REFUNDED_ON_REPLY";
1123
+ statements.push({
1124
+ type: "transfer_v3",
1125
+ typeUrl: "fg:t:transfer_v3",
1126
+ from: stampId,
1127
+ itx: {
1128
+ to: stamp.senderDid,
1129
+ tokens: [{
1130
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
1131
+ value: senderRefundAbt.toString(10)
1132
+ }],
1133
+ data: {
1134
+ type: "json",
1135
+ value: JSON.stringify({
1136
+ primitive: "ATTENTION_STAMP_REFUND_ON_REPLY",
1137
+ stampId,
1138
+ evidence: replyOrSpamEvidenceDigest
1139
+ })
1140
+ }
1141
+ }
1142
+ });
1143
+ } else if (input.mode === "CLAIM_AS_PAID_CONSULTATION") {
1144
+ if (stamp.referrerDid && stamp.referrerBps > 0) referrerAbt = stamp.stampAmountAbt * BigInt(stamp.referrerBps) / BPS_DENOMINATOR;
1145
+ if (stamp.protocolTreasuryDid && stamp.protocolFeeBps > 0) protocolFeeAbt = stamp.stampAmountAbt * BigInt(stamp.protocolFeeBps) / BPS_DENOMINATOR;
1146
+ recipientNetAbt = stamp.stampAmountAbt - referrerAbt - protocolFeeAbt;
1147
+ stamp.status = "CLAIMED_CONSULTATION";
1148
+ statements.push({
1149
+ type: "transfer_v3",
1150
+ typeUrl: "fg:t:transfer_v3",
1151
+ from: stampId,
1152
+ itx: {
1153
+ to: stamp.recipientDid,
1154
+ tokens: [{
1155
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
1156
+ value: recipientNetAbt.toString(10)
1157
+ }]
1158
+ }
1159
+ });
1160
+ if (stamp.referrerDid && referrerAbt > 0n) statements.push({
1161
+ type: "transfer_v3",
1162
+ typeUrl: "fg:t:transfer_v3",
1163
+ from: stampId,
1164
+ itx: {
1165
+ to: stamp.referrerDid,
1166
+ tokens: [{
1167
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
1168
+ value: referrerAbt.toString(10)
1169
+ }]
1170
+ }
1171
+ });
1172
+ if (stamp.protocolTreasuryDid && protocolFeeAbt > 0n) statements.push({
1173
+ type: "transfer_v3",
1174
+ typeUrl: "fg:t:transfer_v3",
1175
+ from: stampId,
1176
+ itx: {
1177
+ to: stamp.protocolTreasuryDid,
1178
+ tokens: [{
1179
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
1180
+ value: protocolFeeAbt.toString(10)
1181
+ }]
1182
+ }
1183
+ });
1184
+ } else if (input.mode === "SLASH_ON_SPAM") {
1185
+ spamSinkAbt = stamp.stampAmountAbt;
1186
+ stamp.status = "SLASHED_TO_SPAM_SINK";
1187
+ statements.push({
1188
+ type: "transfer_v3",
1189
+ typeUrl: "fg:t:transfer_v3",
1190
+ from: stampId,
1191
+ itx: {
1192
+ to: stamp.spamSinkDid,
1193
+ tokens: [{
1194
+ address: DEFAULT_ABT_TOKEN_ADDRESS,
1195
+ value: spamSinkAbt.toString(10)
1196
+ }],
1197
+ data: {
1198
+ type: "json",
1199
+ value: JSON.stringify({
1200
+ primitive: "ATTENTION_STAMP_SLASH_SPAM",
1201
+ stampId,
1202
+ evidence: replyOrSpamEvidenceDigest
1203
+ })
1204
+ }
1205
+ }
1206
+ });
1207
+ } else throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unsupported resolution mode: ${String(input.mode)}`);
1208
+ if (senderRefundAbt + recipientNetAbt + referrerAbt + protocolFeeAbt + spamSinkAbt !== stamp.stampAmountAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ConservationViolation, "AttentionStamp resolution violated ABT conservation");
1209
+ const postConditions = {
1210
+ signer: stampId,
1211
+ maxTokenOutflow: { [DEFAULT_ABT_TOKEN_ADDRESS]: stamp.stampAmountAbt.toString(10) },
1212
+ strictZeroUnlistedOutflow: true
1213
+ };
1214
+ return {
1215
+ stampId,
1216
+ mode: input.mode,
1217
+ senderRefundAbt,
1218
+ recipientNetAbt,
1219
+ referrerAbt,
1220
+ protocolFeeAbt,
1221
+ spamSinkAbt,
1222
+ conservationVerified: true,
1223
+ statements,
1224
+ postConditions
1225
+ };
1226
+ }
1227
+ reclaimExpiredAttentionStamp(stampId, callerDid, epochIndex) {
1228
+ const cleanStampId = assertCleanDidOrId(stampId, "stampId");
1229
+ const cleanCaller = assertCleanDidOrId(callerDid, "callerDid");
1230
+ const epoch = assertValidEpoch(epochIndex);
1231
+ const stamp = this.attentionStamps.get(cleanStampId);
1232
+ if (!stamp) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSuperSuite, `Unknown AttentionStamp: ${cleanStampId}`);
1233
+ if (stamp.senderDid !== cleanCaller) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, "Only senderDid can reclaim an expired AttentionStamp");
1234
+ if (stamp.status !== "ESCROWED") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `AttentionStamp ${cleanStampId} is not ESCROWED`);
1235
+ if (epoch <= stamp.expiresAtEpoch) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSuperSuite, `AttentionStamp ${cleanStampId} has not expired yet (expiresAtEpoch: ${stamp.expiresAtEpoch})`);
1236
+ stamp.status = "EXPIRED_RECLAIMED";
1237
+ return { ...stamp };
1238
+ }
1239
+ };
1240
+
1241
+ //#endregion
1242
+ exports.BPS_DENOMINATOR = BPS_DENOMINATOR;
1243
+ exports.DEFAULT_ABT_TOKEN_ADDRESS = DEFAULT_ABT_TOKEN_ADDRESS;
1244
+ exports.IBO_DIVIDEND_PRECISION = IBO_DIVIDEND_PRECISION;
1245
+ exports.MAX_ARCADE_HOUSE_SPLIT_BPS = MAX_ARCADE_HOUSE_SPLIT_BPS;
1246
+ exports.MAX_ARCADE_WINNERS_PER_ROUND = MAX_ARCADE_WINNERS_PER_ROUND;
1247
+ exports.MAX_ATTENTION_STAMP_TTL_EPOCHS = MAX_ATTENTION_STAMP_TTL_EPOCHS;
1248
+ exports.MAX_IBO_TOTAL_FEE_SPLIT_BPS = MAX_IBO_TOTAL_FEE_SPLIT_BPS;
1249
+ exports.MAX_PREPAID_CARD_ALLOWED_PROVIDERS = MAX_PREPAID_CARD_ALLOWED_PROVIDERS;
1250
+ exports.MAX_SPACE_DISPLAYED_STICKERS = MAX_SPACE_DISPLAYED_STICKERS;
1251
+ exports.MAX_SPACE_PLACED_MACHINES = MAX_SPACE_PLACED_MACHINES;
1252
+ exports.MAX_STICKER_ROYALTY_BPS = MAX_STICKER_ROYALTY_BPS;
1253
+ exports.MIN_ARCADE_HOUSE_SPLIT_BPS = MIN_ARCADE_HOUSE_SPLIT_BPS;
1254
+ exports.MIN_ATTENTION_STAMP_ABT = MIN_ATTENTION_STAMP_ABT;
1255
+ exports.OcapSuperSuitesFoundationEngine = OcapSuperSuitesFoundationEngine;
1256
+ exports.computeArcadeCommitDigest = computeArcadeCommitDigest;
1257
+ exports.computeSpaceManifestRootDigest = computeSpaceManifestRootDigest;