@ocap/tx-pipeline 1.30.26 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +46 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +56 -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 +73 -0
  32. package/esm/pipes/pre-flight-waf.mjs +756 -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 +46 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +55 -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 +772 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +73 -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,431 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_ofac_screening = require('./ofac-screening.cjs');
3
+ require('./uniswap-router.cjs');
4
+ const require_transaction_block = require('./transaction-block.cjs');
5
+ let _ocap_mcrypto = require("@ocap/mcrypto");
6
+ let _ocap_util = require("@ocap/util");
7
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
+
9
+ //#region src/uniswap-token-factory-graduation.ts
10
+ /**
11
+ * Minimum creator token vesting cliff in blocks (~7 days at 12s/block = 50,400 blocks)
12
+ * to prevent creator dump / rug-pulls upon Base Uniswap V4 graduation.
13
+ */
14
+ const MIN_CREATOR_VESTING_CLIFF_BLOCKS = 50400;
15
+ /**
16
+ * Canonical burn address for permanently locked Uniswap V4 LP position NFTs.
17
+ */
18
+ const CANONICAL_LP_BURN_DEAD_ADDRESS = "0x000000000000000000000000000000000000dead";
19
+ /**
20
+ * Maximum initial token mint ratio per unit of reserve on the bonding curve.
21
+ */
22
+ const MAX_MINT_RATIO_PER_RESERVE_UNIT = 1e3;
23
+ const FORBIDDEN_KEYS = new Set([
24
+ "__proto__",
25
+ "constructor",
26
+ "prototype"
27
+ ]);
28
+ const CANONICAL_UINT_REGEX = /^\d+$/;
29
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
30
+ const FORBIDDEN_INVESTMENT_PROMISE_REGEX = /\b(apy|apr|dividend|profit[\s_-]*shar|revenue[\s_-]*shar|passive[\s_-]*income|staking[\s_-]*yield|investment[\s_-]*return)\b/i;
31
+ function assertSafeId(val, label) {
32
+ if (typeof val !== "string") throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", `${label} must be a non-empty string`);
33
+ const trimmed = val.trim();
34
+ if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", `Invalid or unsafe ${label}`);
35
+ return trimmed;
36
+ }
37
+ function parsePositiveBn(val, label) {
38
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", `${label} must be a canonical base-10 integer string`);
39
+ const bn = new _ocap_util.BN(val, 10);
40
+ if (bn.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", `${label} must be strictly positive`);
41
+ return bn;
42
+ }
43
+ function parseNonNegativeBn(val, label) {
44
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", `${label} must be a canonical non-negative integer string`);
45
+ return new _ocap_util.BN(val, 10);
46
+ }
47
+ /**
48
+ * Computes the deterministic Base Uniswap V4 `PoolId` (`bytes32` SHA3 digest) for a graduating OCAP `TokenFactory`.
49
+ */
50
+ function computeDeterministicV4GraduationPoolId(params) {
51
+ const fac = assertSafeId(params.factoryAddress, "factoryAddress");
52
+ const tok = assertSafeId(params.tokenAddress, "tokenAddress");
53
+ const res = assertSafeId(params.reserveAddress, "reserveAddress");
54
+ const hook = require_ofac_screening.normalizeScreeningAddress(assertSafeId(params.targetV4HookAddress, "targetV4HookAddress"));
55
+ if (!Number.isSafeInteger(params.targetV4ChainId) || params.targetV4ChainId <= 0) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "targetV4ChainId must be a positive safe integer");
56
+ const canonical = `ocap-v4-graduation:v1:${fac}:${tok}:${res}:${params.targetV4ChainId}:${hook}`;
57
+ return `0x${_ocap_mcrypto.Hasher.SHA3.hash256(Buffer.from(canonical, "utf8")).replace(/^0x/, "").toLowerCase()}`;
58
+ }
59
+ /**
60
+ * OCAP `TokenFactory` Bonding Curve Cross-Chain Incubation & Base Uniswap V4 Auto-Graduation Engine (#1201).
61
+ *
62
+ * Architectural, Anti-Vampire & Regulatory Guarantees:
63
+ * 1. **One-Way Atomic Graduation Latch (`ACTIVE -> GRADUATING -> GRADUATED`)**:
64
+ * - When `reserveBalance >= graduationThreshold`, the factory atomically latches into `GRADUATING`.
65
+ * - Any subsequent bonding-curve buy/sell on a `GRADUATING` or `GRADUATED` factory is immediately rejected,
66
+ * eliminating race conditions where bots drain reserve liquidity during cross-chain migration.
67
+ * 2. **Anti-Rug & Reputation-Backed Graduation (`VerifiedCreatorCredential` + LP Burn/Lock)**:
68
+ * - Requires a non-expired Verified Creator VC from a trusted issuer DID, enforces `>= 50,400` blocks
69
+ * creator vesting cliff, and requires cryptographic proof that migrated V4 LP tokens are burned to
70
+ * `0x...dead` or locked inside `OcapVerifiedHook`.
71
+ * 3. **SEC Howey & Co-Issuer Safe Harbor**:
72
+ * - Enforces a Functional Utility Charter (`isPassiveInvestmentContract: false`), strictly prohibits
73
+ * protocol token allocations (`protocolTokenAllocationBps === 0`), and charges only a flat `ABT`
74
+ * infrastructure graduation fee.
75
+ */
76
+ var OcapTokenFactoryGraduationEngine = class {
77
+ constructor(options) {
78
+ this.factories = /* @__PURE__ */ new Map();
79
+ this.registeredTokenAddresses = /* @__PURE__ */ new Set();
80
+ this.trustedVcIssuerDids = /* @__PURE__ */ new Set();
81
+ this.consumedVcIds = /* @__PURE__ */ new Set();
82
+ this.consumedMigrationEvidences = /* @__PURE__ */ new Set();
83
+ this.ofacSet = /* @__PURE__ */ new Set();
84
+ if (!options || !options.trustedVcIssuerDids) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "trustedVcIssuerDids is required");
85
+ for (const issuer of options.trustedVcIssuerDids) this.trustedVcIssuerDids.add(require_ofac_screening.normalizeScreeningAddress(assertSafeId(issuer, "trustedVcIssuerDid")));
86
+ if (this.trustedVcIssuerDids.size === 0) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "trustedVcIssuerDids must contain at least one trusted VC issuer DID");
87
+ if (options.ofacBlocklist) for (const item of options.ofacBlocklist) this.ofacSet.add(require_ofac_screening.normalizeScreeningAddress(item));
88
+ }
89
+ /**
90
+ * Registers and initializes an incubated `TokenFactory` on OCAP after validating its
91
+ * Functional Utility Charter, Verified Creator VC, Creator Vesting Cliff, and 0% Protocol Token Cut.
92
+ */
93
+ async registerIncubatedTokenFactory(spec, currentUnixTimestamp, statedb) {
94
+ if (!spec || typeof spec !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "Missing IncubatedTokenFactorySpec");
95
+ if (typeof currentUnixTimestamp !== "number" || !Number.isSafeInteger(currentUnixTimestamp) || currentUnixTimestamp <= 0) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "currentUnixTimestamp must be a positive safe integer");
96
+ const factoryAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.factoryAddress, "factoryAddress"));
97
+ const tokenAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.tokenAddress, "tokenAddress"));
98
+ const reserveAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.reserveAddress, "reserveAddress"));
99
+ const creatorDid = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.creatorDid, "creatorDid"));
100
+ const abtTokenAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.abtTokenAddress, "abtTokenAddress"));
101
+ const graduationFeeRecipientDid = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.graduationFeeRecipientDid, "graduationFeeRecipientDid"));
102
+ const targetV4HookAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(spec.targetV4HookAddress, "targetV4HookAddress"));
103
+ if (this.factories.has(factoryAddress)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TOKEN_FACTORY", `TokenFactory ${factoryAddress} is already registered`);
104
+ if (this.registeredTokenAddresses.has(tokenAddress)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_INCUBATED_TOKEN", `Token ${tokenAddress} is already bound to another incubated TokenFactory`);
105
+ if (typeof statedb?.tokenFactory?.get === "function") {
106
+ if (await statedb.tokenFactory.get(factoryAddress)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TOKEN_FACTORY", `TokenFactory ${factoryAddress} already exists in statedb`);
107
+ }
108
+ if (typeof statedb?.token?.get === "function") {
109
+ if (await statedb.token.get(tokenAddress)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_INCUBATED_TOKEN", `Token ${tokenAddress} already exists in statedb`);
110
+ }
111
+ if (tokenAddress === reserveAddress) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "tokenAddress and reserveAddress must be distinct");
112
+ if (creatorDid === graduationFeeRecipientDid) throw new _ocap_util_lib_error.CustomError("SELF_DEALING_GRADUATION_FEE", "creatorDid and graduationFeeRecipientDid must be distinct (cannot self-refund infrastructure fee)");
113
+ if (spec.protocolTokenAllocationBps !== void 0 && spec.protocolTokenAllocationBps !== 0) throw new _ocap_util_lib_error.CustomError("ILLEGAL_PROTOCOL_TOKEN_ALLOCATION", "Protocol token percentage allocation (protocolTokenAllocationBps > 0) is strictly prohibited to avoid co-issuer securities liability; charge flat ABT infrastructure fee only");
114
+ const charter = spec.utilityCharter;
115
+ if (!charter || typeof charter !== "object") throw new _ocap_util_lib_error.CustomError("MISSING_UTILITY_CHARTER", "FunctionalUtilityCharter is required");
116
+ if (charter.isPassiveInvestmentContract === true || charter.promisesProfitFromOthersEfforts === true) throw new _ocap_util_lib_error.CustomError("ILLEGAL_INVESTMENT_CONTRACT_CHARTER", "Passive investment contracts or profit-sharing promises are strictly prohibited under Howey Safe Harbor");
117
+ if (!new Set([
118
+ "AIGNE_AGENT_COMPUTE_CREDIT",
119
+ "BLOCKLET_SAAS_ACCESS_TOKEN",
120
+ "DID_COMMUNITY_MEMBERSHIP_BADGE"
121
+ ]).has(charter.category)) throw new _ocap_util_lib_error.CustomError("INVALID_UTILITY_CHARTER", `Unsupported utility category: ${String(charter.category)}`);
122
+ const targetBlockletDid = require_ofac_screening.normalizeScreeningAddress(assertSafeId(charter.targetBlockletDid, "utilityCharter.targetBlockletDid"));
123
+ const consumptiveDesc = assertSafeId(charter.consumptiveUseDescription, "utilityCharter.consumptiveUseDescription");
124
+ if (consumptiveDesc.length < 12) throw new _ocap_util_lib_error.CustomError("INVALID_UTILITY_CHARTER", "utilityCharter.consumptiveUseDescription must be at least 12 characters");
125
+ if (FORBIDDEN_INVESTMENT_PROMISE_REGEX.test(consumptiveDesc)) throw new _ocap_util_lib_error.CustomError("ILLEGAL_INVESTMENT_CONTRACT_CHARTER", "utilityCharter.consumptiveUseDescription contains prohibited passive-yield/dividend/profit-sharing promotion terms");
126
+ const vc = spec.creatorVc;
127
+ if (!vc || typeof vc !== "object") throw new _ocap_util_lib_error.CustomError("MISSING_CREATOR_VC", "VerifiedCreatorCredential is required");
128
+ const vcId = assertSafeId(vc.vcId, "creatorVc.vcId");
129
+ if (this.consumedVcIds.has(vcId)) throw new _ocap_util_lib_error.CustomError("REPLAYED_CREATOR_VC", `VerifiedCreatorCredential ${vcId} has already been used`);
130
+ const vcIssuer = require_ofac_screening.normalizeScreeningAddress(assertSafeId(vc.issuerDid, "creatorVc.issuerDid"));
131
+ if (!this.trustedVcIssuerDids.has(vcIssuer)) throw new _ocap_util_lib_error.CustomError("UNTRUSTED_VC_ISSUER", `VC issuer ${vcIssuer} is not in trustedVcIssuerDids`);
132
+ const vcSubject = require_ofac_screening.normalizeScreeningAddress(assertSafeId(vc.subjectCreatorDid, "creatorVc.subjectCreatorDid"));
133
+ const vcFactory = require_ofac_screening.normalizeScreeningAddress(assertSafeId(vc.boundFactoryAddress, "creatorVc.boundFactoryAddress"));
134
+ if (vcSubject !== creatorDid || vcFactory !== factoryAddress) throw new _ocap_util_lib_error.CustomError("INVALID_CREATOR_VC_BINDING", "creatorVc subjectCreatorDid and boundFactoryAddress must match creatorDid and factoryAddress");
135
+ if (typeof vc.issuedAt !== "number" || !Number.isSafeInteger(vc.issuedAt) || vc.issuedAt <= 0 || currentUnixTimestamp < vc.issuedAt || typeof vc.expiresAt !== "number" || !Number.isSafeInteger(vc.expiresAt) || vc.expiresAt <= vc.issuedAt || currentUnixTimestamp > vc.expiresAt) throw new _ocap_util_lib_error.CustomError("EXPIRED_CREATOR_VC", `VerifiedCreatorCredential ${vcId} is expired or has invalid timestamps`);
136
+ if (typeof vc.verifiedSignatureHex !== "string" || !/^0x[0-9a-fA-F]{64,256}$/.test(vc.verifiedSignatureHex)) throw new _ocap_util_lib_error.CustomError("INVALID_CREATOR_VC_SIGNATURE", "creatorVc.verifiedSignatureHex must be a valid hex signature");
137
+ if (typeof spec.creatorVestingCliffBlocks !== "number" || !Number.isSafeInteger(spec.creatorVestingCliffBlocks) || spec.creatorVestingCliffBlocks < MIN_CREATOR_VESTING_CLIFF_BLOCKS) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_CREATOR_VESTING_CLIFF", `creatorVestingCliffBlocks (${spec.creatorVestingCliffBlocks}) must be at least ${MIN_CREATOR_VESTING_CLIFF_BLOCKS} blocks`);
138
+ require_ofac_screening.assertNotOfacSanctioned([
139
+ factoryAddress,
140
+ tokenAddress,
141
+ reserveAddress,
142
+ creatorDid,
143
+ abtTokenAddress,
144
+ graduationFeeRecipientDid,
145
+ targetV4HookAddress,
146
+ targetBlockletDid,
147
+ vcIssuer
148
+ ], this.ofacSet);
149
+ const graduationThresholdBn = parsePositiveBn(spec.graduationThreshold, "graduationThreshold");
150
+ const initialReserveBn = parseNonNegativeBn(spec.initialReserveBalance ?? "0", "initialReserveBalance");
151
+ const initialSupplyBn = parseNonNegativeBn(spec.initialSupply ?? "0", "initialSupply");
152
+ if (!initialReserveBn.isZero() || !initialSupplyBn.isZero()) throw new _ocap_util_lib_error.CustomError("UNBACKED_INITIAL_RESERVE_OR_SUPPLY", "Incubated TokenFactory must start with initialReserveBalance = 0 and initialSupply = 0 to prevent unbacked supply/reserve inflation");
153
+ const fixedAbtGraduationFeeBn = parseNonNegativeBn(spec.fixedAbtGraduationFee, "fixedAbtGraduationFee");
154
+ if (!Number.isSafeInteger(spec.targetV4ChainId) || spec.targetV4ChainId <= 0) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "targetV4ChainId must be a positive safe integer");
155
+ const record = {
156
+ factoryAddress,
157
+ tokenAddress,
158
+ reserveAddress,
159
+ creatorDid,
160
+ graduationThreshold: graduationThresholdBn.toString(10),
161
+ reserveBalance: initialReserveBn.toString(10),
162
+ currentSupply: initialSupplyBn.toString(10),
163
+ creatorVestingCliffBlocks: spec.creatorVestingCliffBlocks,
164
+ protocolTokenAllocationBps: 0,
165
+ fixedAbtGraduationFee: fixedAbtGraduationFeeBn.toString(10),
166
+ abtTokenAddress,
167
+ graduationFeeRecipientDid,
168
+ targetV4ChainId: spec.targetV4ChainId,
169
+ targetV4HookAddress,
170
+ utilityCharter: {
171
+ category: charter.category,
172
+ targetBlockletDid,
173
+ consumptiveUseDescription: consumptiveDesc,
174
+ isPassiveInvestmentContract: false,
175
+ promisesProfitFromOthersEfforts: false
176
+ },
177
+ creatorVcId: vcId,
178
+ status: "ACTIVE"
179
+ };
180
+ if (typeof statedb?.tokenFactory?.updateOrCreate === "function") await statedb.tokenFactory.updateOrCreate(factoryAddress, {
181
+ address: factoryAddress,
182
+ tokenAddress,
183
+ reserveAddress,
184
+ reserveBalance: record.reserveBalance,
185
+ currentSupply: record.currentSupply,
186
+ status: record.status
187
+ });
188
+ if (typeof statedb?.token?.updateOrCreate === "function") await statedb.token.updateOrCreate(tokenAddress, {
189
+ address: tokenAddress,
190
+ totalSupply: record.currentSupply
191
+ });
192
+ this.consumedVcIds.add(vcId);
193
+ this.registeredTokenAddresses.add(tokenAddress);
194
+ this.factories.set(factoryAddress, record);
195
+ return { ...record };
196
+ }
197
+ /**
198
+ * Executes a bonding curve buy on an `ACTIVE` incubated `TokenFactory` inside an atomic `TransactionBlock`
199
+ * with `enforceZeroSum: true`.
200
+ *
201
+ * If the post-buy `reserveBalance >= graduationThreshold`, the factory atomically latches into
202
+ * `status = 'GRADUATING'` in the exact same transaction and computes the deterministic Base V4 Pool ID.
203
+ */
204
+ async executeBondingCurveBuy(params, statedb) {
205
+ if (!params || typeof params !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "Missing executeBondingCurveBuy params");
206
+ const factoryAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(params.factoryAddress, "factoryAddress"));
207
+ const buyerDid = require_ofac_screening.normalizeScreeningAddress(assertSafeId(params.buyerDid, "buyerDid"));
208
+ const factory = this.factories.get(factoryAddress);
209
+ if (!factory) throw new _ocap_util_lib_error.CustomError("NOT_FOUND", `Incubated TokenFactory ${factoryAddress} not found`);
210
+ if (factory.status !== "ACTIVE") throw new _ocap_util_lib_error.CustomError("FACTORY_ALREADY_GRADUATING_OR_GRADUATED", `TokenFactory ${factoryAddress} is in ${factory.status} state; bonding curve trading is permanently locked`);
211
+ if (typeof statedb?.tokenFactory?.get === "function") {
212
+ const onChainFac = await statedb.tokenFactory.get(factoryAddress);
213
+ if (onChainFac && (onChainFac.status !== factory.status || String(onChainFac.reserveBalance) !== factory.reserveBalance || String(onChainFac.currentSupply) !== factory.currentSupply)) throw new _ocap_util_lib_error.CustomError("STATE_DESYNC_DETECTED", `On-chain TokenFactory ${factoryAddress} state does not match in-memory engine state`);
214
+ }
215
+ if (typeof params.currentBlockHeight !== "number" || !Number.isSafeInteger(params.currentBlockHeight) || params.currentBlockHeight <= 0) throw new _ocap_util_lib_error.CustomError("INVALID_TOKEN_FACTORY_GRADUATION", "currentBlockHeight must be a positive safe integer");
216
+ const combinedOfac = new Set(this.ofacSet);
217
+ if (params.ofacBlocklist) for (const a of params.ofacBlocklist) combinedOfac.add(require_ofac_screening.normalizeScreeningAddress(a));
218
+ require_ofac_screening.assertNotOfacSanctioned([buyerDid, factoryAddress], combinedOfac);
219
+ const reserveInBn = parsePositiveBn(params.reserveAmountIn, "reserveAmountIn");
220
+ const tokensOutBn = parsePositiveBn(params.tokensMintedOut, "tokensMintedOut");
221
+ const curReserveBn = new _ocap_util.BN(factory.reserveBalance, 10);
222
+ const curSupplyBn = new _ocap_util.BN(factory.currentSupply, 10);
223
+ const thresholdBn = new _ocap_util.BN(factory.graduationThreshold, 10);
224
+ const maxInitialMintBn = reserveInBn.mul(new _ocap_util.BN(MAX_MINT_RATIO_PER_RESERVE_UNIT));
225
+ if (tokensOutBn.gt(maxInitialMintBn)) throw new _ocap_util_lib_error.CustomError("BONDING_CURVE_MINT_CAP_EXCEEDED", `Requested tokensMintedOut (${tokensOutBn.toString(10)}) exceeds maximum bonding curve mint ratio (${MAX_MINT_RATIO_PER_RESERVE_UNIT}x reserveAmountIn)`);
226
+ if (curReserveBn.gt(new _ocap_util.BN(0)) && curSupplyBn.gt(new _ocap_util.BN(0))) {
227
+ if (tokensOutBn.mul(curReserveBn).gt(reserveInBn.mul(curSupplyBn))) throw new _ocap_util_lib_error.CustomError("BONDING_CURVE_PRICE_INVARIANT_VIOLATED", "Bonding curve marginal token price cannot decrease as reserve balance grows");
228
+ }
229
+ const nextReserveBn = curReserveBn.add(reserveInBn);
230
+ const nextSupplyBn = curSupplyBn.add(tokensOutBn);
231
+ const willGraduate = nextReserveBn.gte(thresholdBn);
232
+ const nextStatus = willGraduate ? "GRADUATING" : "ACTIVE";
233
+ const deterministicBaseV4PoolId = willGraduate ? computeDeterministicV4GraduationPoolId({
234
+ factoryAddress: factory.factoryAddress,
235
+ tokenAddress: factory.tokenAddress,
236
+ reserveAddress: factory.reserveAddress,
237
+ targetV4ChainId: factory.targetV4ChainId,
238
+ targetV4HookAddress: factory.targetV4HookAddress
239
+ }) : void 0;
240
+ const blockResult = await require_transaction_block.executeTransactionBlock({
241
+ from: buyerDid,
242
+ enforceZeroSum: true,
243
+ statements: [{
244
+ type: "bonding_curve_buy",
245
+ typeUrl: "fg:t:bonding_curve_buy",
246
+ from: buyerDid,
247
+ itx: {
248
+ factory: factoryAddress,
249
+ tokenAddress: factory.tokenAddress,
250
+ reserveAddress: factory.reserveAddress,
251
+ reserveAmountIn: reserveInBn.toString(10),
252
+ tokensMintedOut: tokensOutBn.toString(10)
253
+ }
254
+ }]
255
+ }, {
256
+ statedb,
257
+ executeStatement: async (_stmt, overlay) => {
258
+ const buyerAcct = await overlay.account.get(buyerDid);
259
+ if (!buyerAcct) throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Buyer account ${buyerDid} not found`);
260
+ const availReserve = new _ocap_util.BN(buyerAcct.tokens?.[factory.reserveAddress] || "0", 10);
261
+ if (availReserve.lt(reserveInBn)) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_BALANCE", `Insufficient reserve token (${factory.reserveAddress}) balance`);
262
+ const curBuyerTok = new _ocap_util.BN(buyerAcct.tokens?.[factory.tokenAddress] || "0", 10);
263
+ await overlay.account.update(buyerDid, {
264
+ ...buyerAcct,
265
+ tokens: {
266
+ ...buyerAcct.tokens || {},
267
+ [factory.reserveAddress]: availReserve.sub(reserveInBn).toString(10),
268
+ [factory.tokenAddress]: curBuyerTok.add(tokensOutBn).toString(10)
269
+ }
270
+ });
271
+ await overlay.tokenFactory.update(factoryAddress, {
272
+ address: factoryAddress,
273
+ tokenAddress: factory.tokenAddress,
274
+ reserveAddress: factory.reserveAddress,
275
+ reserveBalance: nextReserveBn.toString(10),
276
+ currentSupply: nextSupplyBn.toString(10),
277
+ status: nextStatus,
278
+ ...willGraduate ? {
279
+ graduatingAtHeight: params.currentBlockHeight,
280
+ creatorUnlockHeight: params.currentBlockHeight + factory.creatorVestingCliffBlocks,
281
+ graduatedBaseV4PoolId: deterministicBaseV4PoolId
282
+ } : {}
283
+ });
284
+ await overlay.token.update(factory.tokenAddress, {
285
+ address: factory.tokenAddress,
286
+ totalSupply: nextSupplyBn.toString(10)
287
+ });
288
+ return {
289
+ reserveBalance: nextReserveBn.toString(10),
290
+ currentSupply: nextSupplyBn.toString(10),
291
+ status: nextStatus
292
+ };
293
+ }
294
+ });
295
+ if (!blockResult.ok) throw blockResult.error || new _ocap_util_lib_error.CustomError("BONDING_CURVE_BUY_FAILED", "Bonding curve buy failed");
296
+ factory.reserveBalance = nextReserveBn.toString(10);
297
+ factory.currentSupply = nextSupplyBn.toString(10);
298
+ if (willGraduate) {
299
+ factory.status = "GRADUATING";
300
+ factory.graduatingAtHeight = params.currentBlockHeight;
301
+ factory.creatorUnlockHeight = params.currentBlockHeight + factory.creatorVestingCliffBlocks;
302
+ factory.graduatedBaseV4PoolId = deterministicBaseV4PoolId;
303
+ }
304
+ return {
305
+ blockResult,
306
+ factory: { ...factory },
307
+ triggeredGraduation: willGraduate,
308
+ deterministicBaseV4PoolId
309
+ };
310
+ }
311
+ /**
312
+ * Finalizes cross-chain graduation (`GRADUATING -> GRADUATED`) upon verifying the `#1169` Rollup
313
+ * migration proof, LP permanent burn/lock (`0x...dead` or `LOCKED_IN_HOOK`), and flat `ABT` graduation fee.
314
+ */
315
+ async finalizeV4Graduation(params, statedb) {
316
+ if (!params || typeof params !== "object" || !params.migrationProof) throw new _ocap_util_lib_error.CustomError("INVALID_MIGRATION_PROOF", "Missing BaseV4GraduationMigrationProof");
317
+ const { migrationProof, currentBlockHeight } = params;
318
+ if (typeof currentBlockHeight !== "number" || !Number.isSafeInteger(currentBlockHeight) || currentBlockHeight <= 0) throw new _ocap_util_lib_error.CustomError("INVALID_MIGRATION_PROOF", "currentBlockHeight must be a positive safe integer");
319
+ const factoryAddress = require_ofac_screening.normalizeScreeningAddress(assertSafeId(migrationProof.factoryAddress, "migrationProof.factoryAddress"));
320
+ const factory = this.factories.get(factoryAddress);
321
+ if (!factory) throw new _ocap_util_lib_error.CustomError("NOT_FOUND", `Incubated TokenFactory ${factoryAddress} not found`);
322
+ if (factory.status !== "GRADUATING") throw new _ocap_util_lib_error.CustomError("INVALID_GRADUATION_STATE", `TokenFactory ${factoryAddress} must be in GRADUATING state to finalize (current: ${factory.status})`);
323
+ if (factory.graduatingAtHeight !== void 0 && currentBlockHeight < factory.graduatingAtHeight) throw new _ocap_util_lib_error.CustomError("INVALID_MIGRATION_PROOF", `currentBlockHeight (${currentBlockHeight}) cannot be earlier than graduatingAtHeight (${factory.graduatingAtHeight})`);
324
+ if (typeof statedb?.tokenFactory?.get === "function") {
325
+ const onChainFac = await statedb.tokenFactory.get(factoryAddress);
326
+ if (onChainFac && (onChainFac.status !== factory.status || String(onChainFac.reserveBalance) !== factory.reserveBalance || String(onChainFac.currentSupply) !== factory.currentSupply)) throw new _ocap_util_lib_error.CustomError("STATE_DESYNC_DETECTED", `On-chain TokenFactory ${factoryAddress} state does not match in-memory engine state`);
327
+ }
328
+ if (migrationProof.rollupVerified !== true) throw new _ocap_util_lib_error.CustomError("UNVERIFIED_ROLLUP_EVIDENCE", `V4 graduation migration proof for ${factoryAddress} is not verified by #1169 Rollup consensus`);
329
+ if (typeof migrationProof.evidenceHash !== "string" || !BYTES32_HEX_REGEX.test(migrationProof.evidenceHash)) throw new _ocap_util_lib_error.CustomError("INVALID_MIGRATION_PROOF", "evidenceHash must be a 32-byte 0x hex string");
330
+ const normalizedEvidence = migrationProof.evidenceHash.toLowerCase();
331
+ if (this.consumedMigrationEvidences.has(normalizedEvidence)) throw new _ocap_util_lib_error.CustomError("REPLAYED_MIGRATION_EVIDENCE", `Migration evidence ${normalizedEvidence} already consumed`);
332
+ if (migrationProof.targetV4ChainId !== factory.targetV4ChainId) throw new _ocap_util_lib_error.CustomError("INVALID_MIGRATION_PROOF", `targetV4ChainId (${migrationProof.targetV4ChainId}) does not match factory targetV4ChainId (${factory.targetV4ChainId})`);
333
+ const expectedPoolId = computeDeterministicV4GraduationPoolId({
334
+ factoryAddress: factory.factoryAddress,
335
+ tokenAddress: factory.tokenAddress,
336
+ reserveAddress: factory.reserveAddress,
337
+ targetV4ChainId: factory.targetV4ChainId,
338
+ targetV4HookAddress: factory.targetV4HookAddress
339
+ });
340
+ if (typeof migrationProof.baseV4PoolId !== "string" || migrationProof.baseV4PoolId.toLowerCase() !== expectedPoolId) throw new _ocap_util_lib_error.CustomError("POOL_ID_MISMATCH", `migrationProof.baseV4PoolId (${migrationProof.baseV4PoolId}) does not match deterministic V4 PoolId (${expectedPoolId})`);
341
+ const attachedHook = require_ofac_screening.normalizeScreeningAddress(assertSafeId(migrationProof.attachedHookAddress, "migrationProof.attachedHookAddress"));
342
+ if (attachedHook !== factory.targetV4HookAddress) throw new _ocap_util_lib_error.CustomError("HOOK_ADDRESS_MISMATCH", `attachedHookAddress (${attachedHook}) does not match factory targetV4HookAddress (${factory.targetV4HookAddress})`);
343
+ const migratedReserveBn = parsePositiveBn(migrationProof.migratedReserveAmount, "migratedReserveAmount");
344
+ if (!migratedReserveBn.eq(new _ocap_util.BN(factory.reserveBalance, 10))) throw new _ocap_util_lib_error.CustomError("MIGRATED_RESERVE_MISMATCH", `migratedReserveAmount (${migratedReserveBn.toString(10)}) must equal full factory reserveBalance (${factory.reserveBalance})`);
345
+ const holder = require_ofac_screening.normalizeScreeningAddress(assertSafeId(migrationProof.lpPositionHolderAddress, "migrationProof.lpPositionHolderAddress"));
346
+ if (migrationProof.lpPositionLockMode === "BURNED_TO_DEAD_ADDRESS") {
347
+ if (holder !== CANONICAL_LP_BURN_DEAD_ADDRESS) throw new _ocap_util_lib_error.CustomError("INVALID_LP_BURN_HOLDER", `BURNED_TO_DEAD_ADDRESS mode requires lpPositionHolderAddress to equal ${CANONICAL_LP_BURN_DEAD_ADDRESS}`);
348
+ } else if (migrationProof.lpPositionLockMode === "LOCKED_IN_HOOK") {
349
+ if (holder !== factory.targetV4HookAddress) throw new _ocap_util_lib_error.CustomError("INVALID_LP_LOCK_HOLDER", `LOCKED_IN_HOOK mode requires lpPositionHolderAddress to equal ${factory.targetV4HookAddress}`);
350
+ } else throw new _ocap_util_lib_error.CustomError("INVALID_LP_LOCK_MODE", `Unsupported lpPositionLockMode: ${String(migrationProof.lpPositionLockMode)}`);
351
+ const feeBn = new _ocap_util.BN(factory.fixedAbtGraduationFee, 10);
352
+ if (feeBn.gt(new _ocap_util.BN(0))) {
353
+ const feeRes = await require_transaction_block.executeTransactionBlock({
354
+ from: factory.creatorDid,
355
+ enforceZeroSum: true,
356
+ statements: [{
357
+ type: "transfer_v3",
358
+ typeUrl: "fg:t:transfer_v3",
359
+ from: factory.creatorDid,
360
+ itx: {
361
+ to: factory.graduationFeeRecipientDid,
362
+ tokens: [{
363
+ address: factory.abtTokenAddress,
364
+ value: feeBn.toString(10)
365
+ }]
366
+ }
367
+ }]
368
+ }, {
369
+ statedb,
370
+ executeStatement: async (_stmt, overlay) => {
371
+ const creatorAcct = await overlay.account.get(factory.creatorDid);
372
+ const availAbt = new _ocap_util.BN(creatorAcct?.tokens?.[factory.abtTokenAddress] || "0", 10);
373
+ if (availAbt.lt(feeBn)) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_GRADUATION_FEE_BALANCE", `Creator ${factory.creatorDid} has insufficient ABT for flat graduation fee (${feeBn.toString(10)})`);
374
+ const recAcct = await overlay.account.get(factory.graduationFeeRecipientDid) || {
375
+ address: factory.graduationFeeRecipientDid,
376
+ tokens: {}
377
+ };
378
+ const curRecAbt = new _ocap_util.BN(recAcct.tokens?.[factory.abtTokenAddress] || "0", 10);
379
+ await overlay.account.update(factory.creatorDid, {
380
+ ...creatorAcct,
381
+ tokens: {
382
+ ...creatorAcct.tokens || {},
383
+ [factory.abtTokenAddress]: availAbt.sub(feeBn).toString(10)
384
+ }
385
+ });
386
+ await overlay.account.updateOrCreate(factory.graduationFeeRecipientDid, {
387
+ ...recAcct,
388
+ address: factory.graduationFeeRecipientDid,
389
+ tokens: {
390
+ ...recAcct.tokens || {},
391
+ [factory.abtTokenAddress]: curRecAbt.add(feeBn).toString(10)
392
+ }
393
+ });
394
+ return { paidGraduationFee: feeBn.toString(10) };
395
+ }
396
+ });
397
+ if (!feeRes.ok) throw feeRes.error || new _ocap_util_lib_error.CustomError("GRADUATION_FEE_PAYMENT_FAILED", "Failed to pay flat ABT graduation fee");
398
+ }
399
+ if (typeof statedb?.tokenFactory?.update === "function") await statedb.tokenFactory.update(factoryAddress, {
400
+ address: factoryAddress,
401
+ tokenAddress: factory.tokenAddress,
402
+ reserveAddress: factory.reserveAddress,
403
+ reserveBalance: factory.reserveBalance,
404
+ migratedReserveBalance: migratedReserveBn.toString(10),
405
+ currentSupply: factory.currentSupply,
406
+ status: "GRADUATED",
407
+ graduatedAtHeight: currentBlockHeight,
408
+ graduatedBaseV4PoolId: expectedPoolId,
409
+ migrationEvidenceHash: normalizedEvidence
410
+ });
411
+ this.consumedMigrationEvidences.add(normalizedEvidence);
412
+ factory.status = "GRADUATED";
413
+ factory.graduatedAtHeight = currentBlockHeight;
414
+ factory.graduatedBaseV4PoolId = expectedPoolId;
415
+ factory.migrationEvidenceHash = normalizedEvidence;
416
+ factory.lpPositionLockMode = migrationProof.lpPositionLockMode;
417
+ return { ...factory };
418
+ }
419
+ getFactory(factoryAddress) {
420
+ const norm = require_ofac_screening.normalizeScreeningAddress(assertSafeId(factoryAddress, "factoryAddress"));
421
+ const rec = this.factories.get(norm);
422
+ return rec ? { ...rec } : void 0;
423
+ }
424
+ };
425
+
426
+ //#endregion
427
+ exports.CANONICAL_LP_BURN_DEAD_ADDRESS = CANONICAL_LP_BURN_DEAD_ADDRESS;
428
+ exports.MAX_MINT_RATIO_PER_RESERVE_UNIT = MAX_MINT_RATIO_PER_RESERVE_UNIT;
429
+ exports.MIN_CREATOR_VESTING_CLIFF_BLOCKS = MIN_CREATOR_VESTING_CLIFF_BLOCKS;
430
+ exports.OcapTokenFactoryGraduationEngine = OcapTokenFactoryGraduationEngine;
431
+ exports.computeDeterministicV4GraduationPoolId = computeDeterministicV4GraduationPoolId;
@@ -0,0 +1,187 @@
1
+ import { TransactionBlockResult } from "./transaction-block.cjs";
2
+
3
+ //#region src/uniswap-token-factory-graduation.d.ts
4
+
5
+ /**
6
+ * Minimum creator token vesting cliff in blocks (~7 days at 12s/block = 50,400 blocks)
7
+ * to prevent creator dump / rug-pulls upon Base Uniswap V4 graduation.
8
+ */
9
+ declare const MIN_CREATOR_VESTING_CLIFF_BLOCKS = 50400;
10
+ /**
11
+ * Canonical burn address for permanently locked Uniswap V4 LP position NFTs.
12
+ */
13
+ declare const CANONICAL_LP_BURN_DEAD_ADDRESS = "0x000000000000000000000000000000000000dead";
14
+ /**
15
+ * Maximum initial token mint ratio per unit of reserve on the bonding curve.
16
+ */
17
+ declare const MAX_MINT_RATIO_PER_RESERVE_UNIT = 1000;
18
+ type TokenFactoryGraduationStatus = 'ACTIVE' | 'GRADUATING' | 'GRADUATED';
19
+ type FunctionalUtilityCategory = 'AIGNE_AGENT_COMPUTE_CREDIT' | 'BLOCKLET_SAAS_ACCESS_TOKEN' | 'DID_COMMUNITY_MEMBERSHIP_BADGE';
20
+ /**
21
+ * Functional Utility Charter required by SEC Howey Safe Harbor:
22
+ * Every incubated TokenFactory must have a concrete consumptive utility in a live Blocklet / AIGNE Agent
23
+ * and must explicitly disclaim passive profit-sharing or investment-contract promises.
24
+ */
25
+ interface FunctionalUtilityCharter {
26
+ category: FunctionalUtilityCategory;
27
+ targetBlockletDid: string;
28
+ consumptiveUseDescription: string;
29
+ /** Must ALWAYS be false (SEC Howey Test Safe Harbor) */
30
+ isPassiveInvestmentContract?: boolean;
31
+ /** Must ALWAYS be false (SEC Howey Test Safe Harbor) */
32
+ promisesProfitFromOthersEfforts?: boolean;
33
+ }
34
+ /**
35
+ * W3C / DID Verifiable Credential proving the creator's verified developer / identity reputation
36
+ * to prevent anonymous Sybil rug-pull factories from polluting Base & Uniswap V4.
37
+ */
38
+ interface VerifiedCreatorCredential {
39
+ vcId: string;
40
+ issuerDid: string;
41
+ subjectCreatorDid: string;
42
+ boundFactoryAddress: string;
43
+ issuedAt: number;
44
+ expiresAt: number;
45
+ verifiedSignatureHex: string;
46
+ }
47
+ interface IncubatedTokenFactorySpec {
48
+ factoryAddress: string;
49
+ tokenAddress: string;
50
+ reserveAddress: string;
51
+ creatorDid: string;
52
+ /** Reserve threshold (in base units of `reserveAddress`, e.g. ABT or USDC) that triggers auto-graduation */
53
+ graduationThreshold: string;
54
+ /** Initial bonding curve reserve balance (usually "0" or creator seed) */
55
+ initialReserveBalance?: string;
56
+ /** Initial minted token supply (usually "0") */
57
+ initialSupply?: string;
58
+ /** Mandatory creator vesting cliff in blocks (`>= 50400`) */
59
+ creatorVestingCliffBlocks: number;
60
+ /** Must ALWAYS be 0 or omitted (Zero protocol token cut to avoid SEC co-issuer liability) */
61
+ protocolTokenAllocationBps?: number;
62
+ /** Fixed flat ABT infrastructure fee charged once upon graduation */
63
+ fixedAbtGraduationFee: string;
64
+ abtTokenAddress: string;
65
+ graduationFeeRecipientDid: string;
66
+ /** Target EVM chain ID for Uniswap V4 graduation (e.g., 8453 for Base) */
67
+ targetV4ChainId: number;
68
+ /** OcapVerifiedHook contract address attached to the graduated Uniswap V4 pool */
69
+ targetV4HookAddress: string;
70
+ utilityCharter: FunctionalUtilityCharter;
71
+ creatorVc: VerifiedCreatorCredential;
72
+ }
73
+ interface IncubatedTokenFactoryRecord {
74
+ factoryAddress: string;
75
+ tokenAddress: string;
76
+ reserveAddress: string;
77
+ creatorDid: string;
78
+ graduationThreshold: string;
79
+ reserveBalance: string;
80
+ currentSupply: string;
81
+ creatorVestingCliffBlocks: number;
82
+ creatorUnlockHeight?: number;
83
+ protocolTokenAllocationBps: 0;
84
+ fixedAbtGraduationFee: string;
85
+ abtTokenAddress: string;
86
+ graduationFeeRecipientDid: string;
87
+ targetV4ChainId: number;
88
+ targetV4HookAddress: string;
89
+ utilityCharter: FunctionalUtilityCharter;
90
+ creatorVcId: string;
91
+ status: TokenFactoryGraduationStatus;
92
+ graduatingAtHeight?: number;
93
+ graduatedAtHeight?: number;
94
+ graduatedBaseV4PoolId?: string;
95
+ migrationEvidenceHash?: string;
96
+ lpPositionLockMode?: 'BURNED_TO_DEAD_ADDRESS' | 'LOCKED_IN_HOOK';
97
+ }
98
+ /**
99
+ * Cryptographic proof (`#1169` Rollup Bridge Evidence + Base Uniswap V4 Pool initialization receipt)
100
+ * required to transition a factory from `GRADUATING -> GRADUATED`.
101
+ */
102
+ interface BaseV4GraduationMigrationProof {
103
+ factoryAddress: string;
104
+ evidenceHash: string;
105
+ rollupVerified: boolean;
106
+ targetV4ChainId: number;
107
+ baseV4PoolId: string;
108
+ attachedHookAddress: string;
109
+ migratedReserveAmount: string;
110
+ lpPositionLockMode: 'BURNED_TO_DEAD_ADDRESS' | 'LOCKED_IN_HOOK';
111
+ lpPositionHolderAddress: string;
112
+ }
113
+ /**
114
+ * Computes the deterministic Base Uniswap V4 `PoolId` (`bytes32` SHA3 digest) for a graduating OCAP `TokenFactory`.
115
+ */
116
+ declare function computeDeterministicV4GraduationPoolId(params: {
117
+ factoryAddress: string;
118
+ tokenAddress: string;
119
+ reserveAddress: string;
120
+ targetV4ChainId: number;
121
+ targetV4HookAddress: string;
122
+ }): string;
123
+ /**
124
+ * OCAP `TokenFactory` Bonding Curve Cross-Chain Incubation & Base Uniswap V4 Auto-Graduation Engine (#1201).
125
+ *
126
+ * Architectural, Anti-Vampire & Regulatory Guarantees:
127
+ * 1. **One-Way Atomic Graduation Latch (`ACTIVE -> GRADUATING -> GRADUATED`)**:
128
+ * - When `reserveBalance >= graduationThreshold`, the factory atomically latches into `GRADUATING`.
129
+ * - Any subsequent bonding-curve buy/sell on a `GRADUATING` or `GRADUATED` factory is immediately rejected,
130
+ * eliminating race conditions where bots drain reserve liquidity during cross-chain migration.
131
+ * 2. **Anti-Rug & Reputation-Backed Graduation (`VerifiedCreatorCredential` + LP Burn/Lock)**:
132
+ * - Requires a non-expired Verified Creator VC from a trusted issuer DID, enforces `>= 50,400` blocks
133
+ * creator vesting cliff, and requires cryptographic proof that migrated V4 LP tokens are burned to
134
+ * `0x...dead` or locked inside `OcapVerifiedHook`.
135
+ * 3. **SEC Howey & Co-Issuer Safe Harbor**:
136
+ * - Enforces a Functional Utility Charter (`isPassiveInvestmentContract: false`), strictly prohibits
137
+ * protocol token allocations (`protocolTokenAllocationBps === 0`), and charges only a flat `ABT`
138
+ * infrastructure graduation fee.
139
+ */
140
+ declare class OcapTokenFactoryGraduationEngine {
141
+ private readonly factories;
142
+ private readonly registeredTokenAddresses;
143
+ private readonly trustedVcIssuerDids;
144
+ private readonly consumedVcIds;
145
+ private readonly consumedMigrationEvidences;
146
+ private readonly ofacSet;
147
+ constructor(options: {
148
+ trustedVcIssuerDids: Iterable<string>;
149
+ ofacBlocklist?: Iterable<string>;
150
+ });
151
+ /**
152
+ * Registers and initializes an incubated `TokenFactory` on OCAP after validating its
153
+ * Functional Utility Charter, Verified Creator VC, Creator Vesting Cliff, and 0% Protocol Token Cut.
154
+ */
155
+ registerIncubatedTokenFactory(spec: IncubatedTokenFactorySpec, currentUnixTimestamp: number, statedb: Record<string, any>): Promise<IncubatedTokenFactoryRecord>;
156
+ /**
157
+ * Executes a bonding curve buy on an `ACTIVE` incubated `TokenFactory` inside an atomic `TransactionBlock`
158
+ * with `enforceZeroSum: true`.
159
+ *
160
+ * If the post-buy `reserveBalance >= graduationThreshold`, the factory atomically latches into
161
+ * `status = 'GRADUATING'` in the exact same transaction and computes the deterministic Base V4 Pool ID.
162
+ */
163
+ executeBondingCurveBuy(params: {
164
+ factoryAddress: string;
165
+ buyerDid: string;
166
+ reserveAmountIn: string;
167
+ tokensMintedOut: string;
168
+ currentBlockHeight: number;
169
+ ofacBlocklist?: Iterable<string>;
170
+ }, statedb: Record<string, any>): Promise<{
171
+ blockResult: TransactionBlockResult;
172
+ factory: IncubatedTokenFactoryRecord;
173
+ triggeredGraduation: boolean;
174
+ deterministicBaseV4PoolId?: string;
175
+ }>;
176
+ /**
177
+ * Finalizes cross-chain graduation (`GRADUATING -> GRADUATED`) upon verifying the `#1169` Rollup
178
+ * migration proof, LP permanent burn/lock (`0x...dead` or `LOCKED_IN_HOOK`), and flat `ABT` graduation fee.
179
+ */
180
+ finalizeV4Graduation(params: {
181
+ migrationProof: BaseV4GraduationMigrationProof;
182
+ currentBlockHeight: number;
183
+ }, statedb: Record<string, any>): Promise<IncubatedTokenFactoryRecord>;
184
+ getFactory(factoryAddress: string): IncubatedTokenFactoryRecord | undefined;
185
+ }
186
+ //#endregion
187
+ export { BaseV4GraduationMigrationProof, CANONICAL_LP_BURN_DEAD_ADDRESS, FunctionalUtilityCategory, FunctionalUtilityCharter, IncubatedTokenFactoryRecord, IncubatedTokenFactorySpec, MAX_MINT_RATIO_PER_RESERVE_UNIT, MIN_CREATOR_VESTING_CLIFF_BLOCKS, OcapTokenFactoryGraduationEngine, TokenFactoryGraduationStatus, VerifiedCreatorCredential, computeDeterministicV4GraduationPoolId };