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