# 🔐 Security Architecture & Math Specifications

### 1. Security Protocols

The Aegis Protocol implements a defensive programming approach, utilizing industry-standard libraries combined with rigid state validation.<br>

<figure><img src="/files/PDVaVHllyx7lLAEmV5ak" alt="" width="375"><figcaption></figcaption></figure>

#### A. Anti-Reentrancy Mechanisms

All state-changing functions (`stake`, `withdraw`, `getReward`, `claim`) are protected by `ReentrancyGuard` (OpenZeppelin). This enforces the Checks-Effects-Interactions pattern atomically.

* Implementation: The `nonReentrant` modifier locks the contract state before any external call (transfer) is made and unlocks it only after execution concludes.
* Impact: Eliminates the risk of recursive call attacks where a malicious contract could drain the pool by re-entering the `withdraw` function before the user's balance is updated.

#### B. SafeERC20 & Decimal Agnosticism

The protocol strictly utilizes `SafeERC20` wrappers for all token interactions.

* Problem Solved: Many tokens (e.g., USDT on BSC) do not return a boolean `true` on successful transfer, causing standard `IERC20.transfer` calls to revert or fail silently.
* Solution: Aegis wraps these calls to handle non-standard return values gracefully.
* Decimal Handling: The `NeonFixedStaking` contract calculates rewards based on the principal amount ratio. This allows the protocol to natively support tokens with varying decimals (6 for USDC, 18 for BNB) without precision loss or scaling errors.

#### C. Solvency & Reward Integrity

To prevent the "Empty Pool" scenario—where a protocol promises rewards it cannot pay—Aegis implements a strict solvency check during the funding phase.

In `NeonStaking.sol`, the `notifyRewardAmount` function enforces:

Solidity

```
require(rewardRate * duration <= rewardsToken.balanceOf(address(this)), "Reward amount > balance");
```

This ensures that 100% of the advertised rewards are physically present in the contract vault before the farming period begins.

***

### 2. Mathematical Models

Aegis employs two distinct mathematical models for yield distribution.

#### A. The Flexible Algorithm (Cumulative Distribution)

*Used in: `NeonStaking.sol`*

This model is based on the Synthetix StakingRewards architecture. Instead of iterating through all users to distribute rewards (which costs too much gas), the protocol tracks a global Reward Per Token (RPT) accumulator.

1\. Reward Per Token ($$St​$$) At any block $$t$$, the cumulative reward per token is calculated as:<br>

<figure><img src="/files/mR7HpMNSSYaayIYEVvzj" alt=""><figcaption></figcaption></figure>

Where:

* $$S$$: Cumulative Reward Per Token (stored in `rewardPerTokenStored`)
* $$R$$: Reward Rate (tokens released per second)
* $$Δt$$: Time elapsed since last update
* $$Lt​$$: Total Liquidity Staked (`totalSupply`)

2\. User Earned Calculation A user's pending reward is calculated by comparing the global accumulator snapshot at their last interaction ($$Suser​$$) vs. the current global accumulator \
($$Scurrent​$$):

<figure><img src="/files/tuhW1YF1a5j4N1zxrVfU" alt=""><figcaption></figcaption></figure>

This allows for O(1) complexity, meaning the gas cost remains low and constant regardless of how many users are in the pool.\
\
B. The Fixed Vault Algorithm (Linear Yield)

*Used in: `NeonFixedStaking.sol`*

The Fixed Vaults use a deterministic linear formula. This guarantees a specific APY regardless of the pool's total size.

The Formula:

<figure><img src="/files/eLPEa94PJyUpoJxNLKes" alt=""><figcaption></figcaption></figure>

Where:

* $$P$$: Principal (Staked Amount)
* $$APY$$: Annual Percentage Yield (Integer, e.g., 15 for 15%)
* $$T$$: Lock Duration in seconds
* $$365$$: Days in a year (represented as seconds: $$31,536,000$$)

Precision Handling: In Solidity, division is performed last to maintain precision. The actual implementation code is:

Solidity

```
(userStake.amount * apy * timeElapsed) / (100 * 365 days)
```

This order of operations ensures that even for small stakes or short durations, the reward calculation remains accurate down to the smallest unit (wei).

***

### 3. Gas Optimization

The contracts are optimized for the Binance Smart Chain (BSC) environment:

* Immutable Variables: Core addresses (`stakingToken`, `rewardsToken`) are declared `immutable`, saving gas on every read operation (SLOAD vs. internal bytecode read).
* External vs Public: Functions meant for UI interaction are marked `external`, optimizing memory allocation during execution.
* Memory vs Storage: The `StakeInfo` struct in Fixed Staking is loaded into `memory` for read operations (like checking pending rewards) to avoid expensive storage reads.


---

# 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.metuslabs.com/metus/dapps/aegis/security-architecture-and-math-specifications.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.
