# Security

> 📂 Source code: [github.com/Pixsd/hypepool](https://github.com/Pixsd/hypepool)

## Security Reviews

> ⚠️ **Disclaimer**: The security reviews referenced below were performed using [Hashlock's free AI audit tool](https://aiaudit.hashlock.com/), an automated vulnerability scanner. They are **not** formal manual audits conducted by Hashlock's security team. No formal manual audit has been completed to date, though one is planned for the future.

The Protocol has been reviewed using automated security analysis tools.

### Automated Security Review — Hashlock AI Tool (Initial)

**Findings summary:**

| Severity | Count | Status               |
| -------- | ----- | -------------------- |
| High     | 1     | Mitigated            |
| Medium   | 3     | Fixed                |
| Low      | 3     | Fixed / Acknowledged |
| Gas      | 1     | Fixed                |

**Key findings and resolutions (from automated analysis):**

* **\[High] Centralized admin control** — mitigated by adding 48-hour and 72-hour timelocks on all critical admin actions (router changes, upgrades, etc.), reducing the impact of a compromised admin key.
* **\[Medium] VRF request ID collision** — addressed by validating the round ID in `fulfillRandomWords` and tracking `pendingRoundId`.
* **\[Medium] Gas DoS in settlement** — resolved by implementing batch settlement (`settleRoundBatch`) so large rounds can be settled in chunks of configurable size.
* **\[Medium] Missing VRF coordinator validation** — addressed with contract-existence checks on address setters.
* **\[Low] Precision loss in prize distribution** — dust from integer division carries over to the next round.
* **\[Low] Deterministic RNG derivation** — accepted; the VRF seed itself is unpredictable, and the derivation is deterministic by design.
* **\[Low] Reentrancy in prize claiming** — the contract uses OpenZeppelin `ReentrancyGuard` and checks-effects-interactions where possible.

### Automated Security Review — Hashlock AI Tool (Follow-Up)

**Findings summary:**

| Severity      | Count | Status               |
| ------------- | ----- | -------------------- |
| Medium        | 2     | Fixed / Acknowledged |
| Low           | 3     | Fixed / Acknowledged |
| Gas           | 1     | Fixed                |
| Informational | 1     | Acknowledged         |

**Key findings and resolutions (from automated analysis):**

* **\[Medium] `tx.origin` in `noContract` modifier** — acknowledged; the modifier exists to prevent contract-based griefing and is paired with `msg.sender` checks for access control.
* **\[Medium] Gas DoS in single settlement** — already addressed with `settleRoundBatch` in the first audit cycle.
* **\[Low] Open settlement functions** — settlement is permissionless by design (anyone can call it), with a 1 % fee-pool reward incentivizing timely settlement.
* **\[Low] Precision loss** — same as initial review, with dust rollover to next round.
* **\[Low] Timestamp dependence** — acknowledged; miner manipulation is bounded to \~15 seconds and does not materially affect fairness.

### Automated Test Suite

The Protocol has been tested with **300+ automated unit and integration tests** covering:

* Core mechanics — pricing, round states, pool carry-over
* Edge cases — overpayment refunds, duplicate validation, range checks
* Security boundaries — CCIP authorization, timelock enforcement, upgrade window, access control
* ETH conservation invariants — total contract balance verified against outstanding prizes, pools, and fees after every round
* All V2 features — Early Bird, Last Drop, Lucky Draw, mintFreeEntry, FoundationPass, referral system

The full test suite is publicly available on [GitHub](https://github.com/HypePoolApp/contracts). No formal third-party audit has been conducted — interact at your own risk.

***

## Randomness — Chainlink VRF v2.5

Winning numbers are generated using **Chainlink VRF (Verifiable Random Function) v2.5** on the Base network.

### How It Works

1. The protocol contract on Hyperliquid sends a draw request via CCIP to `HypePoolVRFRequester` on Base.
2. `HypePoolVRFRequester` calls the Chainlink VRF Coordinator requesting 1 random word.
3. Chainlink's decentralized oracle network generates the random word with a cryptographic proof.
4. The VRF Coordinator calls `fulfillRandomWords()` on `HypePoolVRFRequester`.
5. The random word is sent back to Hyperliquid via CCIP.
6. The protocol contract deterministically derives all drawn numbers from the single random word.

### Why This Matters

* **Tamper-proof** — neither the contract owner, the miners, nor the VRF node operators can predict or influence the outcome.
* **Verifiable** — anyone can verify the VRF proof on-chain and confirm the drawn numbers are correct.
* **Decentralized** — Chainlink VRF is operated by a decentralized network of independent node operators.

***

## Non-Custodial Design

The smart contract is fully non-custodial:

* **Prize pools** are held in the contract, not in any external wallet.
* **No human can move prize funds** — pools can only be distributed through the settlement logic.
* **Owner fees** are accumulated separately and can only be withdrawn from the fee pool (`withdrawFees`).
* **Prizes never expire** — players can claim at any time.
* **Pending payouts** — if an ETH transfer fails, funds are escrowed in `pendingPayouts` and can be withdrawn by the player at any time.

***

## Admin Safeguards

All sensitive admin operations are protected by timelocks:

| Action                 | Delay                 | Mechanism                                                         |
| ---------------------- | --------------------- | ----------------------------------------------------------------- |
| Change CCIP router     | 48 hours              | `proposeSetCCIPRouter` → `executeSetCCIPRouter`                   |
| Change VRF requester   | 48 hours              | `proposeSetVRFRequester` → `executeSetVRFRequester`               |
| Change source chain    | 48 hours              | `proposeSetSourceChainSelector` → `executeSetSourceChainSelector` |
| Change upkeep interval | 24 hours              | `proposeSetUpkeepInterval` → `executeSetUpkeepInterval`           |
| Upgrade contract       | 72 hours + 1 h window | `proposeUpgrade` → `upgradeToAndCall`                             |

Any pending action can be cancelled by the owner with `cancelAdminAction(hash)`.

During the upgrade execution window, **entry purchases are blocked** to prevent state corruption.

***

## Emergency Mechanisms

### Admin Emergency Cancel

If a draw is stuck (CCIP message lost, VRF failure), the owner can cancel after a **5-minute grace period**:

```
emergencyCancelDraw()
→ Requires: round is DRAWING, 300 seconds have passed since drawRequestedAt
→ Effect: resets round to OPEN, clears CCIP message ID
```

### Public Emergency Cancel

If the owner is unresponsive, **anyone** can cancel a stuck draw after **24 hours**:

```
publicEmergencyCancelDraw()
→ Requires: round is DRAWING, 24 hours have passed since drawRequestedAt
→ Effect: resets round to OPEN, awards caller 2 free entry credits
```

This ensures the protocol can never be permanently stuck, even without owner intervention.

***

## Access Control

| Role                 | Who                            | Capabilities                                                       |
| -------------------- | ------------------------------ | ------------------------------------------------------------------ |
| Owner (admin)        | Deployer                       | Admin functions, fee withdrawal, emergency cancel                  |
| CCIP Router          | Chainlink                      | Deliver cross-chain messages to `ccipReceive`                      |
| VRF Requester        | `HypePoolVRFRequester` on Base | Send draw results back via CCIP                                    |
| Players              | Any EOA                        | Buy entries, claim prizes, trigger public draw, trigger settlement |
| Free Entry Minter    | Address set by owner           | Call `mintFreeEntry` to issue free entries (max 100/round)         |
| FoundationPass Owner | Deployer                       | Set pool contract, admin mint, set mint price                      |
| Pool Contract        | HypePoolV1 proxy               | Call `poolMint` during settlement                                  |

The `noContract` modifier on `buyEntries` requires `tx.origin == msg.sender`, preventing contracts from purchasing entries directly.

***

## FoundationPass Access Control

The FoundationPass contract has two separate mint functions with distinct access control:

| Function        | Who Can Call        | Purpose                      |
| --------------- | ------------------- | ---------------------------- |
| `adminMint(to)` | Contract owner only | Initial distribution (sales) |
| `poolMint(to)`  | Pool contract only  | Auto-award on Super Pool     |

The `poolContract` address is set by the owner via `setPoolContract()`. Only this address can call `poolMint`.

### Double-Mint Protection

The protocol contract maintains a `foundationPassAwarded` boolean flag:

* Set to `true` after the first successful `poolMint` call.
* Once `true`, the settlement logic skips the NFT minting entirely — no gas wasted, no revert risk.
* The `try/catch` wrapper around `poolMint` ensures that if the NFT supply is exhausted (all 10 minted via `adminMint`), settlement proceeds normally.

***

## Additional Protections

* **ReentrancyGuard** — all state-changing functions that transfer ETH are protected.
* **ERC-165 `supportsInterface`** — both `HypePoolV1` and `HypePoolVRFRequester` correctly respond to CCIP interface queries.
* **CCIP sender validation** — `ccipReceive` verifies the source chain selector and sender address.
* **Upgrade window purchase block** — `buyEntries` reverts during the 1-hour upgrade execution window.
* **Contract-existence checks** — all address setters verify the target has deployed bytecode.
