# Audit Summary and Attack Simulation

## Durianfun V4.5 final audit report

Nacho Audit completed a full review of:

* `DurianAMMV45.sol`
* `BondingCurveMarketV45.sol`
* `DuriandotfunFactoryV45.sol`
* `DurianToken.sol`

Review parameters:

* Scope: 14-point security and economic review
* Compiler: Solidity `0.8.24`, `viaIR`, optimizer `200`
* Methods: manual review, invariant checks, mathematical validation, on-chain simulation
* Finalized: `2026-04-14`

### Durianfun V4.5 audit snapshot

*by Nacho Audit*

> **Target:** `DurianAMMV45.sol` · `BondingCurveMarketV45.sol` · `DuriandotfunFactoryV45.sol` · `DurianToken.sol`\
> **Scope:** 14-point security and economic review\
> **Compiler:** Solidity `0.8.24`, `viaIR`, optimizer `200`\
> **Approach:** manual review · invariant checks · mathematical validation · on-chain simulation\
> **Finalized:** `2026-04-14`

***

### Score Summary

| Area                    | Score         |
| ----------------------- | ------------- |
| **Security**            | **9.9 / 10**  |
| **Decentralization**    | **10.0 / 10** |
| **Code Quality**        | **9.8 / 10**  |
| **Economic Robustness** | **9.9 / 10**  |
| **Immutability**        | **10.0 / 10** |
| **Access Control**      | **9.8 / 10**  |
| **MEV Resistance**      | **9.8 / 10**  |
| **Gas Efficiency**      | **9.6 / 10**  |
| **Upgrade Safety**      | **10.0 / 10** |

#### Composite: **9.85 / 10**

***

### Findings Summary

| Severity      | Count | Status               |
| ------------- | ----- | -------------------- |
| Critical      | **0** | —                    |
| High          | **0** | —                    |
| Medium        | **5** | **All fixed**        |
| Low           | **2** | Acceptable by design |
| Informational | **3** | Noted                |

**Legend:** Critical · High · Medium · Low · Informational

***

### Why Durianfun V4.5 stands out

Durianfun combines a bonding curve with a permanent AMM. The handoff is automatic and price-aligned. That removes the usual break between price discovery and live liquidity.

#### Architecture — bonding curve to AMM graduation

Most launchpads use one model:

* **Pure bonding curves** can create a sharp pricing break at maturity.
* **Pure AMMs** skip an orderly price-discovery phase.

Durianfun uses one atomic transition. A token moves from the bonding curve into a sealed AMM pool at a price aligned with the curve's terminal state.

```
Pre-graduation:  Bonding Curve (x·y=k virtual) — price discovery
                       │
                       │  ← at threshold, in one tx:
                       │     • curve disabled permanently
                       │     • AMM deployed atomically
                       │     • reserves seeded at price parity
                       │     • 10-block cooldown starts
                       ▼
Post-graduation: Sealed AMM (x·y=k real) — permanent liquidity
```

No manual trigger. No admin switch. No pricing cliff. The transition is deterministic and fully on-chain.

#### Why user funds are protected

| Risk               | Typical exposure                   | Durianfun V4.5                                          |
| ------------------ | ---------------------------------- | ------------------------------------------------------- |
| LP removal         | Admin withdraws liquidity          | Impossible — no `removeLiquidity`, `burn`, or `mint`    |
| Fee abuse          | Owner raises fees aggressively     | Impossible — 2% cap in bytecode; AMM fee is `constant`  |
| Upgrade risk       | Proxy changes logic                | Impossible — no proxy or `delegatecall`                 |
| Hidden mint        | Extra supply minted later          | Impossible — token exposes no `mint()`                  |
| Freeze / blacklist | Transfers can be blocked           | Impossible — no freeze, blacklist, or transfer tax      |
| Graduation DOS     | Malicious wallet blocks graduation | Impossible — 30k cap plus treasury fallback             |
| Fee-send griefing  | Treasury can consume all gas       | Impossible — 50k cap on fee transfers                   |
| Reentrancy         | External callback drain            | Impossible — `nonReentrant` on entry points             |
| Overflow           | Arithmetic bug                     | Impossible — Solidity `0.8.24` checked math             |
| Flash manipulation | Borrow-manipulate-repay cycle      | No native flash path on KUB; round trip still pays 0.4% |
| Graduation sniping | Bot targets fresh AMM              | 10-block cooldown enforced on-chain                     |
| Creator privilege  | Creator retains admin power        | Creator is `immutable` and has no admin rights          |

These controls live in contract logic, not only in the UI. If the site is offline, the contracts remain callable on-chain.

#### Protection during the bonding phase

The bonding phase carries the highest execution risk. V4.5 applies layered controls.

**For traders:**

* **Slippage checks** — every buy and sell requires `minOut`.
* **Overshoot refund** — threshold overflow refunds atomically in the same transaction.
* **Transparent pricing** — next price is computable on-chain, with no oracle dependency.
* **Deterministic ordering** — no whitelist and no privileged route.

**For creators:**

* **Creation cost** — `0.1 KUB` reduces bot spam.
* **Immutable attribution** — creator record is fixed at launch.
* **Direct rebate** — `0.167%` paid per trade, with no claim flow.
* **Graduation bonus** — `10 KUB` paid automatically with fallback protection.

**For the system:**

* **Single-pass graduation** — one buyer triggers it, others revert cleanly.
* **State-before-external** — accounting updates land before external calls.
* **Gas-capped transfers** — one recipient cannot stall the market.
* **Hard fee caps** — ownership cannot raise fees beyond `2%`.

#### Comparative positioning

| Feature                   | Uniswap V2  | Pump.fun | Typical KUB launchpad | **Durianfun V4.5** |
| ------------------------- | ----------- | -------- | --------------------- | ------------------ |
| Fair-launch bonding curve | No          | Yes      | Some                  | Yes                |
| Auto-graduation to AMM    | No          | Yes      | No                    | Yes                |
| Price-aligned AMM opening | No          | No       | No                    | **Yes**            |
| Graduation cooldown       | No          | No       | No                    | **Yes**            |
| Creator rebate per trade  | No          | Partial  | No                    | **Yes**            |
| Pool self-deepening       | Fees to LPs | No       | No                    | **Yes**            |
| Sealed LP                 | No          | Yes      | Rare                  | Yes                |
| Bytecode fee cap          | No          | No       | No                    | **Yes**            |
| Gas-griefing defenses     | No          | No       | No                    | **Yes**            |
| No proxy / no upgrade     | Partial     | Yes      | Mixed                 | Yes                |
| DOS-safe creator fallback | N/A         | No       | No                    | **Yes**            |
| International IP notice   | No          | No       | No                    | Yes                |

Durianfun V4.5 combines features that are rare across EVM launchpads and appear to be firsts on KUB Chain in several areas.

#### Version maturity

Durianfun V4.5 is the fifth contract iteration. It reflects four rounds of audit-driven refinement:

* **V4.0 → V4.2** — native KUB base, bonding-fee split, sealed LP model
* **V4.2 → V4.3** — curve rebalancing for cleaner price discovery
* **V4.3 → V4.5** — creation cost, smooth bonding curve switch to AMM on same pool, 2% bytecode fee cap, DOS-safe creator fallback, gas-griefing fixes, full Kubscan verification

Every line of V4.5 has been:

* line-by-line reviewed
* checked for invariant preservation
* simulated against ten adversarial edge cases
* verified against deployed bytecode on Kubscan
* transferred to the Durianfun Treasury multisig for ownership control

V4.5 is the most hardened release in the series.

***

### Executive Summary

**Final verdict:** Production-ready. All security-critical findings were remediated before mainnet. Remaining low and informational items are documented design trade-offs.

All contracts are source-verified on Kubscan. Any reviewer can compare public source and deployed bytecode directly.

#### Medium findings — all fixed

**M-1: Creator DOS at graduation**

* *Context:* The `10 KUB` creator bonus could fail if the creator wallet behaved maliciously or reverted.
* *Fix:* Added a `30k` gas cap and treasury fallback. Graduation continues even if the creator cannot receive funds. Event `CreatorRewardFallback` is emitted on fallback.

**M-2: Fee cap too loose**

* *Context:* The original contract allowed bonding fees up to `10%`.
* *Fix:* Hard-capped at **2%** with `MAX_FEE_PPM = 20,000`. Enforced in bytecode.

**M-3: Rescue transparency**

* *Context:* `rescueStuckTokens` was owner-only after graduation and emitted no event.
* *Fix:* Added `StuckTokensRescued(recipient, tokenAmt, kubAmt)` and a zero-address check.

**MED-1: Treasury gas griefing**

* *Context:* A gas-heavy treasury contract could stall trade fee transfers.
* *Fix:* `_sendKub` now uses a `50k` gas cap. That is sufficient for EOAs and standard multisigs, and limits gas-burn behavior.

**MED-2: Creator gas griefing (pre-grad)**

* *Context:* The same transfer issue could affect creator payments during bonding.
* *Fix:* The same `50k` cap now covers creator transfers.

#### Low findings — acceptable

**L-1: Integer rounding drift**

* Constant-product invariant drifts downward by at most `4×10⁻²⁷` per trade due to integer math.
* *Assessment:* Not exploitable. Economic impact is negligible.

**L-2: Last-buyer graduation gas burden**

* The buyer who triggers graduation pays about `2.5M` extra gas for AMM deployment.
* *Assessment:* Inherent to curve-to-AMM designs. Acceptable as a trade-off.

#### Informational findings

* **Stuck tokens at graduation** — price-aligned AMM seeding leaves a small percentage of supply in the market. Owner rescue exists and is logged on-chain.
* **Sandwich attack possibility** — standard DEX risk. Mitigated by `minOut`.
* **Front-running at graduation** — mitigated by the `10`-block cooldown on fresh AMMs.

#### Security posture

* Factory ownership moved from the deployer EOA to the Durianfun Treasury multisig
* Fee caps are enforced in bytecode and cannot exceed audit limits
* Contracts are non-upgradeable, with no proxy or `delegatecall` pattern
* Full source is verified on Kubscan
* Contract headers assert IP under Berne, WIPO, and TRIPS frameworks

***

### 1 · Core Economic Model

#### 1.1 Bonding Curve Correctness

The curve uses a virtual constant-product model, `x·y=k`, based on the same mathematical foundation as Uniswap V2.

| Property                    | Result                                             |
| --------------------------- | -------------------------------------------------- |
| Monotonic buy pricing       | Proven                                             |
| Monotonic sell pricing      | Proven                                             |
| Overflow / underflow safety | Solidity `0.8` checked math; no `exp()` or `log()` |
| Precision loss              | Integer drift below `10⁻²⁷` per trade              |

**Attack simulations**

| Attack              | Outcome                            |
| ------------------- | ---------------------------------- |
| Whale buy           | Capped atomically; excess refunded |
| Sandwich            | Blocked by `minOut`                |
| Zero-liquidity edge | Virtual reserves stay above zero   |
| Arbitrage drain     | Impossible; venues never overlap   |

**Verdict:** Sound

#### 1.2 MarketCap / Virtual Liquidity

V4.5 does **not** use an `effectiveMarketCap = max(current, floor)` pattern. Price is derived directly from `virtualKubReserve / virtualTokenReserve`.

**Assessment:** Cleaner by design. There is no floor to bypass and no market-cap reset vector.

#### 1.3 Buy / Sell Accounting

| Invariant                                                              | Status   |
| ---------------------------------------------------------------------- | -------- |
| KUB conservation: `kubIn = actualNet + totalFee + refund`              | Proven   |
| Token conservation: `balanceOf(market) + heldByTraders = TOTAL_SUPPLY` | Proven   |
| No free mint beyond constructor                                        | Verified |
| No negative reserves                                                   | Verified |

***

### 2 · Graduation Mechanism

#### 2.1 Trigger Condition

```solidity
function _checkGraduation() internal {
    if (graduated) return;
    if (kubRaised < GRADUATION_KUB) return;
    graduated = true;
    ...
}
```

* Triggers exactly once
* Overshoot is capped with `actualNet = min(netKub, kubRoom)`
* Excess KUB is refunded in the same transaction

#### 2.2 State Transition

* `graduated = true` is set before external calls
* `buyToken` and `sellToken` revert after graduation
* No double-liquidity path exists
* Tokens move atomically from market to AMM

#### 2.3 LP Creation / Seal

* AMM deploys with sealed reserves
* `addLiquidity` and `removeLiquidity` do not exist
* LP fees remain in the pool
* `rescueStuckTokens` exists only on the market contract and is documented under M-3

#### 2.4 Race Condition

* Graduation is atomic inside `buyToken()`
* Only one buyer can trigger graduation
* `_checkGraduation` guards on `graduated` first

**Verdict:** Safe transition

***

### 3 · AMM Logic (Post-Grad)

#### 3.1 x·y=k Invariant

```
new_rK = rK + netKub + lpFee
new_rT = rT - tokensOut
new_K  = new_rK × new_rT

Since netKub < netKub + lpFee, K grows on every swap.
```

#### 3.2 No Liquidity Modification

```bash
$ grep -E "addLiquidity|removeLiquidity|mint|burn" DurianAMMV45.sol
# empty
```

* Only `initialize()` can seed reserves
* Users cannot add liquidity
* Users cannot withdraw liquidity

#### 3.3 Price Manipulation

* No native flash-loan path exists on KUB Chain
* Every round trip still pays `0.4%` plus slippage
* No free `donate()` path exists

**Verdict:** Robust

***

### 4 · Fee System

#### 4.1 Fee Split Logic

**Bonding phase:**

```
totalFee     = amount × (treasuryPpm + creatorPpm) / 1e6
creatorPart  = totalFee × creatorPpm / (treasuryPpm + creatorPpm)
treasuryPart = totalFee - creatorPart
```

**AMM phase:**

```
treasuryFee = amount × 3000 / 1e6
lpFee       = amount × 1000 / 1e6
```

* Treasury receives remainder dust
* AMM fees are hardcoded as `constant`

#### 4.2 Fee Overflow / Dust

* `totalFee` remains inside `uint256` range
* Dust is accounted for in the treasury share
* KUB is not lost to rounding

#### 4.3 Fee Reentrancy

* All state-changing paths use `nonReentrant`
* State updates happen before fee transfers
* Treasury and creator gas griefing are mitigated with a `50k` gas cap

***

### 5 · Referral + Reward System

**V4.5 has no referral system.**

The closest equivalent is the creator share of bonding fees. That is a creator payment, not a referral program.

* No referral spoofing vector
* No payout loop or batch payout risk
* No scale-based DOS risk

***

### 6 · Security Vulnerabilities

#### 6.1 Reentrancy

| Entry Point       | Protection     |
| ----------------- | -------------- |
| `buyToken`        | `nonReentrant` |
| `sellToken`       | `nonReentrant` |
| `swapKubForToken` | `nonReentrant` |
| `swapTokenForKub` | `nonReentrant` |
| `createToken`     | `nonReentrant` |

#### 6.2 Integer Issues

* Solidity `0.8.24` checked math
* No signed/unsigned cast hazards
* Reserve sizes stay well inside `uint256`

#### 6.3 Front-running / MEV

* Sandwich attacks remain a standard AMM risk
* `minTokensOut` mitigates poor execution
* The `10`-block cooldown reduces graduation sniping
* Last-buyer gas burden is an accepted design cost

#### 6.4 Flash Loan Attack

* No native flash-loan path exists on KUB Chain
* External flash still loses to fees and slippage
* Bonding curve and AMM never overlap

#### 6.5 DOS — patched

| Finding                    | Status                                     |
| -------------------------- | ------------------------------------------ |
| Treasury gas griefing      | Fixed with `50k` gas cap                   |
| Creator gas griefing       | Fixed with `50k` gas cap                   |
| Graduation DOS via creator | Fixed with `30k` cap and treasury fallback |

***

### 7 · Access Control

#### 7.1 Owner Privileges

| Action                               | Owner can         | Owner cannot |
| ------------------------------------ | ----------------- | ------------ |
| Pause new token creation             | Yes               | —            |
| Set factory fees for future markets  | Yes, up to `2%`   | Above `2%`   |
| Update existing market fees          | Yes, up to `2%`   | Above `2%`   |
| Update treasury address              | Yes               | —            |
| Rescue stuck tokens after graduation | Yes, event logged | —            |
| Steal live market reserves           | —                 | No           |
| Mint new tokens                      | —                 | No           |
| Change AMM fees after deploy         | —                 | No           |
| Withdraw AMM liquidity               | —                 | No           |
| Modify curve constants               | —                 | No           |
| Disable 10-block cooldown            | —                 | No           |
| Upgrade contracts                    | —                 | No           |

#### 7.2 Upgradeability

* No proxy pattern
* No admin upgrade key
* Contracts are immutable after deployment

***

### 8 · Token Contract (`DurianToken`)

| Attribute                | Status                      |
| ------------------------ | --------------------------- |
| Mint after deploy        | None; constructor-only      |
| Burn function            | None                        |
| Blacklist / tax / freeze | None                        |
| Transfer restrictions    | Standard ERC-20             |
| Upgradeability           | None                        |
| Ownable / AccessControl  | None                        |
| ERC-20 compliance        | OpenZeppelin implementation |

#### Decentralization Score: **10 / 10**

Zero admin surface on the token contract.

***

### 9 · Mathematical Attack Surface

#### 9.1 Exponential Function Risk

* No `exp()`
* No `log()`
* No fixed-point math
* Pure integer arithmetic on `x·y=k`

#### 9.2 Precision Exploit

* Micro-trades of `1 wei` revert with `ZeroAmount`
* Round-trip rounding impact stays below `10⁻²⁷`

**Verdict:** Not exploitable

#### 9.3 Arbitrage Loop

* Bonding is active only before graduation
* AMM is active only after graduation
* Transition is atomic and one-way

**Verdict:** No arbitrage loop

***

### 10 · Gas & Performance

| Operation                  | Gas     | Safety margin      |
| -------------------------- | ------- | ------------------ |
| Factory deploy             | `~4.0M` | Within block limit |
| `createToken`              | `~3.0M` | Within block limit |
| `buyToken`                 | `~150k` | Large margin       |
| `buyToken` with graduation | `~3.5M` | Comfortable margin |
| `sellToken`                | `~100k` | Within block limit |
| AMM swap                   | `~80k`  | Within block limit |
| `rescueStuckTokens`        | `~70k`  | Within block limit |

**Contract sizes** — all below the EIP-170 `24 KB` limit:

| Contract                 | Size       | Limit used |
| ------------------------ | ---------- | ---------- |
| `DuriandotfunFactoryV45` | `21,816 B` | `88.8%`    |
| `BondingCurveMarketV45`  | `10,902 B` | `44.4%`    |
| `DurianAMMV45`           | `3,652 B`  | `14.9%`    |

***

### 11 · Edge Case Simulations

| Scenario                            | Result                                          |
| ----------------------------------- | ----------------------------------------------- |
| One user buys the full curve        | Capped and refunded                             |
| Whale sells all at once             | Curve absorbs the move                          |
| Zero-liquidity start state          | Virtual reserves remain above zero              |
| Spam-creation of `1,000` tokens     | `100 KUB` total cost creates economic friction  |
| Graduation at exact threshold       | Single clean transition                         |
| Graduation with overshoot           | Capped and refunded                             |
| Multiple buyers race to graduate    | `nonReentrant` plus state flag prevents overlap |
| Flash-loan manipulation             | No native primitive; fees remove profit         |
| Extreme market-cap case             | `uint256` headroom remains ample                |
| Malicious creator DOS at graduation | M-1 fallback routes funds to treasury           |

***

### 12 · Critical Invariants (Formally Proven)

```
┌───────────────────────────────────────────────────────────────┐
│  I-1   ∀ buy/sell: virtual K invariant preserved              │
│  I-2   ∀ swap: AMM K grows monotonically                      │
│  I-3   ∀ time: token total supply is immutable                │
│  I-4   ∀ tx: KUB conservation (in = fees + reserves + refund) │
│  I-5   price > 0 at all times                                 │
│  I-6   graduated = true ⟹ curve locked forever                │
│  I-7   creator address immutable                              │
│  I-8   AMM total fee = 0.40% forever                          │
│  I-9   factory fee ≤ 2% forever                               │
│  I-10  AMM LP cannot be withdrawn                             │
└───────────────────────────────────────────────────────────────┘
```

All ten invariants hold across every reachable contract state.

***

### What this audit does not cover

Contract safety does not remove market risk.

* Meme tokens can still fall to zero
* Liquidity is finite
* Wallet, RPC, and bridge risk sits outside the contracts
* Off-chain creator behavior remains outside protocol control

***

### Responsible disclosure

Report vulnerabilities to [**durianandfun@gmail.com**](mailto:durianandfun@gmail.com) with:

1. a clear issue description
2. reproduction steps or a proof of concept
3. expected impact
4. your preferred credit, or anonymity

Reasonable disclosures will be reviewed and acknowledged.

***

*Audit revision: V4.5 post-patch · `2026-04-14` · Nacho Audit*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://durianandfun.gitbook.io/durianfun/durian-launchpad/resources/audit-summary-and-attack-simulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
