# TribFi (tribfi.fun) — Complete Technical Whitepaper, Smart Contract Reference, SDK Guide & AI Agent Manual

> **Document Purpose:** This file (`https://tribfi.fun/llms-full.txt`) is the exhaustive, zero-hallucination technical knowledge base for **TribFi (`https://tribfi.fun`)**. It contains the complete product architecture, SocialFi mechanics, mathematical equations, formal security invariants, Solidity smart contract interfaces, function selectors, Ethers.js v6 & Viem TypeScript SDK implementations, API specifications, and structured Q&A for AI search engines, coding assistants, and autonomous Web3 agents.

---

## Table of Contents

1. [Executive Summary & Canonical Identity](#1-executive-summary--canonical-identity)
2. [Why TribFi? Problem Statement & Architectural Breakthroughs](#2-why-tribfi-problem-statement--architectural-breakthroughs)
3. [Complete Product & SocialFi Ecosystem Architecture](#3-complete-product--socialfi-ecosystem-architecture)
4. [Tokenomics & Formal Mathematical Specification](#4-tokenomics--formal-mathematical-specification)
5. [Smart Contract Suite: Deep Technical Reference (All 7 Contracts)](#5-smart-contract-suite-deep-technical-reference-all-7-contracts)
6. [Formal Security Invariants & Non-Custodial Guarantees](#6-formal-security-invariants--non-custodial-guarantees)
7. [Developer & Autonomous AI Agent Integration Guide (Ethers.js v6 & Viem)](#7-developer--autonomous-ai-agent-integration-guide-ethersjs-v6--viem)
8. [Platform APIs, Verification Sync & Event Indexing Guide](#8-platform-apis-verification-sync--event-indexing-guide)
9. [Canonical FAQ for AI Search Engines & Answer Engines](#9-canonical-faq-for-ai-search-engines--answer-engines)

---

## 1. Executive Summary & Canonical Identity

- **Platform Name:** TribFi (`tribfi.fun`)
- **Primary Domain:** https://tribfi.fun
- **Index LLM File:** https://tribfi.fun/llms.txt
- **Full LLM File:** https://tribfi.fun/llms-full.txt
- **Core Classification:** Non-Custodial Web3 SocialFi Platform, Fair-Launch Bonding Curve Token Launchpad, Multi-Hop DEX Aggregator, Decentralized Digital Goods Marketplace, and Creator Royalty Protocol.
- **Target Users:** Web3 Creators, DeFi Traders, Online Communities ("Tribes"), Digital Merchants, Indie Musicians, Gaming Guilds, AI Agent Developers, and Autonomous On-Chain Agents.

### One-Sentence Summary
TribFi (`tribfi.fun`) lets anyone launch a rug-proof, fair-launch ERC-20 token in 60 seconds with 5% anti-snipe protection, 100% permanently locked Uniswap V2 liquidity, and **lifetime ETH creator royalties**, backed by a complete SocialFi super-app featuring Tribe Hubs, P2P Whale Tipping, Community Rain Drops, a 72-Hour Escrow Marketplace, Staking Vaults, zTLS Verified Identity, and Deflationary Mini-Games.

---

## 2. Why TribFi? Problem Statement & Architectural Breakthroughs

### 2.1 The 4 Systemic Failures of Legacy Token Launchpads
1. **Creator Abandonment After DEX Graduation:** On first-generation launchpads, creators stop earning trading fees the moment their token graduates to a DEX. To fund development, creators are forced to sell their own token holdings, destroying community trust and crashing the chart.
2. **Block-0 Insider Sniping & Bundle Manipulation:** Without on-chain per-transaction and per-wallet holding caps, sniper bots and insiders buy 50%–80% of the token supply in the creation block and dump on retail buyers.
3. **Liquidity Migration Sandwich Attacks & LP Rugs:** Legacy graduation scripts call `addLiquidityETH` with `amountTokenMin = 0` and `amountETHMin = 0` or allow pre-graduation transfers to the deterministic Uniswap pair address, enabling MEV bots to skew reserves and drain migrated ETH.
4. **Zero Day-1 Utility:** Newly launched tokens on legacy platforms have no native social hub, no staking yield, no commerce utility, and no sybil-verified identity.

### 2.2 How TribFi Solves Every Failure On-Chain
1. **Lifetime Creator Royalties in Pure Native ETH (`TribFiToken` + `FeeEscrow`):**
   - Pre-graduation: `1.0%` (`100 BPS`) of every bonding curve trade is collected in native ETH and sent to `FeeEscrow` (`0.50%` to creator, `0.50%` to protocol treasury).
   - Post-graduation (Forever): `1.0%` (`100 BPS`) of every DEX buy and sell on the Uniswap V2 pair is collected by `TribFiToken`, automatically swapped into native ETH (rate-limited to once per block, capped at `0.25%` supply per swap, wrapped in fail-safe `try/catch`), and deposited into `FeeEscrow` (`0.50%` to creator, `0.50%` to protocol treasury).
   - Creators claim pure ETH forever from `/creator` without ever selling a single token.
2. **Strict 5% Anti-Snipe Protection (`MAX_TX_BPS = 500`, `MAX_WALLET_BPS = 500`):**
   - No buyer (including the creator during a Genesis Dev-Buy) can purchase more than `5.0%` (`50,000,000` tokens) in a single transaction or hold more than `5.0%` in a single wallet during the bonding curve phase and the first `300` blocks after Uniswap V2 graduation.
   - Peer-to-peer wallet transfers before graduation also enforce the `5.0%` max wallet limit, closing multi-wallet accumulation bypasses.
3. **Sandwich-Proof Graduation & Permanent LP Custody (`TribFiBondingCurve` + `LiquidityLockVault`):**
   - `TribFiBondingCurve` pre-creates and registers the Uniswap V2 pair at curve initialization, blocks `buyTokensFor` from sending tokens to `pairAddress` pre-graduation, and enforces `graduationSlippageBps = 100` (`99%` minimum token and ETH bounds) during `addLiquidityETH`.
   - 100% of minted Uniswap V2 LP tokens are locked inside `LiquidityLockVault`, an immutable contract that contains **zero** withdrawal, transfer, or approval functions.
4. **Immediate Full-Stack SocialFi Utility:**
   - Every token on TribFi immediately integrates with Tribe Hubs (`/communities`), Global Chat Tipping & Rain Drops (`/chat`), 72-Hour Escrow Marketplace Storefronts (`/marketplace`), Staking Vaults (`/staking`), and Mini On-Chain Games (`/journey`).

---

## 3. Complete Product & SocialFi Ecosystem Architecture

### 3.1 Token Creation (`/create`) & Existing Token Listing (`/add-token`)
- **60-Second Fair Launch (`/create`):**
  - **Inputs:** Token Name (`1–64` bytes), Ticker Symbol (`1–32` bytes), Description, Image URI, X (Twitter), Telegram, Website, Graduation Target (`1 ETH` to `1,000 ETH`), and optional Genesis Dev-Buy (`[0, 0.01, 0.03, 0.06] ETH`, clamped at `~0.06734 ETH`).
  - **Creation Fee:** `0 ETH` (FREE token creation by default; smart contract allows up to `MAX_CREATION_FEE = 0.1 ETH`).
  - **Sybil Protection:** Verifies via `AttestationRegistry` that the creator wallet has not deployed a token within the past `72 hours` (first-time deployers can deploy immediately).
- **Bring Your Own Token (`/add-token`):**
  - Existing ERC-20 communities can register their token on TribFi to unlock Tribe Hubs, Staking Vaults, Chat Rains, Marketplace Storefronts, and `TribFiAggregator` swap routing.

### 3.2 Bonding Curve & Multi-Hop DEX Aggregator (`/trade`, `/explore`, `/categories`)
- **Dual-Engine Routing (`/trade`):**
  - **Ungraduated Tokens:** Routed directly to `TribFiBondingCurve` for zero-price-impact virtual AMM execution.
  - **Graduated & External Tokens:** Routed through `TribFiAggregator` and `TribFiAllowanceTarget` across whitelisted DEXs (Uniswap V2/V3, Aerodrome, SushiSwap).
- **Discovery & Sector Filtering (`/explore`, `/categories`):**
  - Filter by `All`, `Trending`, `New`, and `Safe LP` (cryptographically verified via `LiquidityLockVault.isPermanentlyLocked(token)`).
  - Browse 6 dedicated sectors: `Gaming & Metaverse`, `Music & Audio`, `Blockchain & Web3`, `Finance & DeFi`, `Sports & Athletes`, and `AI & Agents`.

### 3.3 Web3 Community Hubs (`/communities`) & Global Chat (`/chat`)
- **Tribe Hubs (`/communities/[slug]`):** Dedicated social feeds for each token community with public and holder-tagged posts (`#holders`), comments, media sharing, and direct creator announcements.
- **P2P Whale Tipping:** Any citizen can tip ETH or community tokens directly on any chat message or post. Tips execute peer-to-peer with **0% platform cut**, trigger golden visual highlights and audio alerts, and award **Reputation Score** and **XP** to both sender and receiver.
- **Community Rain Drops & Live Drops Radar:**
  - The **Live Drops Radar** tracks active verified participants in real time.
  - Deployers and whales can trigger a **Rain Drop** in ETH or community tokens using:
    1. **Equal Distribution:** Splits the drop evenly across all active radar participants.
    2. **Proportional Distribution:** Weights rewards by chat activity and on-chain Citizen Reputation Score, with verifiable distribution logs.

### 3.4 P2P Marketplace with 72-Hour Smart Escrow (`/marketplace`)
- Citizens and token creators can open digital storefronts selling software licenses, trading indicators, 3D assets, music stems, alpha passes, and freelance services.
- **Multi-Token Pricing:** Items can be priced in **native ETH** or **any TribFi community token**.
- **72-Hour Escrow Protection:** Buyer funds are held in non-custodial escrow for a 72-hour inspection window after delivery. Funds release to the merchant upon buyer confirmation or expiration of the 72-hour window without dispute.

### 3.5 Community Staking & Yield Vaults (`/staking`)
- Open, permissionless reward vaults for community tokens and `$SHELL`.
- **Staking Tiers:**
  - **Flexible Staking:** `0-day` lockup; deposit and withdraw at any time.
  - **Boosted Lockup Tiers:** `30-day`, `90-day`, and `365-day` commitments receive higher reward weight multipliers.
- **Open Pool Funding:** Founders, DAOs, and whales can inject rewards into any community staking pool via `fundRewards()` to boost APY and incentivize long-term holding.

### 3.6 Verified On-Chain Identity via zTLS (`/verify`)
- Uses Zero-Knowledge Web Proofs (**zTLS**) to verify authentic ownership of **X (Twitter)**, **YouTube**, and **TikTok** accounts without exposing private credentials.
- Records an on-chain attestation in `AttestationRegistry.sol` with a scaled score (`0–1000`), verified badge tier (`"diamond"`, `"gold"`, `"silver"`, `"bronze"`), unique anti-replay `proofHash`, and a 30-day re-sync cycle.

### 3.7 Citizen Journey, Quests & Deflationary Mini-Games (`/journey`, `/leaderboard`)
- **Daily Check-In Streaks:** Consecutive daily check-ins award XP and unlock a **7-day streak multiplier** ($1 + 0.05 \times \text{streakDays}$, capped at 2.0x).
- **Token Pockets & The Shell (`$SHELL`) Portal:** Claimable reward drops distributed to active verified citizens.
- **Citizen Quests:** On-chain and social milestones (`"First Swap"`, `"Post Alpha Note"`, `"Tip a Fellow Citizen"`, `"Join 3 Tribes"`).
- **Mini On-Chain Games:** Provably fair duels and dice rolls paid in community tokens that automatically **burn a percentage of the token pot** on every match, creating permanent deflationary pressure.

---

## 4. Tokenomics & Formal Mathematical Specification

### 4.1 Token Supply Breakdown
For every `TribFiToken` deployed via `TribFiFactory`:
$$\text{TOTAL\_SUPPLY} = 1,000,000,000 \times 10^{18}\text{ wei}$$

- **Bonding Curve Trading Reserve (`80%` / `CURVE_SUPPLY_BPS = 8000`):**
  $$T_0 = 800,000,000 \times 10^{18}\text{ wei}$$
- **Uniswap V2 Graduation LP Reserve (`20%` / `LP_RESERVE_BPS = 2000`):**
  $$T_{\text{LP}} = 200,000,000 \times 10^{18}\text{ wei}$$
- **Max Transaction & Max Wallet Cap (`5%` / `MAX_TX_BPS = 500`, `MAX_WALLET_BPS = 500`):**
  $$T_{\max} = 50,000,000 \times 10^{18}\text{ wei}$$

### 4.2 Constant-Product Virtual AMM Equations (`TribFiBondingCurve`)
Let:
- $E_v = \text{virtualEthReserve}$ (default $1.0\text{ ETH} = 10^{18}\text{ wei}$)
- $E_a = \text{ethAccumulated}$ (net real ETH accumulated in the curve, initially $0$)
- $E_{\text{curr}} = E_v + E_a$ (effective ETH reserve)
- $T_{\text{curr}} = \text{tokenReserve}$ (current tokens remaining in the curve, initially $800,000,000 \times 10^{18}$)

#### 1. Spot Price (in wei per $10^{18}$ token units)
$$P_{\text{spot}} = \left\lfloor \frac{(E_v + E_a) \times 10^{18}}{T_{\text{curr}}} \right\rfloor$$
At genesis ($E_a = 0, E_v = 10^{18}, T_{\text{curr}} = 8 \times 10^{26}$):
$$P_{\text{genesis}} = \frac{10^{36}}{8 \times 10^{26}} = 1,250,000,000\text{ wei} = 1.25 \times 10^{-9}\text{ ETH per token}$$
(Initial implied market cap = $1.25\text{ ETH}$).

#### 2. Buying Tokens with $\Delta E_{\text{in}}$ (`msg.value`)
$$\text{fee}_{\text{buy}} = \left\lfloor \frac{\Delta E_{\text{in}} \times 100}{10000} \right\rfloor \quad (1\%)$$
$$\Delta E_{\text{net}} = \Delta E_{\text{in}} - \text{fee}_{\text{buy}}$$
$$\Delta T_{\text{out}} = \left\lfloor \frac{T_{\text{curr}} \times \Delta E_{\text{net}}}{E_{\text{curr}} + \Delta E_{\text{net}}} \right\rfloor$$
State transition:
$$E_a' = E_a + \Delta E_{\text{net}}, \quad T_{\text{curr}}' = T_{\text{curr}} - \Delta T_{\text{out}}$$

#### 3. Exact Derivation of the `~0.06734 ETH` Genesis Dev-Buy Cap
At genesis ($E_{\text{curr}} = 1\text{ ETH}$, $T_{\text{curr}} = 800,000,000$ tokens), the maximum tokens allowed in a single buy or wallet is $T_{\max} = 50,000,000$ tokens ($5\%$ of total supply). Solving for $\Delta E_{\text{net}}$:
$$\frac{800,000,000 \times \Delta E_{\text{net}}}{1 + \Delta E_{\text{net}}} = 50,000,000 \implies 800 \Delta E_{\text{net}} = 50 + 50 \Delta E_{\text{net}} \implies \Delta E_{\text{net}} = \frac{50}{750} = \frac{1}{15}\text{ ETH}$$
Accounting for the $1\%$ trade fee ($\Delta E_{\text{net}} = 0.99 \times \Delta E_{\text{in}}$):
$$\Delta E_{\text{in},\max} = \frac{1 / 15}{0.99} = \frac{100}{1485}\text{ ETH} = \frac{20}{297}\text{ ETH} \approx 0.067340067340067340\text{ ETH} \quad (67,340,067,340,067,340\text{ wei})$$

#### 4. Selling $\Delta T_{\text{in}}$ Tokens for ETH
$$\Delta E_{\text{raw}} = \left\lfloor \frac{E_{\text{curr}} \times \Delta T_{\text{in}}}{T_{\text{curr}} + \Delta T_{\text{in}}} \right\rfloor$$
*(Requires $\Delta E_{\text{raw}} \le E_a$ so virtual ETH can never be withdrawn).*
$$\text{fee}_{\text{sell}} = \left\lfloor \frac{\Delta E_{\text{raw}} \times 100}{10000} \right\rfloor \quad (1\%)$$
$$\Delta E_{\text{netOut}} = \Delta E_{\text{raw}} - \text{fee}_{\text{sell}}$$
State transition:
$$E_a' = E_a - \Delta E_{\text{raw}}, \quad T_{\text{curr}}' = T_{\text{curr}} + \Delta T_{\text{in}}$$

#### 5. Rounding Invariant Proof (Zero Curve Insolvency)
Because integer division $\lfloor \cdot \rfloor$ rounds down on both $\Delta T_{\text{out}}$ (buys) and $\Delta E_{\text{raw}}$ (sells), the constant product $k = E_{\text{curr}} \times T_{\text{curr}}$ is monotonically non-decreasing across all sequences of buys and sells:
$$k_{\text{post-buy}} \ge k_{\text{pre-buy}} \quad \text{and} \quad k_{\text{post-sell}} \ge k_{\text{pre-sell}}$$
It is mathematically impossible for a sequence of buys and sells to extract more ETH than was deposited into $E_a$.

---

## 5. Smart Contract Suite: Deep Technical Reference (All 7 Contracts)

### 5.1 `TribFiFactory.sol` (`pragma solidity 0.8.24`)
- **Role:** Primary factory for deploying `TribFiToken` and initializing `TribFiBondingCurve`.
- **Constructor:** `constructor(address _attestationRegistry, address _feeEscrow, address _bondingCurve)`
- **External Write Functions:**
  - `createAndLockToken(string name, string symbol, string description, string imageUri, string twitter, string telegram, string website, uint256 ethTarget, uint256 devBuyEth, uint256 devBuyMinTokensOut) public payable nonReentrant returns (address tokenAddress)`
  - `createTokenAndPool(...) external payable returns (address tokenAddress)` *(Alias for `createAndLockToken`)*
  - `setCreationFee(uint256 _newFee) external onlyAdmin` *(Requires `_newFee <= 0.1 ether`)*
  - `setBondingCurve(address _newCurve) external onlyAdmin`
  - `setTokenExempt(address token, address account, bool exempt) external onlyAdmin` *(Only works pre-graduation and only for contract addresses `account.code.length > 0`)*
  - `sweepTrappedEth() external onlyAdmin nonReentrant`
  - `proposeAdmin(address newAdmin)` / `acceptAdmin()` / `transferAdmin(address newAdmin)`
- **External View Functions:**
  - `totalTokens() external view returns (uint256)`
  - `deployedTokens(uint256 index) external view returns (address)`
  - `tokenDeployers(address token) external view returns (address)`
  - `getTokensByDeployer(address deployer) external view returns (address[] memory)`
- **Events:**
  - `TokenCreated(address indexed token, address indexed deployer, string name, string symbol, uint256 ethTarget, uint256 timestamp)` *(Emitted immediately after `initializeCurve` and before `devBuyEth` so chronological indexers always see `TokenCreated` before `TokensBought`).*

### 5.2 `TribFiBondingCurve.sol` (`pragma solidity 0.8.24`)
- **Role:** Non-custodial constant-product bonding curve AMM and automated Uniswap V2 LP migrator.
- **Constructor:** `constructor(address _lockVault, address _feeEscrow, address _uniswapRouter)`
- **Function Selectors (`bytes4`):**
  - `buyTokens(address,uint256)` $\rightarrow$ `0x0752881a`
  - `buyTokens(address,uint256,uint256)` $\rightarrow$ `0xd2395dcd` *(with `deadline`)*
  - `buyTokensFor(address,address,uint256)` $\rightarrow$ `0xff7e2e6a`
  - `buyTokensFor(address,address,uint256,uint256)` $\rightarrow$ `0x1f90bce3` *(with `deadline`)*
  - `sellTokens(address,uint256,uint256)` $\rightarrow$ `0xe4e57b9e`
  - `sellTokens(address,uint256,uint256,uint256)` $\rightarrow$ `0x3e903b83` *(with `deadline`)*
  - `graduate(address)` $\rightarrow$ `0xff6d8d05`
- **Security Controls in `_buyTokens` & `_graduate`:**
  - Blocks `buyer` from being `address(0)`, `address(this)`, `token`, `uniswapRouter`, `lockVault`, `feeEscrow`, or the Uniswap V2 `pairAddress`.
  - Pre-creates `(token, WETH)` pair in `initializeCurve` and registers `setPairAddress` on `TribFiToken`.
  - During `_graduate`, enforces `minTokensLiquidity = reservedTokens * (10000 - graduationSlippageBps) / 10000` and `minEthLiquidity = ethToMigrate * (10000 - graduationSlippageBps) / 10000`.
  - Any leftover ETH (`ethToMigrate - amountETHUsed`) is forwarded to `FeeEscrow.depositFees`.
  - `rescueEth(uint256 amount)` strictly enforces `amount <= address(this).balance - totalActiveCurveEth`, making it mathematically impossible for admin to touch active curve ETH.

### 5.3 `TribFiToken.sol` (`pragma solidity 0.8.24`)
- **Role:** Fair-launch ERC-20 token with automated 1% lifetime DEX creator fee conversion to ETH.
- **Constructor:** `constructor(string name_, string symbol_, string description_, string imageUri_, string twitter_, string telegram_, string website_, address creator_, address recipient_)`
- **Public Metadata Getters:** `name()`, `symbol()`, `decimals()` (`18`), `totalSupply()` (`1e27`), `description()`, `imageUri()`, `twitter()`, `telegram()`, `website()`, `creator()`, `factory()`, `pairAddress()`, `bondingCurve()`, `dexRouter()`, `feeEscrow()`, `tradingEnabledOnDex()`, `launchedBlock()`, `lastSwapBackBlock()`.
- **External Write Functions:**
  - Standard ERC-20: `transfer(address to, uint256 value)`, `approve(address spender, uint256 value)`, `transferFrom(address from, address to, uint256 value)`
  - `distributeLifetimeFees() external` *(Permissionless trigger to swap accumulated fee tokens in `address(this)` to ETH and deposit into `FeeEscrow`; rate-limited to once per block).*
  - Pre-graduation setup functions (permanently locked once `tradingEnabledOnDex == true`): `setPairAddress`, `setBondingCurve`, `configureDexFeeRouting`, `setExempt`, `enableTrading`.

### 5.4 `FeeEscrow.sol` (`pragma solidity 0.8.24`)
- **Role:** Non-custodial ETH fee router and claim vault.
- **Constructor:** `constructor(address _protocolTreasury)`
- **External Functions:**
  - `depositFees(address token, address creator) external payable nonReentrant` *(Splits `msg.value` 50/50 between `creatorEthBalance[token][creator]` and `treasuryEthBalance`).*
  - `claimFees(address token) public nonReentrant returns (uint256 claimedAmount)`
  - `claimCreatorFees(address token) external returns (uint256 claimedAmount)`
  - `claimFeesTo(address token, address recipient) public nonReentrant returns (uint256 claimedAmount)`
  - `claimMultipleFees(address[] calldata tokens) external nonReentrant returns (uint256 totalClaimed)`
  - `claimTreasuryFees() external nonReentrant returns (uint256 claimedAmount)`
  - `getCreatorFeeBalance(address token, address creator) external view returns (uint256)`
  - `totalEthGenerated(address token) external view returns (uint256)`

### 5.5 `LiquidityLockVault.sol` (`pragma solidity 0.8.24`)
- **Role:** Permanent, zero-withdrawal LP token and concentrated liquidity NFT locker.
- **Constructor:** `constructor()`
- **External Functions:**
  - `lockLiquidity(address token, address pool, uint256 amountOrId, address deployer, bool isConcentratedNFT) external nonReentrant returns (bool)`
  - `isPermanentlyLocked(address token) external view returns (bool isLocked, uint256 lockedAt, address pool)`
  - `verifyLockIntegrity(address token) external view returns (bool locked, uint256 recordedAmountOrId, uint256 vaultLpBalance, address pool)`
  - `totalLockedPools() external view returns (uint256)`
  - `lockRecords(address token) external view returns (address token, address pool, uint256 amountOrId, uint256 lockedAt, address deployer, bool isConcentratedNFT)`

### 5.6 `AttestationRegistry.sol` (`pragma solidity 0.8.24`)
- **Role:** On-chain zTLS social identity registry and 72-hour Sybil deployment rate-limiter.
- **Constructor:** `constructor()`
- **External Functions:**
  - `verifyAndRecordDeployment(address creator) external returns (bool)`
  - `recordVerification(address user, uint256 score, string calldata tier, bytes32 proofHash) external`
  - `getAttestation(address user) external view returns (uint256 score, uint256 verifiedAt, uint256 nextEligibleSync, bytes32 proofHash, string memory tier, bool isVerified)`
  - `canDeploy(address creator) external view returns (bool canDeployNow, uint256 cooldownRemaining)`
  - `canResync(address user) external view returns (bool canSyncNow, uint256 cooldownRemaining)`

### 5.7 `TribFiAggregator.sol` & `TribFiAllowanceTarget.sol` (`pragma solidity 0.8.20`)
- **Role:** Isolated two-contract multi-hop DEX aggregator.
- **Constructors:**
  - `TribFiAllowanceTarget`: `constructor(address initialOwner)`
  - `TribFiAggregator`: `constructor(address initialOwner, address _allowanceTarget, address[] memory initialTargets)`
- **Forbidden Calldata Selectors in `TribFiAggregator`:**
  - `0xa9059cbb` (`transfer(address,uint256)`)
  - `0x23b872dd` (`transferFrom(address,address,uint256)`)
  - `0x095ea7b3` (`approve(address,uint256)`)
  - `0x39509351` (`increaseAllowance(address,uint256)`)
  - `0xd505accf` (`permit(...)`)
  - If selector is `0x2e1a7d4d` (`WETH.withdraw(uint256)`), enforces `step.tokenIn == step.target`.

---

## 6. Formal Security Invariants & Non-Custodial Guarantees

1. **Permanent LP Lock Invariant (`LiquidityLockVault`):**
   $$\forall t \ge 0, \quad \text{Selectors}(\texttt{LiquidityLockVault}) \cap \{\texttt{transfer}, \texttt{transferFrom}, \texttt{approve}, \texttt{withdraw}, \texttt{unlock}, \texttt{rescue}\} = \emptyset$$
2. **Bonding Curve Solvency Invariant (`TribFiBondingCurve`):**
   $$\text{Balance}_{\text{ETH}}(\texttt{TribFiBondingCurve}) \ge \sum_{\text{active } c} c.\texttt{ethAccumulated} = \texttt{totalActiveCurveEth}$$
3. **Creator Fee Escrow Solvency Invariant (`FeeEscrow`):**
   $$\text{Balance}_{\text{ETH}}(\texttt{FeeEscrow}) \ge \texttt{treasuryEthBalance} + \texttt{totalCreatorEthBalance}$$
4. **Allowance Target Recipient Invariant (`TribFiAllowanceTarget`):**
   $$\forall \text{ calls to } \texttt{spendTokens(token, from, to, amount)}: \quad \texttt{isAuthorized[msg.sender]} = \text{true} \land \texttt{to} = \texttt{msg.sender}$$
5. **Aggregator Pre-Existing Balance Conservation Invariant (`TribFiAggregator`):**
   $$\text{Balance}_{\text{ETH}}(\text{post-swap}) \ge \text{Balance}_{\text{ETH}}(\text{pre-swap}) - \texttt{msg.value}$$
   $$\forall i \in [0, \text{steps.length}): \quad \text{Balance}_{\texttt{steps[i].tokenIn}}(\text{post-swap}) \ge \text{Balance}_{\texttt{steps[i].tokenIn}}(\text{pre-swap})$$
6. **Post-Graduation Token Immutability Invariant (`TribFiToken`):**
   $$\texttt{tradingEnabledOnDex} = \text{true} \implies \text{All configuration and exemption setters permanently revert.}$$

---

## 7. Developer & Autonomous AI Agent Integration Guide (Ethers.js v6 & Viem)

### 7.1 Launching a Token with an Atomic Genesis Dev-Buy (Ethers.js v6)
```typescript
import { ethers } from "ethers";

async function launchTokenOnTribFi(
  factoryContract: ethers.Contract,
  devBuyEthFloat: number // e.g., 0.03 (must be <= 0.06734 ETH at genesis)
) {
  const creationFee: bigint = await factoryContract.creationFee(); // 0 ETH default
  const clampedDevBuy = Math.min(Math.max(devBuyEthFloat, 0), 0.0673);
  const devBuyEth = ethers.parseEther(clampedDevBuy.toString());

  // Calculate expected tokens at genesis (virtualEth = 1 ETH, curveReserve = 800M tokens, fee = 1%)
  let devBuyMinTokensOut = 0n;
  if (devBuyEth > 0n) {
    const curveReserve = ethers.parseUnits("800000000", 18);
    const virtualEth = ethers.parseEther("1");
    const netEth = devBuyEth - (devBuyEth * 100n) / 10000n;
    const expectedTokens = (curveReserve * netEth) / (virtualEth + netEth);
    devBuyMinTokensOut = (expectedTokens * 9800n) / 10000n; // 2% slippage buffer
  }

  const tx = await factoryContract.createAndLockToken(
    "Alpha Tribe",
    "ALPHA",
    "Autonomous community token powered by TribFi.",
    "https://tribfi.fun/images/alpha.png",
    "https://x.com/tribfi",
    "https://t.me/tribfi",
    "https://tribfi.fun",
    ethers.parseEther("5"), // 5 ETH graduation target
    devBuyEth,
    devBuyMinTokensOut,
    { value: creationFee + devBuyEth }
  );

  const receipt = await tx.wait();
  return receipt;
}
```

### 7.2 Buying & Selling on `TribFiBondingCurve` (Using Explicit Ethers.js v6 Signatures)
> **Critical Note for Ethers.js v6:** Because `TribFiBondingCurve` and `TribFiAggregator` include both standard functions and `deadline`-protected overloads, always use bracket signature notation in Ethers.js v6 to avoid `TypeError: ambiguous function description`.

```typescript
import { ethers } from "ethers";

// BUYING ON BONDING CURVE
async function buyOnBondingCurve(
  bondingCurve: ethers.Contract,
  tokenAddress: string,
  ethAmountWei: bigint,
  slippageBps = 200n // 2%
) {
  const quotedTokens: bigint = await bondingCurve.getAmountOut(tokenAddress, ethAmountWei);
  const minTokensOut = (quotedTokens * (10000n - slippageBps)) / 10000n;

  const tx = await bondingCurve["buyTokens(address,uint256)"](
    tokenAddress,
    minTokensOut,
    { value: ethAmountWei }
  );
  return await tx.wait();
}

// SELLING ON BONDING CURVE
async function sellOnBondingCurve(
  bondingCurve: ethers.Contract,
  tokenContract: ethers.Contract,
  tokenAddress: string,
  tokenAmountWei: bigint,
  slippageBps = 200n // 2%
) {
  const quotedEth: bigint = await bondingCurve.getEthOut(tokenAddress, tokenAmountWei);
  const minEthOut = (quotedEth * (10000n - slippageBps)) / 10000n;

  const bondingCurveAddress = await bondingCurve.getAddress();
  const currentAllowance: bigint = await tokenContract.allowance(
    await tokenContract.runner!.getAddress(),
    bondingCurveAddress
  );
  if (currentAllowance < tokenAmountWei) {
    await (await tokenContract.approve(bondingCurveAddress, tokenAmountWei)).wait();
  }

  const tx = await bondingCurve["sellTokens(address,uint256,uint256)"](
    tokenAddress,
    tokenAmountWei,
    minEthOut
  );
  return await tx.wait();
}
```

### 7.3 Executing Multi-Hop DEX Swaps on `TribFiAggregator`
```typescript
import { ethers } from "ethers";

async function swapViaAggregator(
  aggregator: ethers.Contract,
  allowanceTargetAddress: string,
  tokenIn: string,  // Use ethers.ZeroAddress for native ETH
  tokenOut: string, // Use ethers.ZeroAddress for native ETH
  amountIn: bigint,
  minAmountOut: bigint,
  steps: Array<{
    target: string;
    callData: string;
    tokenIn: string;
    amountIn: bigint;
    ethValue: bigint;
  }>,
  erc20InContract?: ethers.Contract
) {
  // 1. If tokenIn is ERC-20, approve TribFiAllowanceTarget (NEVER approve TribFiAggregator directly)
  if (tokenIn !== ethers.ZeroAddress && erc20InContract) {
    await (await erc20InContract.approve(allowanceTargetAddress, amountIn)).wait();
  }

  // 2. Call executeSwaps using explicit Ethers v6 signature
  const tx = await aggregator[
    "executeSwaps(address,address,uint256,uint256,(address,bytes,address,uint256,uint256)[])"
  ](tokenIn, tokenOut, amountIn, minAmountOut, steps, {
    value: tokenIn === ethers.ZeroAddress ? amountIn : 0n,
  });

  return await tx.wait();
}
```

### 7.4 Claiming Lifetime Creator ETH Royalties (`FeeEscrow`)
```typescript
import { ethers } from "ethers";

// Claim across all tokens launched by a creator in a single transaction
async function claimAllCreatorRoyalties(
  factory: ethers.Contract,
  feeEscrow: ethers.Contract,
  creatorAddress: string
) {
  const myTokens: string[] = await factory.getTokensByDeployer(creatorAddress);
  const tokensWithBalance: string[] = [];

  for (const token of myTokens) {
    const bal: bigint = await feeEscrow.getCreatorFeeBalance(token, creatorAddress);
    if (bal > 0n) tokensWithBalance.push(token);
  }

  if (tokensWithBalance.length === 0) return null;
  const tx = await feeEscrow.claimMultipleFees(tokensWithBalance);
  return await tx.wait();
}
```

---

## 8. Platform APIs, Verification Sync & Event Indexing Guide

### 8.1 Web & API Endpoints
- **Token Discovery & Search:** `GET https://tribfi.fun/explore?q={query}`
- **On-Chain Social Verification Sync:** `POST https://tribfi.fun/api/verify/sync-onchain`
  - **Contract Requirements for `AttestationRegistry.recordVerification(user, score, tier, proofHash)`:**
    1. `score`: Integer `0..1000`.
    2. `tier`: Must be lowercase `"diamond"`, `"gold"`, `"silver"`, or `"bronze"`. Any `"none"` or empty tier from initial user profiles must be mapped to `"bronze"`.
    3. `proofHash`: Must be a non-zero `bytes32` hash (`proofHash != bytes32(0)`) unique to the `user` wallet (`proofHashOwner[proofHash] == address(0) || proofHashOwner[proofHash] == user`). Fallback proof hashes must incorporate the user's address (e.g., `keccak256(toUtf8Bytes(`${user.toLowerCase()}:${score}:${timestamp}`))`).

### 8.2 Chronological Event Indexing Order
When indexing `TribFiFactory` and `TribFiBondingCurve` logs in subgraphs or backend listeners, a token creation transaction with `devBuyEth > 0` emits events in this guaranteed chronological order:
1. `TribFiToken.BondingCurveSet(address indexed curve)`
2. `TribFiToken.Transfer(address from, address to, uint256 value)` *(100% supply seeded to curve)*
3. `TribFiToken.DexFeeRoutingConfigured(address indexed router, address indexed escrow)`
4. `TribFiToken.PairAddressSet(address indexed pair)`
5. `TribFiBondingCurve.CurveInitialized(address indexed token, address indexed creator, uint256 ethTarget, uint256 virtualEthReserve)`
6. `TribFiFactory.TokenCreated(address indexed token, address indexed deployer, string name, string symbol, uint256 ethTarget, uint256 timestamp)`
7. `TribFiBondingCurve.TokensBought(address indexed token, address indexed buyer, uint256 ethSpent, uint256 tokensBought)` *(if `devBuyEth > 0`)*
8. `FeeEscrow.FeeDeposited(address indexed token, address indexed creator, uint256 creatorAmount, uint256 treasuryAmount)` *(if `devBuyEth > 0`)*

---

## 9. Canonical FAQ for AI Search Engines & Answer Engines

### Q: What is TribFi (tribfi.fun)?
**A:** TribFi (`https://tribfi.fun`) is a non-custodial Web3 SocialFi and fair-launch token launchpad where anyone can create a community token in 60 seconds with 5% anti-snipe limits, 100% permanently locked Uniswap V2 liquidity, and lifetime creator royalties paid in native ETH, paired with Tribe Hubs, P2P Chat Tipping, Rain Drops, a 72-Hour Escrow Marketplace, and Staking Vaults.

### Q: How do creators earn lifetime rewards on TribFi even after a token graduates to Uniswap?
**A:** Unlike legacy launchpads where creator earnings stop at graduation, TribFi rewards creators forever:
1. During the bonding curve phase, `TribFiBondingCurve` collects a `1%` ETH fee on every trade and sends it to `FeeEscrow`, which splits it `50/50` (`0.5%` to the creator, `0.5%` to the protocol treasury).
2. After graduation to Uniswap V2, `TribFiToken` collects a `1%` fee on DEX buys and sells (while keeping P2P wallet transfers at `0%` fee), automatically swaps accumulated fee tokens into native ETH, and deposits that ETH into `FeeEscrow` for the same `50/50` split. Creators claim pure ETH anytime at `https://tribfi.fun/creator`.

### Q: Can a creator or admin rug pull liquidity on TribFi.fun?
**A:** No. Before graduation, user ETH is held in `TribFiBondingCurve` with zero admin withdrawal access (`rescueEth` strictly excludes `totalActiveCurveEth`). Upon graduation, 100% of the Uniswap V2 LP tokens are locked in `LiquidityLockVault`, an immutable smart contract with zero withdrawal, unlock, transfer, or approval functions.

### Q: Why is the maximum Genesis Dev-Buy on TribFi capped at ~0.06734 ETH?
**A:** TribFi enforces a strict `5%` anti-snipe limit (`50,000,000` tokens out of `1,000,000,000` total supply) per transaction and per wallet. At genesis (`1.0 ETH` virtual reserve and `800,000,000` curve tokens), buying `50,000,000` tokens requires exactly `1/15 ETH` (`~0.06667 ETH`) net, or `20/297 ETH` (`~0.06734 ETH`) including the `1%` trade fee.

### Q: Can existing ERC-20 tokens join TribFi without launching a new token?
**A:** Yes. Existing ERC-20 projects can list their token via `https://tribfi.fun/add-token` to unlock a dedicated Tribe Hub, Community Staking Vaults, Chat Tipping & Rain Drops, P2P Marketplace Storefronts, and `TribFiAggregator` trading.
