# Game Security

## Overview

MemeDice uses a multi-layered security protection system, from smart contract design to external audits, to fully safeguard the funds of players and investors.

***

## Security Audit

### Triple Security Protection

```mermaid
graph TD
    A[Security Protection System] --> B[🤖 AI Audit]
    A --> C[👥 Professional Security Team]
    A --> D[🔴 Red Team Offense and Defense]
    
    B --> E[Automated Vulnerability Scanning<br/>Code Pattern Analysis]
    C --> F[Manual Code Review<br/>Logic Vulnerability Detection]
    D --> G[Simulated Real Attacks<br/>Penetration Testing]
    
    style A fill:#4F46E5,color:#fff
    style B fill:#059669,color:#fff
    style C fill:#D97706,color:#fff
    style D fill:#DC2626,color:#fff
```

| Tier                                | Method              | Description                                                                |
| ----------------------------------- | ------------------- | -------------------------------------------------------------------------- |
| **🤖 AI audit**                     | Automated Analysis  | Use AI tools to scan code and detect common vulnerability patterns         |
| **👥 Professional Security Team**   | Manual Review       | Professional security researchers conduct in-depth code reviews            |
| **🔴 Red Team Offense and Defense** | Penetration Testing | Simulate real attack scenarios to test the system's defensive capabilities |

***

## Contract Security Design

### 1. ReentrancyGuard Anti-Reentrancy

All functions involving fund transfers use `ReentrancyGuard` protection:

```solidity
// Pseudocode
modifier nonReentrant() {
    require(!locked, "ReentrancyGuard: reentrant call");
    locked = true;
    _;
    locked = false;
}
```

**Protection Purpose**: Prevents reentrancy attacks, where a malicious contract is called back during fund transfers.

**Protected Functions**:

* `placeBetSync()` — Sync Bet
* `placeBatchBetSync()` — Batch Sync Bets
* `placeBetAsync()` — Async Bet
* `placeBatchBetAsync()` — Batch Async Bets
* `deposit()` — Deposit
* `withdraw()` — Withdraw
* `fulfillRandomNumber()` — Oracle Random Number Reveal

### 2. SafeERC20 Secure Token Operations

All token transfer operations use OpenZeppelin's `SafeERC20` library:

```solidity
using SafeERC20 for IERC20;

// Safe transfer in
token.safeTransferFrom(msg.sender, address(this), amount);

// Safe transfer out
token.safeTransfer(recipient, amount);
```

**Protection Purpose**:

* Handles non-standard ERC-20 tokens that do not return a boolean value
* Ensures transactions roll back when transfers fail
* Prevents silent failures

### 3. Pending Settlement Funds Locking (pendingLockedAmount)

When a player places a bet, the potential maximum payout amount is **locked**:

```mermaid
graph LR
    A[Total Pool Amount] --> B[Available Balance]
    A --> C[Locked Amount]
    
    B -->|Used for new bets| D[New Lock]
    C -->|Released after settlement| E[Back to Available Balance]
    
    style C fill:#DC2626,color:#fff
    style B fill:#059669,color:#fff
```

```
Available Balance = Total Pool Amount - pendingLockedAmount
```

**Protection Purpose**:

* Ensures the pool has enough tokens to pay all pending bets
* Prevents insufficient funds when multiple players win at the same time
* Protects shareholders' funds from being overpaid

### 4. Bet Timeout Cancellation (BET\_TIMEOUT)

In Oracle mode, if the Oracle does not reveal the random number within the specified time:

```
BET_TIMEOUT = 300 seconds (5 minutes)
```

After timeout, players can cancel the bet and retrieve their funds.

**Protection Purpose**:

* Prevents player funds from being permanently locked if the Oracle service goes down
* Ensures players can retrieve their funds under any circumstances

### 5. Fee Cap Protection

The owner's fee rate has a hard-coded upper limit:

```
MAX_FEE_BPS = 900 (i.e. 9%)
```

**Protection Purpose**:

* Prevents administrators from setting excessively high fees
* Protects the interests of players and shareholders
* Even if the administrator acts maliciously, the fee rate will not exceed 9%

***

## Attack Protection

### flash loan attacks

**Attack Method**: The attacker borrows in the same transaction → places a bet → decides whether to roll back based on the result.

**Protection Measures**:

* Oracle mode: asynchronous settlement, with betting and settlement in different transactions
* Prevrandao mode:`onlyEOA` restriction, the contract cannot call

### Sandwich Attack

**Attack Method**: The attacker inserts transactions before and after the target transaction to manipulate price or state.

**Protection Measures**:

* Bet results are determined by randomness and are not affected by transaction ordering
* Changes in pool balance do not affect submitted bet results

### Reentrancy Attack

**Attack Method**: Repeatedly withdraw funds by calling back into the contract during fund transfers.

**Protection Measures**:

* All critical functions use `ReentrancyGuard`
* Follow the Checks-Effects-Interactions pattern

### Oracle Manipulation

**Attack Method**: The Oracle modifies the random number after seeing the bet.

**Protection Measures**:

* Commit-Reveal mechanism: the random number is locked in by commitHash before the bet
* Anyone can verify `keccak256(R) == commitHash`

### Pool Depletion

**Attack Method**: Deplete the pool through a large number of winning bets.

**Protection Measures**:

* `pendingLockedAmount` Lock pending settlement funds
* `maxBet` Limit single-bet amounts
* `maxPoolCap` Limit pool capacity
* The bet amount cannot exceed a certain percentage of the available balance

***

## Contract Constants

The following are security-related constants in the contract:

| Constant         | value | Description                    |
| ---------------- | ----- | ------------------------------ |
| `MAX_FEE_BPS`    | 900   | Owner fee rate cap (9%)        |
| `BET_TIMEOUT`    | 300   | Bet timeout duration (seconds) |
| `MAX_WIN_RATE`   | 9000  | Maximum win rate (90%)         |
| `MIN_WIN_RATE`   | 1000  | Minimum win rate (10%)         |
| `MODULO`         | 10000 | Random number modulo base      |
| `MAX_BATCH_SIZE` | 50    | Maximum number of batch bets   |

***

## Security Checklist

For players and investors, here is a checklist for assessing game security:

### ✅ Contract Level

* [x] Has the contract code been audited?
* [x] Is ReentrancyGuard used?
* [x] Is SafeERC20 used?
* [x] Is there a fee cap protection?
* [x] Is there a timeout cancellation mechanism?

### ✅ Game Level

* [x] Has the game been decentralized? (🏛️ tag)
* [x] Has the token been security-verified? (✅ tag)
* [x] Are admin operation logs normal?
* [x] Is the pool balance sufficient?
* [x] Is the owner's fee rate reasonable?

### ✅ Randomness Level

* [x] Is it using Oracle or Prevrandao?
* [x] Is the commitHash in Oracle mode verifiable?
* [x] Do historical bet results match the probability distribution?

***

## Related links

* ⬅️ Back [Technical Deep Dive Overview](/dapp.meme-en/technical-overview/technical-deep-dive-overview.md)
* 🎲 Learn about [Oracle vs Prevrandao](/dapp.meme-en/technical-overview/oracle-vs-prevrandao.md)
* 🏛️ Learn More [Decentralization](file:///7303089/game-admin/decentralize.md)
* 🏗️ Learn about [Smart Contract Architecture](/dapp.meme-en/technical-overview/smart-contract-architecture.md)


---

# Agent Instructions: 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://docs.dapp.meme/dapp.meme-en/technical-overview/game-security.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.
