@ocap/tx-pipeline 1.30.25 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,845 @@
1
+ import { DEFAULT_EPOCH_KARMA_ALLOWANCE, DEFAULT_KARMA_TOKEN_ADDRESS, DEFAULT_MAX_HISTORICAL_KARMA_CLAIM, DEFAULT_SPONSORED_BADGE_MINT_QUOTA, GIVE_TO_MINT_TOKEN_TYPE, MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT, MIN_GIVE_TO_MINT_DUST_FLOOR, MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE, OcapGiveToMintEngine, computeArcSpaceCheckpointRoot } from "./give-to-mint-karma.mjs";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
+ import { createHash } from "node:crypto";
4
+
5
+ //#region src/social-economy-factories.ts
6
+ const ErrorCode = {
7
+ InvalidFactory: "INVALID_SOCIAL_ECONOMY_FACTORY",
8
+ ForbiddenFactory: "FORBIDDEN_SOCIAL_ECONOMY_FACTORY"
9
+ };
10
+ const MAX_SOVEREIGN_NFT_FACTORY_SUPPLY = 1e6;
11
+ const MAX_ISSUER_STAGING_TTL_EPOCHS = 90;
12
+ const DEFAULT_ISSUER_STAGING_TTL_EPOCHS = 7;
13
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
14
+ const VALID_VISIBILITIES = new Set([
15
+ "public",
16
+ "authorized_only",
17
+ "private"
18
+ ]);
19
+ const VALID_NFT_CATEGORIES = new Set([
20
+ "PUBLIC_HONOR_BADGE",
21
+ "PRIVATE_ENCRYPTED_DELIVERABLE",
22
+ "MEMBERSHIP_PASS"
23
+ ]);
24
+ const VALID_POOL_KINDS = new Set([
25
+ "PERSONAL_BAT_TIPPING_POOL",
26
+ "CRYPTO_ADSENSE_SPONSOR_POOL",
27
+ "PHILANTHROPY_TAX_DONATION_POOL"
28
+ ]);
29
+ function assertCleanId(value, label) {
30
+ if (typeof value !== "string" || value.trim().length === 0) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: ${label} must be a non-empty string`);
31
+ const trimmed = value.trim();
32
+ if (trimmed !== value || /[\s/\\?#%]|::|->/.test(trimmed)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: ${label} contains invalid characters`);
33
+ return trimmed;
34
+ }
35
+ function assertValidEpoch(epochIndex) {
36
+ if (!Number.isSafeInteger(epochIndex) || epochIndex < 0) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: epochIndex must be a non-negative safe integer");
37
+ }
38
+ function deriveSovereignNftDid(factoryDid, recipientHolderDid, serialNumber, payloadCommitmentDigest) {
39
+ return `did:abt:snft:${createHash("sha256").update(`ocap:sovereign-nft:v1:${factoryDid}:${recipientHolderDid}:${serialNumber}:${payloadCommitmentDigest.toLowerCase()}`).digest("hex").slice(0, 40)}`;
40
+ }
41
+ /**
42
+ * Issue #1233 (Phase 1 — Foundation):
43
+ * Unified OCAP Social-Economy Factory Registry providing standardized, parameter-driven
44
+ * factories for:
45
+ * 1. `ReputationTokenFactory` (`type = "give_to_mint"`)
46
+ * 2. `SovereignNftFactory` (Holder-hosted `ArcSpace` payload, `public/authorized_only/private` consent gate,
47
+ * and 3-stage delivery custody handover `ISSUER_TEMP_STAGED -> HOLDER_SAVED_IN_ARCSPACE -> ISSUER_STORAGE_RELEASED`)
48
+ * 3. `KarmaSettlementPoolFactory` (Pro-rata KARMA-indexed epoch pool settlement)
49
+ */
50
+ var OcapSocialEconomyFactoryRegistry = class {
51
+ constructor(karmaEngine) {
52
+ this.tokenFactories = /* @__PURE__ */ new Map();
53
+ this.nftFactories = /* @__PURE__ */ new Map();
54
+ this.nftInstances = /* @__PURE__ */ new Map();
55
+ this.poolFactories = /* @__PURE__ */ new Map();
56
+ this.processedPilotRunIds = /* @__PURE__ */ new Set();
57
+ this.processedBlueprintIds = /* @__PURE__ */ new Set();
58
+ this.karmaEngine = karmaEngine ?? new OcapGiveToMintEngine();
59
+ const defaultTokenConfig = this.karmaEngine.getTokenConfig(DEFAULT_KARMA_TOKEN_ADDRESS);
60
+ this.tokenFactories.set("did:abt:factory:token:default-karma", {
61
+ factoryDid: "did:abt:factory:token:default-karma",
62
+ tokenConfig: defaultTokenConfig,
63
+ createdAtEpoch: 0
64
+ });
65
+ }
66
+ assertFactoryDidAvailable(factoryDid) {
67
+ if (this.tokenFactories.has(factoryDid) || this.nftFactories.has(factoryDid) || this.poolFactories.has(factoryDid)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: factoryDid ${factoryDid} already exists`);
68
+ }
69
+ assertVerifiedIdentity(did, roleLabel) {
70
+ const state = this.karmaEngine.getIdentityState(did);
71
+ if (!state || !state.verifiedHumanOrStaker || state.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: ${roleLabel} ${did} must be an active verified identity with positive trustMultiplierBps`);
72
+ }
73
+ /**
74
+ * 1. `ReputationTokenFactory`: Instantiates a new non-transferable `give_to_mint` reputation token
75
+ * via a standardized factory specification.
76
+ */
77
+ createReputationTokenFromFactory(input) {
78
+ const factoryDid = assertCleanId(input.factoryDid, "factoryDid");
79
+ assertValidEpoch(input.epochIndex);
80
+ this.assertFactoryDidAvailable(factoryDid);
81
+ const record = {
82
+ factoryDid,
83
+ tokenConfig: this.karmaEngine.createGiveToMintToken({
84
+ tokenAddress: input.tokenAddress,
85
+ symbol: input.symbol,
86
+ name: input.name,
87
+ issuerDid: input.issuerDid,
88
+ epochBaseAllowance: input.epochBaseAllowance ?? DEFAULT_EPOCH_KARMA_ALLOWANCE,
89
+ maxHistoricalClaimPerDid: input.maxHistoricalClaimPerDid ?? DEFAULT_MAX_HISTORICAL_KARMA_CLAIM,
90
+ transferrable: false,
91
+ creationFeePaid: input.creationFeePaid,
92
+ epochIndex: input.epochIndex
93
+ }),
94
+ createdAtEpoch: input.epochIndex
95
+ };
96
+ this.tokenFactories.set(factoryDid, record);
97
+ return {
98
+ ...record,
99
+ tokenConfig: { ...record.tokenConfig }
100
+ };
101
+ }
102
+ /**
103
+ * 2. `SovereignNftFactory`: Registers a standardized NFT factory template where payloads are
104
+ * hosted in the holder's own ArcSpace and visibility/custody follow the 2019 OCAP NFT sovereignty model.
105
+ */
106
+ registerSovereignNftFactory(spec) {
107
+ const factoryDid = assertCleanId(spec.factoryDid, "factoryDid");
108
+ const creatorDid = assertCleanId(spec.creatorDid, "creatorDid");
109
+ assertValidEpoch(spec.createdAtEpoch);
110
+ this.assertFactoryDidAvailable(factoryDid);
111
+ const seriesName = typeof spec.seriesName === "string" ? spec.seriesName.trim() : "";
112
+ if (seriesName.length === 0 || seriesName.length > 80 || /[\r\n\0]/.test(seriesName)) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: seriesName must be 1..80 single-line characters");
113
+ if (!VALID_NFT_CATEGORIES.has(spec.category)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: invalid NFT category ${String(spec.category)}`);
114
+ if (!VALID_VISIBILITIES.has(spec.defaultVisibility)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: invalid defaultVisibility ${String(spec.defaultVisibility)}`);
115
+ if (spec.category === "PRIVATE_ENCRYPTED_DELIVERABLE" && spec.defaultVisibility === "public") throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: PRIVATE_ENCRYPTED_DELIVERABLE factories cannot default to public visibility");
116
+ const transferrable = Boolean(spec.transferrable ?? false);
117
+ if ((spec.category === "PUBLIC_HONOR_BADGE" || spec.category === "PRIVATE_ENCRYPTED_DELIVERABLE") && transferrable) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: ${spec.category} NFTs must be non-transferable (transferrable: false)`);
118
+ if (!Number.isSafeInteger(spec.maxSupply) || spec.maxSupply <= 0 || spec.maxSupply > MAX_SOVEREIGN_NFT_FACTORY_SUPPLY) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: maxSupply must be between 1 and ${MAX_SOVEREIGN_NFT_FACTORY_SUPPLY}`);
119
+ const issuerStagingTtlEpochs = spec.issuerStagingTtlEpochs ?? DEFAULT_ISSUER_STAGING_TTL_EPOCHS;
120
+ if (!Number.isSafeInteger(issuerStagingTtlEpochs) || issuerStagingTtlEpochs <= 0 || issuerStagingTtlEpochs > MAX_ISSUER_STAGING_TTL_EPOCHS) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: issuerStagingTtlEpochs must be between 1 and ${MAX_ISSUER_STAGING_TTL_EPOCHS}`);
121
+ this.assertVerifiedIdentity(creatorDid, "creator");
122
+ const record = {
123
+ factoryDid,
124
+ creatorDid,
125
+ seriesName,
126
+ category: spec.category,
127
+ defaultVisibility: spec.defaultVisibility,
128
+ transferrable,
129
+ maxSupply: spec.maxSupply,
130
+ totalMinted: 0,
131
+ issuerStagingTtlEpochs,
132
+ createdAtEpoch: spec.createdAtEpoch
133
+ };
134
+ this.nftFactories.set(factoryDid, record);
135
+ return { ...record };
136
+ }
137
+ /**
138
+ * Mints a new Sovereign NFT from a registered `SovereignNftFactory`.
139
+ * On-chain state records only the authorization header and 32B `payloadCommitmentDigest`,
140
+ * while the binary payload is staged for the holder's `ArcSpace`.
141
+ */
142
+ mintSovereignNft(input) {
143
+ const factoryDid = assertCleanId(input.factoryDid, "factoryDid");
144
+ const callerDid = assertCleanId(input.callerDid, "callerDid");
145
+ const recipientHolderDid = assertCleanId(input.recipientHolderDid, "recipientHolderDid");
146
+ assertValidEpoch(input.epochIndex);
147
+ const factory = this.nftFactories.get(factoryDid);
148
+ if (!factory) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: NFT factory ${factoryDid} not found`);
149
+ if (callerDid !== factory.creatorDid) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: only factory creator (${factory.creatorDid}) can mint from ${factoryDid}`);
150
+ this.assertVerifiedIdentity(factory.creatorDid, "creator");
151
+ if (input.epochIndex < factory.createdAtEpoch) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: mint epochIndex (${input.epochIndex}) cannot precede factory createdAtEpoch (${factory.createdAtEpoch})`);
152
+ if (factory.totalMinted >= factory.maxSupply) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: factory ${factoryDid} has reached maxSupply (${factory.maxSupply})`);
153
+ if (!this.karmaEngine.getIdentityState(recipientHolderDid)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: recipientHolderDid ${recipientHolderDid} is not registered`);
154
+ if (typeof input.payloadCommitmentDigest !== "string" || !BYTES32_HEX_REGEX.test(input.payloadCommitmentDigest)) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: payloadCommitmentDigest must be a canonical 32-byte 0x-prefixed hex digest");
155
+ const visibility = input.initialVisibility ?? factory.defaultVisibility;
156
+ if (!VALID_VISIBILITIES.has(visibility)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: invalid initialVisibility ${String(visibility)}`);
157
+ if (factory.category === "PRIVATE_ENCRYPTED_DELIVERABLE" && visibility === "public") throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: PRIVATE_ENCRYPTED_DELIVERABLE cannot be minted with public visibility");
158
+ const normalizedViewers = [];
159
+ if (input.authorizedViewerDids !== void 0) {
160
+ if (!Array.isArray(input.authorizedViewerDids) || input.authorizedViewerDids.length > 100) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: authorizedViewerDids must be an array of at most 100 DIDs");
161
+ const seen = /* @__PURE__ */ new Set();
162
+ for (const v of input.authorizedViewerDids) {
163
+ const cleanViewer = assertCleanId(v, "authorizedViewerDid");
164
+ if (!seen.has(cleanViewer)) {
165
+ seen.add(cleanViewer);
166
+ normalizedViewers.push(cleanViewer);
167
+ }
168
+ }
169
+ }
170
+ factory.totalMinted += 1;
171
+ const serialNumber = factory.totalMinted;
172
+ const nftDid = deriveSovereignNftDid(factoryDid, recipientHolderDid, serialNumber, input.payloadCommitmentDigest);
173
+ const instance = {
174
+ nftDid,
175
+ factoryDid,
176
+ category: factory.category,
177
+ serialNumber,
178
+ issuerDid: factory.creatorDid,
179
+ holderDid: recipientHolderDid,
180
+ transferrable: factory.transferrable,
181
+ mintedAtEpoch: input.epochIndex,
182
+ stagingExpiresAtEpoch: input.epochIndex + factory.issuerStagingTtlEpochs,
183
+ payloadCommitmentDigest: input.payloadCommitmentDigest.toLowerCase(),
184
+ holderArcSpaceUri: `arcspace://${recipientHolderDid}/nfts/${nftDid}`,
185
+ issuerStagingUri: `arcspace://${factory.creatorDid}/staging/${nftDid}`,
186
+ payloadVisibility: visibility,
187
+ authorizedViewerDids: visibility === "authorized_only" ? normalizedViewers : [],
188
+ payloadCustodyState: "ISSUER_TEMP_STAGED"
189
+ };
190
+ this.nftInstances.set(nftDid, instance);
191
+ return {
192
+ ...instance,
193
+ authorizedViewerDids: [...instance.authorizedViewerDids]
194
+ };
195
+ }
196
+ /**
197
+ * Holder-Sovereign Visibility Control: ONLY `holderDid` can decide whether outsiders can view
198
+ * the NFT payload hosted in `holderArcSpaceUri`.
199
+ */
200
+ configureSovereignNftVisibility(params) {
201
+ const nftDid = assertCleanId(params.nftDid, "nftDid");
202
+ const callerDid = assertCleanId(params.callerDid, "callerDid");
203
+ if (!VALID_VISIBILITIES.has(params.visibility)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: invalid visibility ${String(params.visibility)}`);
204
+ const nft = this.nftInstances.get(nftDid);
205
+ if (!nft) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: NFT ${nftDid} not found`);
206
+ if (nft.holderDid !== callerDid) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: only the NFT holder (${nft.holderDid}) can configure visibility for ${nftDid}`);
207
+ if (nft.category === "PRIVATE_ENCRYPTED_DELIVERABLE" && params.visibility === "public") throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: PRIVATE_ENCRYPTED_DELIVERABLE NFTs cannot be switched to public visibility");
208
+ const normalizedViewers = [];
209
+ if (params.authorizedViewerDids !== void 0) {
210
+ if (!Array.isArray(params.authorizedViewerDids) || params.authorizedViewerDids.length > 100) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: authorizedViewerDids must be an array of at most 100 DIDs");
211
+ const seen = /* @__PURE__ */ new Set();
212
+ for (const v of params.authorizedViewerDids) {
213
+ const cleanViewer = assertCleanId(v, "authorizedViewerDid");
214
+ if (!seen.has(cleanViewer)) {
215
+ seen.add(cleanViewer);
216
+ normalizedViewers.push(cleanViewer);
217
+ }
218
+ }
219
+ }
220
+ nft.payloadVisibility = params.visibility;
221
+ nft.authorizedViewerDids = params.visibility === "authorized_only" ? normalizedViewers : [];
222
+ return {
223
+ ...nft,
224
+ authorizedViewerDids: [...nft.authorizedViewerDids]
225
+ };
226
+ }
227
+ /**
228
+ * Evaluates whether `viewerDid` can access the NFT payload.
229
+ * When denied (`private` or unwhitelisted `authorized_only`), both `holderArcSpaceUri` and
230
+ * `issuerStagingUri` are withheld so outsiders cannot see the NFT content.
231
+ */
232
+ resolveSovereignNftPayloadAccess(params) {
233
+ const nftDid = assertCleanId(params.nftDid, "nftDid");
234
+ const viewerDid = assertCleanId(params.viewerDid, "viewerDid");
235
+ const nft = this.nftInstances.get(nftDid);
236
+ if (!nft) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: NFT ${nftDid} not found`);
237
+ if (viewerDid === nft.holderDid) return {
238
+ nftDid,
239
+ factoryDid: nft.factoryDid,
240
+ holderDid: nft.holderDid,
241
+ viewerDid,
242
+ visibility: nft.payloadVisibility,
243
+ custodyState: nft.payloadCustodyState,
244
+ accessible: true,
245
+ reason: "ALLOWED_HOLDER",
246
+ holderArcSpaceUri: nft.holderArcSpaceUri,
247
+ issuerStagingUri: nft.issuerStagingUri,
248
+ payloadCommitmentDigest: nft.payloadCommitmentDigest
249
+ };
250
+ if (nft.payloadVisibility === "public") return {
251
+ nftDid,
252
+ factoryDid: nft.factoryDid,
253
+ holderDid: nft.holderDid,
254
+ viewerDid,
255
+ visibility: nft.payloadVisibility,
256
+ custodyState: nft.payloadCustodyState,
257
+ accessible: true,
258
+ reason: "ALLOWED_PUBLIC",
259
+ holderArcSpaceUri: nft.holderArcSpaceUri,
260
+ payloadCommitmentDigest: nft.payloadCommitmentDigest
261
+ };
262
+ if (nft.payloadVisibility === "authorized_only") {
263
+ if (nft.authorizedViewerDids.includes(viewerDid)) return {
264
+ nftDid,
265
+ factoryDid: nft.factoryDid,
266
+ holderDid: nft.holderDid,
267
+ viewerDid,
268
+ visibility: nft.payloadVisibility,
269
+ custodyState: nft.payloadCustodyState,
270
+ accessible: true,
271
+ reason: "ALLOWED_AUTHORIZED_VIEWER",
272
+ holderArcSpaceUri: nft.holderArcSpaceUri,
273
+ payloadCommitmentDigest: nft.payloadCommitmentDigest
274
+ };
275
+ return {
276
+ nftDid,
277
+ factoryDid: nft.factoryDid,
278
+ holderDid: nft.holderDid,
279
+ viewerDid,
280
+ visibility: nft.payloadVisibility,
281
+ custodyState: nft.payloadCustodyState,
282
+ accessible: false,
283
+ reason: "DENIED_UNAUTHORIZED",
284
+ payloadCommitmentDigest: nft.payloadCommitmentDigest
285
+ };
286
+ }
287
+ return {
288
+ nftDid,
289
+ factoryDid: nft.factoryDid,
290
+ holderDid: nft.holderDid,
291
+ viewerDid,
292
+ visibility: nft.payloadVisibility,
293
+ custodyState: nft.payloadCustodyState,
294
+ accessible: false,
295
+ reason: "DENIED_PRIVATE",
296
+ payloadCommitmentDigest: nft.payloadCommitmentDigest
297
+ };
298
+ }
299
+ /**
300
+ * Stage 2 & 3 Custody Handover:
301
+ * Holder verifies `verifiedPayloadDigest === payloadCommitmentDigest`, saves the binary into their
302
+ * own `ArcSpace`, and acknowledges custody. When `releaseIssuerStorageImmediately !== false`,
303
+ * transitions directly to `ISSUER_STORAGE_RELEASED` and clears `issuerStagingUri`.
304
+ */
305
+ acknowledgeSovereignNftCustody(params) {
306
+ const nftDid = assertCleanId(params.nftDid, "nftDid");
307
+ const holderDid = assertCleanId(params.holderDid, "holderDid");
308
+ if (typeof params.verifiedPayloadDigest !== "string" || !BYTES32_HEX_REGEX.test(params.verifiedPayloadDigest)) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: verifiedPayloadDigest must be a canonical 32-byte 0x-prefixed hex digest");
309
+ const nft = this.nftInstances.get(nftDid);
310
+ if (!nft) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: NFT ${nftDid} not found`);
311
+ if (nft.holderDid !== holderDid) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: only the NFT holder (${nft.holderDid}) can acknowledge custody for ${nftDid}`);
312
+ if (nft.payloadCommitmentDigest.toLowerCase() !== params.verifiedPayloadDigest.toLowerCase()) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: verifiedPayloadDigest mismatch against on-chain commitment for ${nftDid}`);
313
+ if (nft.payloadCustodyState === "ISSUER_STORAGE_RELEASED" && params.releaseIssuerStorageImmediately === false) throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: cannot regress payloadCustodyState from ISSUER_STORAGE_RELEASED to HOLDER_SAVED_IN_ARCSPACE");
314
+ if (params.releaseIssuerStorageImmediately === false) nft.payloadCustodyState = "HOLDER_SAVED_IN_ARCSPACE";
315
+ else {
316
+ nft.payloadCustodyState = "ISSUER_STORAGE_RELEASED";
317
+ nft.issuerStagingUri = void 0;
318
+ }
319
+ return {
320
+ ...nft,
321
+ authorizedViewerDids: [...nft.authorizedViewerDids]
322
+ };
323
+ }
324
+ /**
325
+ * Releases the creator/issuer's temporary staging buffer (`issuerStagingUri = undefined`,
326
+ * `payloadCustodyState = 'ISSUER_STORAGE_RELEASED'`) once EITHER:
327
+ * - the holder has already saved the binary (`HOLDER_SAVED_IN_ARCSPACE` or `ISSUER_STORAGE_RELEASED`), OR
328
+ * - the temporary staging window has expired (`currentEpoch >= stagingExpiresAtEpoch`).
329
+ * Rejects premature deletion while `currentEpoch < stagingExpiresAtEpoch` and the holder has not yet saved it.
330
+ */
331
+ purgeIssuerStagedNftPayload(params) {
332
+ const nftDid = assertCleanId(params.nftDid, "nftDid");
333
+ const callerDid = assertCleanId(params.callerDid, "callerDid");
334
+ assertValidEpoch(params.currentEpoch);
335
+ const nft = this.nftInstances.get(nftDid);
336
+ if (!nft) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: NFT ${nftDid} not found`);
337
+ if (params.currentEpoch < nft.mintedAtEpoch) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: currentEpoch (${params.currentEpoch}) cannot precede NFT mintedAtEpoch (${nft.mintedAtEpoch})`);
338
+ if (callerDid !== nft.issuerDid && callerDid !== nft.holderDid) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: only issuer (${nft.issuerDid}) or holder (${nft.holderDid}) can purge staged payload`);
339
+ if (nft.payloadCustodyState === "ISSUER_TEMP_STAGED" && params.currentEpoch < nft.stagingExpiresAtEpoch) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: caller cannot purge staged binary before stagingExpiresAtEpoch (${nft.stagingExpiresAtEpoch}) until holder acknowledges custody with verified digest`);
340
+ nft.payloadCustodyState = "ISSUER_STORAGE_RELEASED";
341
+ nft.issuerStagingUri = void 0;
342
+ return {
343
+ ...nft,
344
+ authorizedViewerDids: [...nft.authorizedViewerDids]
345
+ };
346
+ }
347
+ /**
348
+ * 3. `KarmaSettlementPoolFactory`: Registers a reusable epoch pool settlement factory
349
+ * (e.g., $100/mo BAT Tipping Pool, $1,000/mo Crypto AdSense Pool, $200k Philanthropy Pool).
350
+ */
351
+ registerKarmaSettlementPoolFactory(spec) {
352
+ const factoryDid = assertCleanId(spec.factoryDid, "factoryDid");
353
+ const sponsorDid = assertCleanId(spec.sponsorDid, "sponsorDid");
354
+ const tokenAddress = spec.tokenAddress ? assertCleanId(spec.tokenAddress, "tokenAddress") : DEFAULT_KARMA_TOKEN_ADDRESS;
355
+ assertValidEpoch(spec.createdAtEpoch);
356
+ this.assertFactoryDidAvailable(factoryDid);
357
+ if (!VALID_POOL_KINDS.has(spec.poolKind)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: invalid poolKind ${String(spec.poolKind)}`);
358
+ if (!this.karmaEngine.getTokenConfig(tokenAddress)) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: target token ${tokenAddress} is not registered`);
359
+ this.assertVerifiedIdentity(sponsorDid, "sponsor");
360
+ const minRecipientKarmaWeight = spec.minRecipientKarmaWeight ?? 1n;
361
+ if (typeof minRecipientKarmaWeight !== "bigint" || minRecipientKarmaWeight <= 0n) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: minRecipientKarmaWeight must be a positive bigint");
362
+ const record = {
363
+ factoryDid,
364
+ sponsorDid,
365
+ poolKind: spec.poolKind,
366
+ tokenAddress,
367
+ minRecipientKarmaWeight,
368
+ totalPoolsSettled: 0,
369
+ cumulativeSettledAmount: 0n,
370
+ createdAtEpoch: spec.createdAtEpoch
371
+ };
372
+ this.poolFactories.set(factoryDid, record);
373
+ return { ...record };
374
+ }
375
+ /**
376
+ * Executes an epoch pool settlement using a registered `KarmaSettlementPoolFactory`.
377
+ */
378
+ executeFactoryPoolSettlement(params) {
379
+ const factoryDid = assertCleanId(params.factoryDid, "factoryDid");
380
+ const callerDid = assertCleanId(params.callerDid, "callerDid");
381
+ assertValidEpoch(params.epochIndex);
382
+ const poolFactory = this.poolFactories.get(factoryDid);
383
+ if (!poolFactory) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: pool factory ${factoryDid} not found`);
384
+ if (callerDid !== poolFactory.sponsorDid) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: only sponsor (${poolFactory.sponsorDid}) can settle pool factory ${factoryDid}`);
385
+ this.assertVerifiedIdentity(poolFactory.sponsorDid, "sponsor");
386
+ if (params.epochIndex < poolFactory.createdAtEpoch) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: settlement epochIndex (${params.epochIndex}) cannot precede pool factory createdAtEpoch (${poolFactory.createdAtEpoch})`);
387
+ if (!Array.isArray(params.recipientWeights) || params.recipientWeights.length === 0) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: recipientWeights must be a non-empty array");
388
+ for (const entry of params.recipientWeights) {
389
+ if (!entry || typeof entry.karmaWeight !== "bigint" || entry.karmaWeight <= 0n) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: karmaWeight must be a positive bigint");
390
+ assertCleanId(entry.recipientDid, "recipientDid");
391
+ if (entry.karmaWeight < poolFactory.minRecipientKarmaWeight) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: recipient ${entry.recipientDid} karmaWeight (${entry.karmaWeight}) is below factory minimum (${poolFactory.minRecipientKarmaWeight})`);
392
+ }
393
+ const settlement = this.karmaEngine.settleKarmaIndexedPool({
394
+ poolId: params.poolId,
395
+ poolKind: poolFactory.poolKind,
396
+ sponsorDid: poolFactory.sponsorDid,
397
+ tokenAddress: poolFactory.tokenAddress,
398
+ epochIndex: params.epochIndex,
399
+ totalPoolAmount: params.totalPoolAmount,
400
+ recipientWeights: params.recipientWeights
401
+ });
402
+ poolFactory.totalPoolsSettled += 1;
403
+ poolFactory.cumulativeSettledAmount += params.totalPoolAmount;
404
+ return settlement;
405
+ }
406
+ getTokenFactory(factoryDid) {
407
+ const f = this.tokenFactories.get(factoryDid);
408
+ return f ? {
409
+ ...f,
410
+ tokenConfig: { ...f.tokenConfig }
411
+ } : void 0;
412
+ }
413
+ getSovereignNftFactory(factoryDid) {
414
+ const f = this.nftFactories.get(factoryDid);
415
+ return f ? { ...f } : void 0;
416
+ }
417
+ getSovereignNftInstance(nftDid) {
418
+ const n = this.nftInstances.get(nftDid);
419
+ return n ? {
420
+ ...n,
421
+ authorizedViewerDids: [...n.authorizedViewerDids]
422
+ } : void 0;
423
+ }
424
+ getPoolFactory(factoryDid) {
425
+ const p = this.poolFactories.get(factoryDid);
426
+ return p ? { ...p } : void 0;
427
+ }
428
+ /**
429
+ * Issue #1234 — Pilot App A:
430
+ * Executes the end-to-end Public Community Content Appreciation & Citation Split workflow:
431
+ * 1. Optionally processes the author's retroactive historical contribution claim (`claimHistoricalKarma`).
432
+ * 2. Grants the author protocol-sponsored free badge minting quota (`SponsoredMintQuota`, default 100).
433
+ * 3. Registers the content object and its upstream `citations` graph (`photo`, `music`, `skill`, `blocklet`, etc.).
434
+ * 4. Commits reader `Give-to-Mint` vouchers via `ArcSpace + Checkpoint`, minting `KARMA` FT across the
435
+ * primary author and cited contributors, companion Medal NFTs, and numbered Creator Thank-You Badges.
436
+ */
437
+ runPilotPublicContentAppreciationWorkflow(input) {
438
+ const pilotRunId = assertCleanId(input.pilotRunId, "pilotRunId");
439
+ const authorDid = assertCleanId(input.authorDid, "authorDid");
440
+ const objectDid = assertCleanId(input.objectDid, "objectDid");
441
+ assertValidEpoch(input.epochIndex);
442
+ if (this.processedPilotRunIds.has(pilotRunId)) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: duplicate pilotRunId ${pilotRunId} replay is forbidden`);
443
+ const tokenFactoryDid = input.tokenFactoryDid ? assertCleanId(input.tokenFactoryDid, "tokenFactoryDid") : "did:abt:factory:token:default-karma";
444
+ const tokenFactory = this.tokenFactories.get(tokenFactoryDid);
445
+ if (!tokenFactory) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: tokenFactory ${tokenFactoryDid} not found`);
446
+ const tokenAddress = tokenFactory.tokenConfig.tokenAddress;
447
+ if (!Array.isArray(input.citations)) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: citations must be an array");
448
+ const quotaToGrant = input.sponsoredBadgeQuotaGrant ?? DEFAULT_SPONSORED_BADGE_MINT_QUOTA;
449
+ if (!Number.isSafeInteger(quotaToGrant) || quotaToGrant < 0 || quotaToGrant > MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT) throw new CustomError(ErrorCode.InvalidFactory, `SocialEconomyFactory: sponsoredBadgeQuotaGrant must be an integer in 0..${MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT}`);
450
+ if (!Array.isArray(input.vouchers) || input.vouchers.length === 0) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: pilot vouchers must be a non-empty array");
451
+ this.assertVerifiedIdentity(authorDid, "author");
452
+ for (const c of input.citations) {
453
+ if (!c || typeof c !== "object") throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: citation entry must be an object");
454
+ this.assertVerifiedIdentity(assertCleanId(c.contributorDid, "citation.contributorDid"), "cited contributor");
455
+ }
456
+ const seenVoucherIds = /* @__PURE__ */ new Set();
457
+ const checkpointVouchers = [];
458
+ for (const v of input.vouchers) {
459
+ if (!v || typeof v !== "object") throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: voucher entry must be an object");
460
+ const voucherId = assertCleanId(v.voucherId, "voucherId");
461
+ if (seenVoucherIds.has(voucherId)) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: duplicate voucherId ${voucherId} in pilot batch`);
462
+ seenVoucherIds.add(voucherId);
463
+ const readerDid = assertCleanId(v.readerDid, "readerDid");
464
+ if (readerDid === authorDid) throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: readerDid cannot self-give to authorDid in pilot batch");
465
+ this.assertVerifiedIdentity(readerDid, "reader");
466
+ if (typeof v.allowanceAmount !== "bigint" || v.allowanceAmount < MIN_GIVE_TO_MINT_DUST_FLOOR) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: voucher allowanceAmount must be >= ${MIN_GIVE_TO_MINT_DUST_FLOOR}`);
467
+ checkpointVouchers.push({
468
+ voucherId,
469
+ senderDid: readerDid,
470
+ objectDid,
471
+ allowanceAmount: v.allowanceAmount,
472
+ medalKind: v.medalKind
473
+ });
474
+ }
475
+ let historicalClaimResult;
476
+ if (input.historicalClaim) historicalClaimResult = this.karmaEngine.claimHistoricalKarma({
477
+ ...input.historicalClaim,
478
+ claimantDid: authorDid,
479
+ tokenAddress,
480
+ epochIndex: input.epochIndex
481
+ });
482
+ if (quotaToGrant > 0) this.karmaEngine.grantSponsoredBadgeMintQuota(authorDid, quotaToGrant);
483
+ this.karmaEngine.registerCreationObject({
484
+ objectDid,
485
+ authorDid,
486
+ kind: input.objectKind,
487
+ citations: input.citations,
488
+ enableThankYouBadge: true
489
+ });
490
+ const expectedCheckpointRoot = computeArcSpaceCheckpointRoot(tokenAddress, input.epochIndex, checkpointVouchers);
491
+ const checkpointResult = this.karmaEngine.commitArcSpaceKarmaCheckpoint({
492
+ checkpointId: `chk:${pilotRunId}`,
493
+ tokenAddress,
494
+ epochIndex: input.epochIndex,
495
+ expectedCheckpointRoot,
496
+ vouchers: checkpointVouchers
497
+ });
498
+ this.processedPilotRunIds.add(pilotRunId);
499
+ const authorAcct = this.karmaEngine.getPerTokenAccountState(authorDid, tokenAddress);
500
+ const authorEarnedKarmaInEpoch = authorAcct && authorAcct.lastEarnedEpoch === input.epochIndex ? authorAcct.earnedKarmaInEpoch : 0n;
501
+ const citationEarnedKarmaByContributor = {};
502
+ for (const c of input.citations) {
503
+ const citedAcct = this.karmaEngine.getPerTokenAccountState(c.contributorDid, tokenAddress);
504
+ citationEarnedKarmaByContributor[c.contributorDid] = citedAcct && citedAcct.lastEarnedEpoch === input.epochIndex ? citedAcct.earnedKarmaInEpoch : 0n;
505
+ }
506
+ const companionMedalsIssued = this.karmaEngine.getCompanionMedalsForObject(objectDid).filter((m) => m.epochIndex === input.epochIndex && m.tokenAddress === tokenAddress);
507
+ const seenReaders = /* @__PURE__ */ new Set();
508
+ const thankYouBadgesIssued = [];
509
+ for (const v of checkpointVouchers) if (!seenReaders.has(v.senderDid)) {
510
+ seenReaders.add(v.senderDid);
511
+ const badges = this.karmaEngine.getThankYouBadgesForRecipient(v.senderDid).filter((b) => b.sourceObjectDid === objectDid && b.epochIndex === input.epochIndex && b.tokenAddress === tokenAddress);
512
+ thankYouBadgesIssued.push(...badges);
513
+ }
514
+ const remainingSponsoredBadgeQuota = this.karmaEngine.getIdentityState(authorDid)?.sponsoredBadgeMintQuota ?? 0;
515
+ return {
516
+ pilotRunId,
517
+ tokenAddress,
518
+ objectDid,
519
+ historicalClaimResult,
520
+ checkpointResult,
521
+ authorEarnedKarmaInEpoch,
522
+ citationEarnedKarmaByContributor,
523
+ companionMedalsIssued,
524
+ thankYouBadgesIssued,
525
+ remainingSponsoredBadgeQuota
526
+ };
527
+ }
528
+ /**
529
+ * Issue #1234 — Pilot App B:
530
+ * Executes the end-to-end Private Circle & Encrypted Media Pack Delivery workflow
531
+ * (`OnlyFans / 知识星球 Sovereign NFT Mode`):
532
+ * 1. Registers (or safely reuses for subsequent subscribers of the same creator series) a
533
+ * `PRIVATE_ENCRYPTED_DELIVERABLE` `SovereignNftFactory` (`defaultVisibility: 'private'`).
534
+ * 2. Mints an encrypted deliverable NFT (`payloadCommitmentDigest`) to the subscriber's DID.
535
+ * 3. Verifies that an external outsider (`outsiderProbeDid`) is strictly blocked (`DENIED_PRIVATE`)
536
+ * and cannot see `holderArcSpaceUri` or `issuerStagingUri`.
537
+ * 4. Subscriber verifies the 32B digest, saves the binary into their own `ArcSpace`, and calls
538
+ * `acknowledgeSovereignNftCustody`, immediately releasing the creator's staging storage obligation
539
+ * (`payloadCustodyState === 'ISSUER_STORAGE_RELEASED'`, `issuerStagingUri === undefined`).
540
+ */
541
+ runPilotPrivateCircleDeliveryWorkflow(input) {
542
+ const pilotRunId = assertCleanId(input.pilotRunId, "pilotRunId");
543
+ const nftFactoryDid = assertCleanId(input.nftFactoryDid, "nftFactoryDid");
544
+ const creatorDid = assertCleanId(input.creatorDid, "creatorDid");
545
+ const subscriberDid = assertCleanId(input.subscriberDid, "subscriberDid");
546
+ const outsiderProbeDid = assertCleanId(input.outsiderProbeDid, "outsiderProbeDid");
547
+ assertValidEpoch(input.epochIndex);
548
+ if (this.processedPilotRunIds.has(pilotRunId)) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: duplicate pilotRunId ${pilotRunId} replay is forbidden`);
549
+ if (subscriberDid === creatorDid) throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: subscriberDid cannot be the same as creatorDid in Private Circle pilot");
550
+ if (outsiderProbeDid === subscriberDid || outsiderProbeDid === creatorDid) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: outsiderProbeDid must be distinct from both subscriberDid and creatorDid");
551
+ if (typeof input.payloadCommitmentDigest !== "string" || !BYTES32_HEX_REGEX.test(input.payloadCommitmentDigest)) throw new CustomError(ErrorCode.InvalidFactory, "SocialEconomyFactory: payloadCommitmentDigest must be a canonical 32-byte 0x-prefixed hex digest");
552
+ this.assertVerifiedIdentity(creatorDid, "creator");
553
+ this.assertVerifiedIdentity(subscriberDid, "subscriber");
554
+ const existingNftFactory = this.nftFactories.get(nftFactoryDid);
555
+ let nftFactory;
556
+ if (existingNftFactory) {
557
+ if (existingNftFactory.creatorDid !== creatorDid || existingNftFactory.category !== "PRIVATE_ENCRYPTED_DELIVERABLE" || existingNftFactory.defaultVisibility !== "private" || existingNftFactory.transferrable) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: existing nftFactory ${nftFactoryDid} cannot be reused by ${creatorDid} for Private Circle pilot`);
558
+ nftFactory = existingNftFactory;
559
+ } else nftFactory = this.registerSovereignNftFactory({
560
+ factoryDid: nftFactoryDid,
561
+ creatorDid,
562
+ seriesName: input.seriesName,
563
+ category: "PRIVATE_ENCRYPTED_DELIVERABLE",
564
+ defaultVisibility: "private",
565
+ transferrable: false,
566
+ maxSupply: 1e4,
567
+ issuerStagingTtlEpochs: input.issuerStagingTtlEpochs ?? DEFAULT_ISSUER_STAGING_TTL_EPOCHS,
568
+ createdAtEpoch: input.epochIndex
569
+ });
570
+ const mintedNftBeforeSave = this.mintSovereignNft({
571
+ factoryDid: nftFactory.factoryDid,
572
+ callerDid: creatorDid,
573
+ recipientHolderDid: subscriberDid,
574
+ payloadCommitmentDigest: input.payloadCommitmentDigest,
575
+ epochIndex: input.epochIndex
576
+ });
577
+ const outsiderAccessCheck = this.resolveSovereignNftPayloadAccess({
578
+ nftDid: mintedNftBeforeSave.nftDid,
579
+ viewerDid: outsiderProbeDid
580
+ });
581
+ if (outsiderAccessCheck.accessible) throw new CustomError(ErrorCode.ForbiddenFactory, "SocialEconomyFactory: private deliverable leaked to outsider probe");
582
+ const subscriberAccessCheck = this.resolveSovereignNftPayloadAccess({
583
+ nftDid: mintedNftBeforeSave.nftDid,
584
+ viewerDid: subscriberDid
585
+ });
586
+ const nftAfterSaveAndRelease = this.acknowledgeSovereignNftCustody({
587
+ nftDid: mintedNftBeforeSave.nftDid,
588
+ holderDid: subscriberDid,
589
+ verifiedPayloadDigest: input.payloadCommitmentDigest,
590
+ releaseIssuerStorageImmediately: true
591
+ });
592
+ this.processedPilotRunIds.add(pilotRunId);
593
+ return {
594
+ pilotRunId,
595
+ nftFactory: this.getSovereignNftFactory(nftFactory.factoryDid),
596
+ mintedNftBeforeSave,
597
+ outsiderAccessCheck,
598
+ subscriberAccessCheck,
599
+ nftAfterSaveAndRelease,
600
+ issuerStorageReleased: nftAfterSaveAndRelease.payloadCustodyState === "ISSUER_STORAGE_RELEASED" && nftAfterSaveAndRelease.issuerStagingUri === void 0
601
+ };
602
+ }
603
+ /**
604
+ * Issue #1235 (Phase 3 — Declarative Blueprint Safety Verifier):
605
+ * Verifies that a proposed `SocialEconomyFactoryBlueprint` satisfies all protocol safety invariants
606
+ * (Sybil-verified proposer, non-transferable reputation, holder-sovereign visibility, bounded creator
607
+ * staging custody handover, and unique factory DID / value conservation) without mutating state.
608
+ */
609
+ verifyFactoryBlueprintSafety(blueprint) {
610
+ const violations = [];
611
+ const safetyChecksPassed = [];
612
+ const isCleanId = (v) => typeof v === "string" && v.trim().length > 0 && v.trim() === v && !/[\s/\\?#%]|::|->/.test(v);
613
+ const blueprintId = typeof blueprint?.blueprintId === "string" ? blueprint.blueprintId.trim() : "";
614
+ if (!isCleanId(blueprint?.blueprintId)) violations.push("blueprintId must be a clean non-empty identifier");
615
+ else if (this.processedBlueprintIds.has(blueprint.blueprintId)) violations.push(`blueprintId ${blueprint.blueprintId} has already been instantiated`);
616
+ if (typeof blueprint?.ideaTitle !== "string" || blueprint.ideaTitle.trim().length === 0 || blueprint.ideaTitle.trim().length > 160 || /[\r\n\0]/.test(blueprint.ideaTitle)) violations.push("ideaTitle must be a non-empty single-line string of at most 160 chars");
617
+ if (!Number.isSafeInteger(blueprint?.epochIndex) || blueprint.epochIndex < 0) violations.push("epochIndex must be a non-negative safe integer");
618
+ let sybilCheckPassed = false;
619
+ if (!isCleanId(blueprint?.proposerDid)) violations.push("proposerDid must be a clean non-empty DID");
620
+ else {
621
+ const proposerState = this.karmaEngine.getIdentityState(blueprint.proposerDid);
622
+ if (!proposerState || !proposerState.verifiedHumanOrStaker || proposerState.trustMultiplierBps <= 0) violations.push(`proposerDid ${blueprint.proposerDid} is not an active verified identity`);
623
+ else sybilCheckPassed = true;
624
+ }
625
+ const kind = blueprint?.targetFactoryKind;
626
+ const providedSpecsCount = (blueprint?.tokenSpec !== void 0 ? 1 : 0) + (blueprint?.nftSpec !== void 0 ? 1 : 0) + (blueprint?.poolSpec !== void 0 ? 1 : 0);
627
+ if (providedSpecsCount !== 1) violations.push("blueprint must provide exactly one specification matching targetFactoryKind");
628
+ if (kind === "REPUTATION_TOKEN_FACTORY") {
629
+ const spec = blueprint.tokenSpec;
630
+ if (!spec || typeof spec !== "object") violations.push("tokenSpec is required for REPUTATION_TOKEN_FACTORY");
631
+ else {
632
+ if (!isCleanId(spec.issuerDid) || spec.issuerDid !== blueprint.proposerDid) {
633
+ violations.push("tokenSpec.issuerDid must match blueprint.proposerDid");
634
+ sybilCheckPassed = false;
635
+ }
636
+ let conservationSafe = providedSpecsCount === 1;
637
+ if (!isCleanId(spec.factoryDid)) {
638
+ violations.push("tokenSpec.factoryDid must be a clean non-empty DID");
639
+ conservationSafe = false;
640
+ } else if (this.tokenFactories.has(spec.factoryDid) || this.nftFactories.has(spec.factoryDid) || this.poolFactories.has(spec.factoryDid)) {
641
+ violations.push(`factoryDid ${spec.factoryDid} already exists`);
642
+ conservationSafe = false;
643
+ }
644
+ let tokenSafe = providedSpecsCount === 1;
645
+ if (!isCleanId(spec.tokenAddress)) {
646
+ violations.push("tokenSpec.tokenAddress must be a clean non-empty identifier");
647
+ tokenSafe = false;
648
+ conservationSafe = false;
649
+ } else if (this.karmaEngine.getTokenConfig(spec.tokenAddress)) {
650
+ violations.push(`tokenAddress ${spec.tokenAddress} is already registered`);
651
+ tokenSafe = false;
652
+ conservationSafe = false;
653
+ }
654
+ const existingSymbols = new Set(Array.from(this.tokenFactories.values()).map((f) => f.tokenConfig.symbol.toUpperCase()));
655
+ if (!isCleanId(spec.symbol) || !/^[A-Z0-9_]{2,16}$/.test(spec.symbol)) {
656
+ violations.push("tokenSpec.symbol must be 2..16 uppercase alphanumeric characters without whitespace");
657
+ tokenSafe = false;
658
+ } else if (existingSymbols.has(spec.symbol.toUpperCase())) {
659
+ violations.push(`tokenSpec.symbol ${spec.symbol} is already registered`);
660
+ tokenSafe = false;
661
+ conservationSafe = false;
662
+ }
663
+ if (typeof spec.name !== "string" || spec.name.trim().length === 0 || spec.name.trim().length > 64 || /[\r\n\0]/.test(spec.name)) {
664
+ violations.push("tokenSpec.name must be 1..64 single-line characters");
665
+ tokenSafe = false;
666
+ }
667
+ if (typeof spec.creationFeePaid !== "bigint" || spec.creationFeePaid < MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE) {
668
+ violations.push(`tokenSpec.creationFeePaid must be >= ${MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE.toString()}`);
669
+ tokenSafe = false;
670
+ conservationSafe = false;
671
+ }
672
+ const allowance = spec.epochBaseAllowance ?? DEFAULT_EPOCH_KARMA_ALLOWANCE;
673
+ if (typeof allowance !== "bigint" || allowance <= 0n || allowance > 10000n) {
674
+ violations.push("tokenSpec.epochBaseAllowance must be a bigint in 1..10000");
675
+ tokenSafe = false;
676
+ }
677
+ const maxHist = spec.maxHistoricalClaimPerDid ?? DEFAULT_MAX_HISTORICAL_KARMA_CLAIM;
678
+ if (typeof maxHist !== "bigint" || maxHist < 0n || maxHist > 50000n) {
679
+ violations.push("tokenSpec.maxHistoricalClaimPerDid must be a bigint in 0..50000");
680
+ tokenSafe = false;
681
+ }
682
+ if (conservationSafe) safetyChecksPassed.push("CONSERVATION_AND_UNIQUE_FACTORY_DID_INVARIANT");
683
+ if (tokenSafe) safetyChecksPassed.push("NON_TRANSFERABLE_REPUTATION_INVARIANT");
684
+ }
685
+ } else if (kind === "SOVEREIGN_NFT_FACTORY") {
686
+ const spec = blueprint.nftSpec;
687
+ if (!spec || typeof spec !== "object") violations.push("nftSpec is required for SOVEREIGN_NFT_FACTORY");
688
+ else {
689
+ if (!isCleanId(spec.creatorDid) || spec.creatorDid !== blueprint.proposerDid) {
690
+ violations.push("nftSpec.creatorDid must match blueprint.proposerDid");
691
+ sybilCheckPassed = false;
692
+ }
693
+ let conservationSafe = providedSpecsCount === 1;
694
+ if (!isCleanId(spec.factoryDid)) {
695
+ violations.push("nftSpec.factoryDid must be a clean non-empty DID");
696
+ conservationSafe = false;
697
+ } else if (this.tokenFactories.has(spec.factoryDid) || this.nftFactories.has(spec.factoryDid) || this.poolFactories.has(spec.factoryDid)) {
698
+ violations.push(`factoryDid ${spec.factoryDid} already exists`);
699
+ conservationSafe = false;
700
+ }
701
+ let visibilitySafe = providedSpecsCount === 1;
702
+ if (!VALID_NFT_CATEGORIES.has(spec.category)) {
703
+ violations.push(`nftSpec.category ${String(spec.category)} is invalid`);
704
+ visibilitySafe = false;
705
+ }
706
+ if (!VALID_VISIBILITIES.has(spec.defaultVisibility)) {
707
+ violations.push(`nftSpec.defaultVisibility ${String(spec.defaultVisibility)} is invalid`);
708
+ visibilitySafe = false;
709
+ }
710
+ if (typeof spec.seriesName !== "string" || spec.seriesName.trim().length === 0 || spec.seriesName.trim().length > 80 || /[\r\n\0]/.test(spec.seriesName)) {
711
+ violations.push("nftSpec.seriesName must be 1..80 single-line characters");
712
+ visibilitySafe = false;
713
+ }
714
+ if (!Number.isSafeInteger(spec.maxSupply) || spec.maxSupply <= 0 || spec.maxSupply > MAX_SOVEREIGN_NFT_FACTORY_SUPPLY) {
715
+ violations.push(`nftSpec.maxSupply must be in 1..${MAX_SOVEREIGN_NFT_FACTORY_SUPPLY}`);
716
+ visibilitySafe = false;
717
+ conservationSafe = false;
718
+ }
719
+ const isTransferrable = Boolean(spec.transferrable ?? false);
720
+ if (spec.category === "PRIVATE_ENCRYPTED_DELIVERABLE") {
721
+ if (spec.defaultVisibility === "public") {
722
+ violations.push("PRIVATE_ENCRYPTED_DELIVERABLE NFTs cannot default to public visibility");
723
+ visibilitySafe = false;
724
+ }
725
+ if (isTransferrable) {
726
+ violations.push("PRIVATE_ENCRYPTED_DELIVERABLE NFTs must be non-transferrable");
727
+ visibilitySafe = false;
728
+ }
729
+ } else if (spec.category === "PUBLIC_HONOR_BADGE" && isTransferrable) {
730
+ violations.push("PUBLIC_HONOR_BADGE NFTs are soulbound and must be non-transferrable");
731
+ visibilitySafe = false;
732
+ }
733
+ if (conservationSafe) safetyChecksPassed.push("CONSERVATION_AND_UNIQUE_FACTORY_DID_INVARIANT");
734
+ if (visibilitySafe) safetyChecksPassed.push("HOLDER_SOVEREIGN_VISIBILITY_INVARIANT");
735
+ const ttl = spec.issuerStagingTtlEpochs ?? DEFAULT_ISSUER_STAGING_TTL_EPOCHS;
736
+ if (!Number.isSafeInteger(ttl) || ttl <= 0 || ttl > MAX_ISSUER_STAGING_TTL_EPOCHS) violations.push(`nftSpec.issuerStagingTtlEpochs must be in 1..${MAX_ISSUER_STAGING_TTL_EPOCHS}`);
737
+ else if (providedSpecsCount === 1) safetyChecksPassed.push("CUSTODY_HANDOVER_RELEASE_INVARIANT");
738
+ }
739
+ } else if (kind === "KARMA_SETTLEMENT_POOL_FACTORY") {
740
+ const spec = blueprint.poolSpec;
741
+ if (!spec || typeof spec !== "object") violations.push("poolSpec is required for KARMA_SETTLEMENT_POOL_FACTORY");
742
+ else {
743
+ if (!isCleanId(spec.sponsorDid) || spec.sponsorDid !== blueprint.proposerDid) {
744
+ violations.push("poolSpec.sponsorDid must match blueprint.proposerDid");
745
+ sybilCheckPassed = false;
746
+ }
747
+ let poolConservationSafe = providedSpecsCount === 1;
748
+ if (!isCleanId(spec.factoryDid)) {
749
+ violations.push("poolSpec.factoryDid must be a clean non-empty DID");
750
+ poolConservationSafe = false;
751
+ } else if (this.tokenFactories.has(spec.factoryDid) || this.nftFactories.has(spec.factoryDid) || this.poolFactories.has(spec.factoryDid)) {
752
+ violations.push(`factoryDid ${spec.factoryDid} already exists`);
753
+ poolConservationSafe = false;
754
+ }
755
+ if (!VALID_POOL_KINDS.has(spec.poolKind)) {
756
+ violations.push(`poolSpec.poolKind ${String(spec.poolKind)} is invalid`);
757
+ poolConservationSafe = false;
758
+ }
759
+ const tokenAddress = spec.tokenAddress ?? DEFAULT_KARMA_TOKEN_ADDRESS;
760
+ if (!isCleanId(tokenAddress) || !this.karmaEngine.getTokenConfig(tokenAddress)) {
761
+ violations.push(`poolSpec.tokenAddress ${String(tokenAddress)} is not a registered reputation token`);
762
+ poolConservationSafe = false;
763
+ }
764
+ const minWeight = spec.minRecipientKarmaWeight ?? 1n;
765
+ if (typeof minWeight !== "bigint" || minWeight <= 0n) {
766
+ violations.push("poolSpec.minRecipientKarmaWeight must be a positive bigint");
767
+ poolConservationSafe = false;
768
+ }
769
+ if (poolConservationSafe) {
770
+ safetyChecksPassed.push("CONSERVATION_AND_UNIQUE_FACTORY_DID_INVARIANT");
771
+ safetyChecksPassed.push("NON_TRANSFERABLE_REPUTATION_INVARIANT");
772
+ }
773
+ }
774
+ } else violations.push(`unsupported targetFactoryKind ${String(kind)}`);
775
+ if (sybilCheckPassed) safetyChecksPassed.unshift("SYBIL_VERIFIED_PROPOSER_INVARIANT");
776
+ return {
777
+ blueprintId,
778
+ targetFactoryKind: kind,
779
+ safe: violations.length === 0,
780
+ safetyChecksPassed,
781
+ violations
782
+ };
783
+ }
784
+ /**
785
+ * Issue #1235 (Phase 3 — Idea-to-Factory Autonomous Rollout Pipeline):
786
+ * Verifies `blueprint` against all protocol safety invariants and automatically provisions
787
+ * the corresponding `ReputationTokenFactory`, `SovereignNftFactory`, or `KarmaSettlementPoolFactory`.
788
+ */
789
+ instantiateFactoryBlueprint(blueprint) {
790
+ const safetyReport = this.verifyFactoryBlueprintSafety(blueprint);
791
+ if (!safetyReport.safe) throw new CustomError(ErrorCode.ForbiddenFactory, `SocialEconomyFactory: blueprint ${safetyReport.blueprintId || "<invalid>"} failed safety verification: ${safetyReport.violations.join("; ")}`);
792
+ const blueprintId = assertCleanId(blueprint.blueprintId, "blueprintId");
793
+ const ideaTitle = blueprint.ideaTitle.trim();
794
+ const proposerDid = assertCleanId(blueprint.proposerDid, "proposerDid");
795
+ if (blueprint.targetFactoryKind === "REPUTATION_TOKEN_FACTORY") {
796
+ const tokenFactory = this.createReputationTokenFromFactory({
797
+ ...blueprint.tokenSpec,
798
+ epochIndex: blueprint.epochIndex
799
+ });
800
+ this.processedBlueprintIds.add(blueprintId);
801
+ return {
802
+ blueprintId,
803
+ ideaTitle,
804
+ proposerDid,
805
+ targetFactoryKind: blueprint.targetFactoryKind,
806
+ factoryDid: tokenFactory.factoryDid,
807
+ safetyReport,
808
+ tokenFactory
809
+ };
810
+ }
811
+ if (blueprint.targetFactoryKind === "SOVEREIGN_NFT_FACTORY") {
812
+ const nftFactory = this.registerSovereignNftFactory({
813
+ ...blueprint.nftSpec,
814
+ createdAtEpoch: blueprint.epochIndex
815
+ });
816
+ this.processedBlueprintIds.add(blueprintId);
817
+ return {
818
+ blueprintId,
819
+ ideaTitle,
820
+ proposerDid,
821
+ targetFactoryKind: blueprint.targetFactoryKind,
822
+ factoryDid: nftFactory.factoryDid,
823
+ safetyReport,
824
+ nftFactory
825
+ };
826
+ }
827
+ const poolFactory = this.registerKarmaSettlementPoolFactory({
828
+ ...blueprint.poolSpec,
829
+ createdAtEpoch: blueprint.epochIndex
830
+ });
831
+ this.processedBlueprintIds.add(blueprintId);
832
+ return {
833
+ blueprintId,
834
+ ideaTitle,
835
+ proposerDid,
836
+ targetFactoryKind: blueprint.targetFactoryKind,
837
+ factoryDid: poolFactory.factoryDid,
838
+ safetyReport,
839
+ poolFactory
840
+ };
841
+ }
842
+ };
843
+
844
+ //#endregion
845
+ export { DEFAULT_ISSUER_STAGING_TTL_EPOCHS, GIVE_TO_MINT_TOKEN_TYPE, MAX_ISSUER_STAGING_TTL_EPOCHS, MAX_SOVEREIGN_NFT_FACTORY_SUPPLY, MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE, OcapSocialEconomyFactoryRegistry, deriveSovereignNftDid };