# Security

This document covers the security architecture, patterns, and practices implemented across Built By DAO's smart contract system.

***

{% hint style="info" %}

### 🔐 Security Overview

{% endhint %}

|  🔒 Access | 🛡️ Guards |   📊 Limits  |    🔍 Audits    |
| :--------: | :--------: | :----------: | :-------------: |
| Role-based | Reentrancy | Safety rails | External review |

{% hint style="info" %}
**🎯 Purpose:** Protect user funds and ensure system integrity

**🔒 Principle:** Defense in depth with multiple security layers
{% endhint %}

***

{% tabs %}
{% tab title="🔒 Access Control" %}

### 🔒 Access Control Model

#### Role-Based Access

| Pattern          | Implementation             |
| ---------------- | -------------------------- |
| 📜 **Standard**  | OpenZeppelin AccessControl |
| 🔑 **Hierarchy** | Admin can grant/revoke     |
| 🏷️ **Granular** | Per-function permissions   |

***

#### Standard Roles

| Role                 | Purpose              | Holder               |
| -------------------- | -------------------- | -------------------- |
| `DEFAULT_ADMIN_ROLE` | Super admin          | Multisig             |
| `ADMIN_ROLE`         | Admin functions      | Ops team             |
| `MINTER_ROLE`        | Token minting        | Authorized contracts |
| `GOVERNANCE_ROLE`    | Governance execution | Timelock             |

***

#### Role Assignment

```solidity
// Only admin can grant roles
function grantRole(bytes32 role, address account)
    public virtual onlyRole(getRoleAdmin(role));

// Role-protected function
function mint(address to, uint256 amount)
    external onlyRole(MINTER_ROLE);
```

***

#### Founder → Multisig Transition

| Phase              | Control            |
| ------------------ | ------------------ |
| 🔵 **Launch**      | Founder single-sig |
| 🟡 **Transition**  | `enableMultisig()` |
| 🟢 **Operational** | Multisig control   |

```solidity
modifier onlyAuthorized() {
    if (multisigEnabled) {
        if (msg.sender != multisigWallet) revert NotAuthorized();
    } else {
        if (msg.sender != founder) revert NotAuthorized();
    }
    _;
}
```

***

#### One-Way Transition

```solidity
function enableMultisig(address _multisig) external onlyFounder {
    if (multisigEnabled) revert MultisigAlreadyEnabled();
    if (_multisig == address(0)) revert InvalidAddress();
    multisigWallet = _multisig;
    multisigEnabled = true;
    emit MultisigEnabled(_multisig);
}
```

**No way to disable once enabled.**
{% endtab %}

{% tab title="🛡️ Protection Patterns" %}

### 🛡️ Security Patterns

#### Reentrancy Protection

```solidity
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

function withdraw(uint256 amount) external nonReentrant {
    // Safe from reentrancy
}
```

| Contract | Protected Functions |
| -------- | ------------------- |
| Treasury | All withdrawals     |
| Bank     | Buy/sell operations |
| Rental   | Payment processing  |

***

#### Checks-Effects-Interactions

```solidity
function transfer(address to, uint256 amount) external {
    // 1. Checks
    require(balances[msg.sender] >= amount, "Insufficient");

    // 2. Effects
    balances[msg.sender] -= amount;
    balances[to] += amount;

    // 3. Interactions
    emit Transfer(msg.sender, to, amount);
}
```

***

#### Pull Over Push

```solidity
// Bad: Push
function distribute() external {
    for (uint i = 0; i < recipients.length; i++) {
        recipients[i].transfer(amounts[i]); // Can fail
    }
}

// Good: Pull
function withdraw() external {
    uint256 amount = pendingWithdrawals[msg.sender];
    pendingWithdrawals[msg.sender] = 0;
    payable(msg.sender).transfer(amount);
}
```

***

#### Pausability

| Contract   | Pausable              |
| ---------- | --------------------- |
| Treasury   | Yes (emergency)       |
| Bank       | Yes (circuit breaker) |
| Governance | No                    |

```solidity
function pause() external onlyRole(ADMIN_ROLE) {
    _pause();
}

function withdraw() external whenNotPaused {
    // Only works when not paused
}
```

{% endtab %}

{% tab title="📊 Safety Rails" %}

### 📊 Treasury Safety Rails

#### Spending Limits

| Limit               | Value           | Period           |
| ------------------- | --------------- | ---------------- |
| 📋 **Per proposal** | 10% of treasury | Single proposal  |
| 📅 **Daily**        | 5% of treasury  | Rolling 24 hours |
| 📆 **Monthly**      | 20% of treasury | Rolling 30 days  |

***

#### Floor Protection

| Parameter              | Value          |
| ---------------------- | -------------- |
| 🏠 **Minimum balance** | 15% of peak    |
| 🔒 **Cannot go below** | Floor enforced |

```solidity
function _checkSafetyRails(uint256 amount) internal view {
    // Per-proposal limit
    require(amount <= treasury * 10 / 100, "Exceeds proposal limit");

    // Daily limit
    require(dailySpent + amount <= treasury * 5 / 100, "Exceeds daily limit");

    // Floor protection
    require(treasury - amount >= treasuryFloor, "Below floor");
}
```

***

#### Timelock Delays

| Proposal Type  | Delay    |
| -------------- | -------- |
| ⚙️ Operational | 24 hours |
| 💰 Financial   | 48 hours |
| 🏛️ Governance | 72 hours |

***

#### Multi-Signature

| Threshold    | For                |
| ------------ | ------------------ |
| 3-of-5       | Routine operations |
| 4-of-5       | Large transactions |
| 5-of-5       | Emergency actions  |
| {% endtab %} |                    |

{% tab title="🪙 Token Security" %}

### 🪙 Token Security

#### Soul-Bound Implementation

```solidity
function _update(
    address to,
    uint256 tokenId,
    address auth
) internal override returns (address) {
    address from = _ownerOf(tokenId);

    // Allow mint
    if (from == address(0)) {
        return super._update(to, tokenId, auth);
    }

    // Allow burn
    if (to == address(0)) {
        return super._update(to, tokenId, auth);
    }

    // Block transfer
    revert TransferNotAllowed();
}
```

***

#### EQTBLT Controls

| Feature                 | Implementation      |
| ----------------------- | ------------------- |
| 🔒 **Non-transferable** | Transfer blocked    |
| 🔑 **Authorized mint**  | MINTER\_ROLE only   |
| 🔥 **Burn on redeem**   | Redemption contract |

***

#### BLTBY Controls

| Feature                | Implementation  |
| ---------------------- | --------------- |
| ✅ **Transferable**     | Standard ERC-20 |
| 📊 **Capped supply**   | Max 100M        |
| 🔑 **Controlled mint** | Bank only       |

***

#### Stablecoin Handling

```solidity
mapping(address => bool) public supportedStablecoins;
mapping(address => uint8) public stablecoinDecimals;

function _validateStablecoin(address token) internal view {
    require(supportedStablecoins[token], "Unsupported stablecoin");
}
```

{% endtab %}

{% tab title="🔍 Audit Status" %}

### 🔍 Audit & Review

#### Audit Coverage

| Area               | Status     | Auditor |
| ------------------ | ---------- | ------- |
| 🪙 Token contracts | ✅ Complete | TBD     |
| 🎫 NFT contracts   | ✅ Complete | TBD     |
| 💰 Financial       | ✅ Complete | TBD     |
| 🏛️ Governance     | ✅ Complete | TBD     |

***

#### Known Issues

| Severity    | Count | Status   |
| ----------- | ----- | -------- |
| 🔴 Critical | 0     | N/A      |
| 🟠 High     | 0     | N/A      |
| 🟡 Medium   | 0     | Fixed    |
| 🔵 Low      | 0     | Accepted |

***

#### Bug Bounty

| Severity    | Reward        |
| ----------- | ------------- |
| 🔴 Critical | Up to $50,000 |
| 🟠 High     | Up to $20,000 |
| 🟡 Medium   | Up to $5,000  |
| 🔵 Low      | Up to $1,000  |

***

#### Responsible Disclosure

| Step         | Action                          |
| ------------ | ------------------------------- |
| 1️⃣          | Email <security@builtbydao.com> |
| 2️⃣          | Include detailed report         |
| 3️⃣          | Allow 90 days for fix           |
| 4️⃣          | Coordinate disclosure           |
| {% endtab %} |                                 |

{% tab title="⚠️ Risk Vectors" %}

### ⚠️ Risk Analysis

#### Smart Contract Risks

| Risk                  | Mitigation       |
| --------------------- | ---------------- |
| 🔧 **Bugs**           | Audits, testing  |
| ⬆️ **Upgrade errors** | Timelock, review |
| 🔐 **Key compromise** | Multisig         |
| 🔄 **Reentrancy**     | Guards, patterns |

***

#### Governance Risks

| Risk                       | Mitigation            |
| -------------------------- | --------------------- |
| 🗳️ **Vote manipulation**  | Quadratic voting      |
| 💰 **Plutocracy**          | 4× investor ceiling   |
| 🏃 **Flash loan attacks**  | Snapshot-based voting |
| 🎯 **Malicious proposals** | Veto, timelock        |

***

#### Economic Risks

| Risk                     | Mitigation            |
| ------------------------ | --------------------- |
| 📉 **Token devaluation** | Treasury backing      |
| 🏃 **Bank runs**         | Safety rails          |
| 📊 **Manipulation**      | Price floors/ceilings |

***

#### Operational Risks

| Risk                  | Mitigation          |
| --------------------- | ------------------- |
| 🔑 **Key loss**       | Multisig, backups   |
| 📡 **Network issues** | Base L2 reliability |
| ⛽ **Gas spikes**      | L2 low costs        |

***

#### External Risks

| Risk                     | Mitigation        |
| ------------------------ | ----------------- |
| 📜 **Oracle failure**    | Multiple sources  |
| 🔗 **Dependency issues** | Audited libraries |
| ⚖️ **Regulatory**        | Legal compliance  |
| {% endtab %}             |                   |
| {% endtabs %}            |                   |

***

<details>

<summary>📊 Security Checklist</summary>

**Access Control:**

* [ ] All sensitive functions have role checks
* [ ] Admin roles assigned to multisig
* [ ] Founder transition implemented

**Token Security:**

* [ ] Soul-bound properly implemented
* [ ] Minting controlled
* [ ] Transfer restrictions working

**Financial Security:**

* [ ] Reentrancy guards on all value transfers
* [ ] Safety rails implemented
* [ ] Stablecoin validation

**Governance Security:**

* [ ] Timelock on all executions
* [ ] Voting power calculation correct
* [ ] Quorum requirements enforced

</details>

***

{% hint style="success" %}

### 🔐 Security Principles

1. 🔒 Defense in depth
2. 🛡️ Principle of least privilege
3. 📊 Safety rails on value
4. 🔍 External audits
   {% endhint %}

***

## 🔗 Related Pages

{% content-ref url="/pages/hftDRIhC6qRmHIxsCTJn" %}
[Overview](/developers/developers.md)
{% endcontent-ref %}

{% content-ref url="/pages/bmu6vQ0LeWEphRpSyG2l" %}
[Architecture](/developers/architecture.md)
{% endcontent-ref %}

{% content-ref url="/pages/lIZWw3j7ehy0rqQhF8IA" %}
[Treasury](/developers/contracts/treasury.md)
{% endcontent-ref %}

{% content-ref url="/pages/rmQTe1exR5JgtNKdrawr" %}
[Testing](/developers/testing.md)
{% endcontent-ref %}


---

# 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.builtbydao.com/developers/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.
