# Vaultfire Codex — Batch 8: Deprecated Contract Archive

> **⚠ DEPRECATED WARNING**
>
> These contracts are archived and not used in the current Vaultfire system. They are documented here for historical completeness. None of the contracts in this file should be deployed, referenced in new code, or treated as canonical implementations. Where a V2 successor exists it supersedes the corresponding entry below in every respect.

---

## Table of Contents

1. [PurchasingPowerBondsV2.sol](#1-purchasingpowerbondsv2sol)
2. [FanBeliefBond.sol](#2-fanbeliefbondsol)
3. [VaultfireDAO.sol](#3-vaultfiredaosol)
4. [VerdantAnchorBondsV2.sol](#4-verdantanchorbondsv2sol)
5. [CommonGroundBonds.sol](#5-commongroundbondssol)
6. [SwapGate.sol](#6-swapgatesol)
7. [BuilderBeliefBondsV2.sol](#7-builderbeliefbondsv2sol)
8. [VaultfireRewardStream.sol](#8-vaultfirerewardstreamsol)
9. [VerdantAnchorBonds.sol](#9-verdantanchorbondssol)
10. [FreedomVow.sol](#10-freedomvowsol)
11. [HealthCommonsBondsV2.sol](#11-healthcommonsbondsv2sol)
12. [CompetitiveIntegrityBond.sol](#12-competitiveintegritybondsol)
13. [EscapeVelocityBonds.sol](#13-escapevelocitybondssol)
14. [GhostkeyAttribution.sol](#14-ghostkeyattributionsol)
15. [RewardMultiplier.sol](#15-rewardmultipliersol)
16. [TeamworkIntegrityBond.sol](#16-teamworkintegritybondsol)
17. [RewardStream.sol](#17-rewardstreamsol)
18. [ContributorUnlockKey.sol](#18-contributorunlockkeysol)
19. [GhostkeyLoyaltyLock.sol](#19-ghostkeyloyaltylocksol)
20. [LaborDignityBonds.sol](#20-labordignityaondssol)
21. [EscapeVelocityBondsV2.sol](#21-escapevelocitybondsv2sol)
22. [YieldPoolHealthMonitor.sol](#22-yieldpoolhealthmonitorsol)
23. [LaborDignityBondsV2.sol](#23-labordignityabondsv2sol)
24. [CommonGroundBondsV2.sol](#24-commongroundbondsv2sol)
25. [CovenantFlame.sol](#25-covenantflamesol)
26. [PurchasingPowerBonds.sol](#26-purchasingpowerbondssol)
27. [AIAccountabilityBonds.sol](#27-aiaccountabilitybondssol)
28. [BuilderBeliefBonds.sol](#28-builderbeliefbondssol)
29. [AIPartnershipBonds.sol](#29-aipartnershipbondssol)
30. [FanVerificationSybilResistance.sol](#30-fanverificationsybilresistancesol)
31. [VaultfireBugBounty.sol](#31-vaultfirebugbountysol)
32. [VaultfireLoyalty.sol](#32-vaultfireloyaltysol)
33. [HealthCommonsBonds.sol](#33-healthcommonsbondssol)

---

## Shared Terminology

Throughout this document the following terms appear repeatedly:

- **BaseYieldPoolBond** — an inherited base contract (not deprecated; still active) that provides `DISTRIBUTION_TIMELOCK`, `_useYieldPool()`, `_replenishYieldPool()`, `_validateNonZero()`, `_validateScore()`, `_validateAddress()`, the `whenNotPaused` modifier, `nonReentrant`, and `onlyOwner`.
- **MissionEnforcement** — an optional gating contract that checks whether a calling contract is compliant with named `CorePrinciple` values (e.g., `OPEN_SOURCE_VERIFIABLE`, `PRIVACY_DEFAULT`, `AI_PROFIT_CAPS`).
- **`.transfer()` pattern** — the Solidity 2300-gas-stipend ETH transfer method. Deprecated in favour of `.call{value: …}("")` because `transfer` can silently fail when the recipient is a smart contract with a non-trivial receive function, or when future EVM repricing changes gas costs.
- **Basis points (bps)** — 1/100th of a percent. 10 000 bps = 100 %. Used throughout for fractional multipliers and percentage calculations.
- **Score range 0–10 000** — the canonical representation of a percentage where 10 000 = 100 %. All raw metric values in these contracts use this scale unless otherwise stated.
- **Math-fix 2026-01-07** — a divisor correction applied across several V2 bond contracts on that date to recalibrate bond-value outputs to realistic ETH magnitudes.

---

---

# 1. PurchasingPowerBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/PurchasingPowerBondsV2.sol`
**Lines:** ~751
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

Companies stake ETH that grows in value when workers can afford a 1990s-equivalent standard of living — housing, food, healthcare, and discretionary spending. The contract operationalises the idea that employer profit-sharing should be pegged to workers' real purchasing power, not nominal wage levels. If workers cannot afford basic necessities at 1990-price parity the company loses its appreciation share; workers receive 100 % by penalty.

## Why It Was Likely Deprecated

This is the **V2 successor** to `PurchasingPowerBonds.sol` (V1). It is itself deprecated because the affordability-scoring methodology was seen as insufficiently decentralised — the AI company still self-reports metrics, and the attestation quorum was not enforced on-chain with cryptographic weight. The contract was absorbed into a redesigned scoring oracle system.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
```
Standard SPDX identifier; MIT licence.

```
L2    pragma solidity ^0.8.25;
```
Requires the compiler to be ≥ 0.8.25, capturing all built-in overflow protection and the `unchecked` keyword improvements of that release series.

```
L4    import "../BaseYieldPoolBond.sol";
```
Pulls in the shared base class that supplies `DISTRIBUTION_TIMELOCK`, `_useYieldPool()`, `whenNotPaused`, `nonReentrant`, `onlyOwner`, and helper validators.

```
L5    import "../MissionEnforcement.sol";
```
Optional mission-gate interface. If `missionEnforcementEnabled` is true, `distributeBond` will revert unless the contract is compliant with configured principles.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `nextBondId` | `uint256` | Auto-incrementing ID counter; starts at 1. |
| `bonds` | `mapping(uint256 => Bond)` | Primary storage for each bond keyed by ID. |
| `affordabilityMetrics` | `mapping(uint256 => AffordabilityMetrics[])` | Timestamped affordability readings per bond. |
| `workerAttestations` | `mapping(uint256 => WorkerAttestation[])` | Worker attestations confirming or challenging metrics. |
| `bondDistributions` | `mapping(uint256 => Distribution[])` | Historical distributions per bond. |
| `PENALTY_PURCHASING_POWER` | `uint256` constant = `80` | Minimum purchasing power score below which penalty fires. |
| `PENALTY_WORKER_VERIFICATION` | `uint256` constant = `70` | Minimum worker verification score below which penalty fires. |

---

### Structs

**`Bond`**
```
bondId            uint256  — unique identifier
company           address  — company that staked ETH
companyName       string   — human-readable name
stakeAmount       uint256  — ETH locked at creation
createdAt         uint256  — block.timestamp at creation
active            bool     — false after settlement
```

**`AffordabilityMetrics`**
```
timestamp               uint256  — when reading was recorded
housingAffordability    uint256  — 0-10000 (can workers afford 1990-equivalent housing?)
foodAffordability       uint256  — 0-10000
healthcareAffordability uint256  — 0-10000
discretionaryAffordability uint256 — 0-10000
submitter               address  — who submitted this reading
```

**`WorkerAttestation`**
```
timestamp       uint256  — attestation time
worker          address  — attesting worker
confirmsScore   bool     — does worker confirm company's metric?
workerScore     uint256  — worker's own affordability estimate (0-10000)
notes           string   — free-text attestation notes
```

**`Distribution`**
```
timestamp       uint256  — settlement time
totalAmount     int256   — appreciation amount (may be negative)
workerShare     uint256  — ETH sent to workers/yield pool
companyShare    uint256  — ETH returned to company
reason          string   — human-readable reason string
```

---

### Functions

#### `createBond(companyName, workerCount)`
- `payable`, open to anyone
- Requires `msg.value > 0`
- Stores new `Bond` with `stakeAmount = msg.value`
- Emits `BondCreated(bondId, company, stakeAmount)`
- Returns the new `bondId`

**Design intent:** Companies call this to put skin in the game — ETH they can only retrieve if workers' purchasing power is high enough.

#### `submitAffordabilityMetrics(bondId, housing, food, healthcare, discretionary)`
- Only callable by `bonds[bondId].company`
- Appends a new `AffordabilityMetrics` entry
- All scores clamped/validated to be ≤ 10 000
- Emits `MetricsSubmitted(bondId, timestamp)`

#### `addWorkerAttestation(bondId, confirmsScore, workerScore, notes)`
- Open to any address (intended to be called by actual workers)
- Appends a `WorkerAttestation` entry
- Emits `WorkerAttested(bondId, worker)`

**No Sybil resistance exists for attestations.** Any address may attest, which was a primary design flaw.

#### `purchasingPowerScore(bondId) → uint256`
Returns the average of the four affordability dimensions from the **latest** `AffordabilityMetrics` entry:
```
score = (housing + food + healthcare + discretionary) / 4
```
Returns 5 000 (neutral) if no metrics have been submitted.

#### `workerVerificationScore(bondId) → uint256`
Iterates recent `WorkerAttestation` entries (within the last 180 days). For each:
- If `confirmsScore = true`, uses the company's latest affordability metrics as the worker's score
- Otherwise uses `workerScore` from the attestation itself

Averages all collected scores. Returns 50 (minimum) if fewer than one attestation exists. Maps the average to the range 50–150 via:
```
if avgScore >= 7000  → return 150
if avgScore >= 4000  → return 100 + (avgScore - 4000) / 60
else                 → return 50 + avgScore / 80
```

#### `timeMultiplier(bondId) → uint256`
```
age = block.timestamp − bond.createdAt
years = age / 31 536 000

years < 1   → 100
years 1–3   → 100 + years × 50
years > 3   → 200 + (years − 3) × 50
```
Rewards long-duration bonds; uncapped above year 3 (a potential overflow risk for very long-lived bonds, though practically negligible).

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stakeAmount × purchasingPower × workerVerification × time) / 1_000_000
```
- `purchasingPower` is 0–10 000
- `workerVerification` is 50–150
- `time` is 100–200+
- Divisor 1 000 000 normalises the product back to ETH-magnitude

**Example:** 1 ETH stake, score 7 000, verification 120, time 150 → `(1e18 × 7000 × 120 × 150) / 1_000_000 = 126e18 ETH` — clearly a calibration error demonstrating why the divisor comment "math-fix kept original" is important context.

#### `calculateAppreciation(bondId) → int256`
```
appreciation = int256(calculateBondValue) − int256(stakeAmount)
```
May be negative if scores have declined.

#### `shouldApplyPenalty(bondId) → (bool, string)`
```
purchasingPower < 80  → (true, "Workers cannot afford basics")
workerVerification < 70 → (true, "Workers not verifying claims")
```

#### `distributeBond(bondId)`
- `nonReentrant`, `whenNotPaused`, `onlyAICompany(bondId)` (actually `onlyCompany`)
- Calls `_requireMissionCompliance()` if mission enforcement is enabled
- Checks `DISTRIBUTION_TIMELOCK` (from `BaseYieldPoolBond`)
- Computes appreciation; requires `appreciation != 0`
- Evaluates penalty
- On **normal appreciation (no penalty):** 70 % to workers (via `_useYieldPool`), 30 % to company
- On **penalty:** 100 % to workers
- On **depreciation (negative appreciation):** 100 % workers as compensation, 0 % company
- Calls `_useYieldPool(workerShare)` to route worker ETH through the yield pool
- Emits `BondDistributed(bondId, workerShare, companyShare)`

**Note:** The actual ETH transfer to individual workers is not performed on-chain; it routes to the yield pool and relies on an off-chain worker-registry to distribute further. This is explicitly acknowledged in the V1 source and carried forward as a known limitation.

---

### Math Summary

| Computation | Formula |
|---|---|
| Purchasing power score | `(housing + food + healthcare + discretionary) / 4` |
| Worker verification multiplier | Segmented: 50–150 based on avg worker score |
| Time multiplier | 100 + 50/year up to year 3, then 200 + 50/year beyond |
| Bond value | `(stake × power × verification × time) / 1_000_000` |
| Appreciation | `bondValue − stakeAmount` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, company, stakeAmount)` | `createBond` |
| `MetricsSubmitted(bondId, timestamp)` | `submitAffordabilityMetrics` |
| `WorkerAttested(bondId, worker)` | `addWorkerAttestation` |
| `BondDistributed(bondId, workerShare, companyShare)` | `distributeBond` |
| `PenaltyApplied(bondId, reason)` | `distributeBond` when penalty triggers |
| `MissionEnforcementUpdated(previous, current)` | `setMissionEnforcement` |
| `MissionEnforcementEnabled(bool)` | `setMissionEnforcementEnabled` |

---

### Design Intent

To create a financial instrument where employer capital appreciates only if worker purchasing power is objectively maintained. The 1990-parity benchmark was chosen because that era is broadly considered the last period of broadly distributed wage-cost parity in the US. The goal was to make employers directly financially motivated to keep wages real.

### Why It Didn't Make Production

1. **No Sybil resistance on worker attestations** — any address can attest as a worker. The attestation pool is trivially gameable.
2. **Worker distribution is off-chain** — ETH goes to a yield pool with no on-chain mechanism to route it to individual workers; requires a centralised worker registry.
3. **Superseded by a redesigned oracle** — the scoring methodology was moved to a purpose-built oracle contract with stronger verification.
4. **Divisor calibration** — the 1 000 000 divisor produces unrealistic bond values at mid-range scores (see math section).

---

---

# 2. FanBeliefBond.sol

**Path:** `theloopbreaker-site/contracts/deprecated/FanBeliefBond.sol`
**Lines:** ~663
**Inherits:** `ReentrancyGuard` only (standalone)

## What It Was Supposed to Do

Allow sports fans to stake ETH on athletes or teams maintaining competitive integrity over 1–10 year bond periods. The contract tracks five integrity statuses and five violation types. Proven violations slash fan stakes and reward whistleblowers 10 %. High-integrity athletes over time yield multiplied returns.

## Why It Was Likely Deprecated

Sports integrity data cannot be reliably sourced on-chain without a trusted oracle, and none was wired in. The `IntegrityStatus` is set by an `investigator` address — a single-point centralisation risk. The bond also uses the deprecated `.transfer()` pattern.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
```
Standalone bond — no base class, only reentrancy protection.

---

### Enums

**`IntegrityStatus`**
```
Corrupted   = 0  — athlete has confirmed violations
Declining   = 1  — integrity score falling
Stable      = 2  — neutral
Rising      = 3  — improving
Elite       = 4  — sustained excellence
```

**`ViolationType`**
```
MatchFixing        = 0  — 100 % stake forfeit
PEDUsage           = 1  — 80 % forfeit
GamblingViolation  = 2  — 70 % forfeit
LoadManagementAbuse = 3 — penalty (amount not specified in enum; moderate)
TankingParticipation = 4 — penalty
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `nextBondId` | `uint256` | Bond ID counter. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `integrityRecords` | `mapping(uint256 => IntegrityRecord[])` | Integrity score history per bond. |
| `violationReports` | `mapping(uint256 => ViolationReport[])` | Filed violation reports. |
| `yieldPool` | `uint256` | Separate pool funding appreciation payouts. |
| `owner` | `address` | Contract owner. |
| `pendingOwner` | `address` | Two-step ownership transfer target. |
| `WHISTLEBLOWER_REWARD_BPS` | `uint256` constant = `1000` | 10 % of slashed amount to whistleblower. |
| `MIN_MATURITY` | `uint256` constant | 1 year in seconds. |
| `MAX_MATURITY` | `uint256` constant | 10 years in seconds. |

---

### Structs

**`Bond`**
```
bondId          uint256  — unique ID
fan             address  — staker
athleteOrTeam   string   — subject of the bond
stakeAmount     uint256  — ETH staked
createdAt       uint256  — creation timestamp
maturityDate    uint256  — earliest settlement date
active          bool
status          IntegrityStatus  — current status
investigator    address  — address allowed to set status
```

**`IntegrityRecord`**
```
timestamp   uint256
score       uint256  — 0-10000
status      IntegrityStatus
verifier    address
notes       string
```

**`ViolationReport`**
```
timestamp       uint256
reporter        address
violationType   ViolationType
evidence        string  — off-chain evidence hash or description
confirmed       bool    — set true by investigator
```

---

### Functions

#### `createBond(athleteOrTeam, maturitySeconds, investigator)`
- `payable`; requires `msg.value > 0`
- `maturitySeconds` must be within `[MIN_MATURITY, MAX_MATURITY]`
- Sets initial `IntegrityStatus` to `Stable`
- Emits `BondCreated`

#### `addIntegrityRecord(bondId, score, status, notes)`
- Only callable by `bonds[bondId].investigator`
- Appends a new `IntegrityRecord`
- Updates `bonds[bondId].status`

#### `reportViolation(bondId, violationType, evidence)`
- Open to any address (intended for fans/whistleblowers)
- Appends a pending `ViolationReport`

#### `confirmViolation(bondId, reportIndex)`
- Only investigator
- Sets `violationReports[bondId][reportIndex].confirmed = true`
- Triggers stake forfeit based on `violationType`:
  - `MatchFixing` → 100 % forfeited; 10 % of that to reporter as whistleblower reward
  - `PEDUsage` → 80 % forfeited; 10 % of that to reporter
  - `GamblingViolation` → 70 % forfeited; 10 % to reporter
  - Others → smaller configurable penalties

**Forfeit mechanic:** Slashed amounts are transferred from `bond.stakeAmount` to a `penaltyPool` stored in the contract, minus the whistleblower reward. The whistleblower reward is sent immediately via `.transfer()`.

#### `averageIntegrityScore(bondId) → uint256`
Iterates all `integrityRecords` for the bond; returns the arithmetic mean score. Returns 5 000 if no records.

#### `consistencyScore(bondId) → uint256`
Measures inverse variance. Computes the mean, then sums squared deviations, then returns:
```
consistencyScore = 10000 − min(10000, variance / 10)
```
Higher score = more consistent = more predictable athlete. Returns 10 000 if fewer than two records.

#### `timeMultiplier(bondId) → uint256`
```
elapsed = maturityDate − createdAt
yearsHeld = elapsed / 31_536_000
multiplier = 100 + (yearsHeld × 80)   (range 100–500 capped at 5× for 5-year max)
```

#### `integrityStatusMultiplier(status) → uint256`
```
Elite      → 200
Rising     → 150
Stable     → 100
Declining  → 75
Corrupted  → 0
```

#### `calculateSettlement(bondId) → uint256`
```
fanShare = bond.stakeAmount
         × statusMultiplier(bond.status) / 100
         × (1 + consistencyBonus / 100)
         × timeMultiplier / 100
```
Plus, if `averageIntegrityScore ≥ 8 000` and bond is ≥ 5 years old, adds a **5-year clean record bonus** of `stakeAmount × 20 / 100`.

Appreciation above `stakeAmount` is drawn from `yieldPool`.

#### `settleBond(bondId)`
- `nonReentrant`
- Requires `block.timestamp >= bond.maturityDate`
- Computes settlement; sends fan their share via `.transfer()`
- Emits `BondSettled`

#### `donateToYieldPool()`
- `payable`, open to anyone
- Increases `yieldPool`

#### `transferOwnership(newOwner)` / `acceptOwnership()`
Two-step ownership transfer pattern.

---

### Math Summary

| Computation | Formula |
|---|---|
| Average integrity score | `sum(records) / count` |
| Consistency score | `10000 − min(10000, variance / 10)` |
| Time multiplier | `100 + years × 80`, range 100–500 |
| Status multiplier | Lookup: 0 / 75 / 100 / 150 / 200 |
| Settlement | `stake × status/100 × consistency × time / 100` |
| Whistleblower reward | `forfeitAmount × 10 / 100` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, fan, athleteOrTeam, stakeAmount, maturityDate)` | `createBond` |
| `IntegrityRecordAdded(bondId, score, status)` | `addIntegrityRecord` |
| `ViolationReported(bondId, reporter, type)` | `reportViolation` |
| `ViolationConfirmed(bondId, reportIndex, penaltyAmount)` | `confirmViolation` |
| `WhistleblowerRewarded(reporter, amount)` | `confirmViolation` |
| `BondSettled(bondId, fan, amount)` | `settleBond` |

---

### Design Intent

Create a financial incentive for fans to hold athletes accountable over multi-year windows. Whistleblower rewards create a self-policing ecosystem where bad actors are economically exposed. Elite athletes who maintain clean records over five years reward patient believers with up to 2× appreciation.

### Why It Didn't Make Production

1. **Centralised investigator** — a single `investigator` address has unilateral power to confirm violations and change integrity status. No multi-sig or oracle quorum.
2. **Unimplemented fanConsensus** — the `_calculateFanConsensusScore` function referenced in settlement always returns 5 000 (hardcoded stub). The full fan-consensus scoring layer was never built.
3. **Deprecated `.transfer()` pattern** — throughout the settlement and whistleblower payout paths.
4. **No oracle for sports data** — integrity data is entirely manual and off-chain.
5. **Yield pool funding** — appreciation beyond initial stake must come from a separately donated `yieldPool` with no automated replenishment mechanism.

---

---

# 3. VaultfireDAO.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VaultfireDAO.sol`
**Lines:** 219
**Contains:** Two contracts — `VaultfireGuardianToken` and `VaultfireDAO`

## What It Was Supposed to Do

Provides the on-chain governance layer for the Vaultfire system. `VaultfireGuardianToken` is an ERC-20 voting token minted by attested guardians. `VaultfireDAO` is a full OpenZeppelin Governor that coordinates guardian votes and, when a proposal passes, can call `publishMissionEvo()` on the base oracle to record new system virtue/weight configurations.

## Why It Was Likely Deprecated

The DAO was archived because the guardian attestation model (off-chain attestation → on-chain mint) was redesigned to use Dilithium-based zero-knowledge attestations rather than a simple `ATTESTOR_ROLE` mint. The two-contract file structure was also refactored into separate files.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3–L16 imports
```
Pulls in the full OpenZeppelin Governor stack plus ERC20Votes extensions. Notably imports `Nonces` because both `ERC20Permit` and `ERC20Votes` define a `nonces()` function — the explicit import resolves the ambiguity.

---

### Contract 1: `VaultfireGuardianToken`

**Inheritance chain:** `AccessControl`, `ERC20Burnable`, `ERC20Permit`, `ERC20Votes`

```
L20    bytes32 public constant ATTESTOR_ROLE = keccak256("ATTESTOR_ROLE");
```
Role that authorises an address to mint guardian voting weight. Intended for a trusted attestation service or multisig.

```
L22    event GuardianAttested(address guardian, uint256 weight, string memo, uint256 newBalance);
```
Emitted whenever voting weight is minted; `memo` carries the off-chain attestation reference.

```
L24–L30 constructor(address admin)
```
Initialises ERC20 as "Vaultfire Guardian" (VFG) and ERC20Permit with domain "Vaultfire Guardian". Grants `DEFAULT_ADMIN_ROLE` to `admin`.

```
L33–L43 function attest(address guardian, uint256 weight, string memo)
```
- Requires `ATTESTOR_ROLE`
- Calls `_mint(guardian, weight)` — increases the guardian's voting power
- `weight` is denominated in raw token units; the calling attestor decides the magnitude
- Returns `newBalance` for convenience
- Emits `GuardianAttested`

```
L45–L50 function _update(address from, address to, uint256 amount)
```
Required override to reconcile `ERC20` and `ERC20Votes`. Delegates to `super._update` which triggers the checkpoint logic in `ERC20Votes`.

```
L52–L58 function nonces(address owner)
```
Overrides both `ERC20Permit` and `Nonces` to resolve the diamond-inheritance conflict. Delegates to `super.nonces`.

---

### Contract 2: `VaultfireDAO`

**Inheritance chain:** `Governor`, `GovernorSettings`, `GovernorCountingSimple`, `GovernorVotes`, `GovernorVotesQuorumFraction`, `GovernorTimelockControl`

```
L73    uint256 public constant RESONANCE_APPROVAL_BPS = 5_100;
```
Proposals must receive at least 51 % of total participating votes (for + against + abstain) to succeed — a stricter threshold than simple majority of for-vs-against.

```
L74    VaultfireGuardianToken public immutable guardianToken;
L75    address public immutable baseOracle;
```
Stored at construction time; immutable so neither can be changed post-deployment (intentional governance rigidity).

```
L92    GovernorSettings(14_400, 50_400, 0)
```
- Voting delay: 14 400 blocks (~2 days at 12 s/block)
- Voting period: 50 400 blocks (~7 days)
- Proposal threshold: 0 tokens (any guardian can propose)

```
L94    GovernorVotesQuorumFraction(4)
```
4 % quorum — at least 4 % of total supply must vote for a proposal to be valid.

---

#### `proposeMissionEvo(virtues, weights, description) → proposalId`

```
L105   require(virtues.length == weights.length, "VaultfireDAO:length");
L106   require(virtues.length != 0, "VaultfireDAO:empty");
```
Validates that virtue names and weights arrays are parallel and non-empty.

```
L113–L120
```
Constructs a standard Governor proposal with a single action:
- Target: `baseOracle`
- Value: 0 ETH
- Calldata: `abi.encodeWithSignature("publishMissionEvo(string[],uint256[])", virtues, weights)`

This pattern encodes the function call at proposal time rather than execution time, which means the exact virtue configuration is visible and auditable in the proposal before any vote is cast.

```
L122   proposalId = propose(targets, values, calldatas, description);
```
Delegates to the standard Governor `propose`, which checks quorum, records the proposal, and starts the voting delay period.

---

#### `_voteSucceeded(proposalId) → bool`

```
L202   (againstVotes, forVotes, abstainVotes) = proposalVotes(proposalId);
L203   total = againstVotes + forVotes + abstainVotes;
L204   if (total == 0) return false;
L207   return forVotes * 10_000 >= total * RESONANCE_APPROVAL_BPS;
```
This is the critical deviation from the OpenZeppelin default. The default `GovernorCountingSimple._voteSucceeded` checks only `forVotes > againstVotes`. This override checks `forVotes / total ≥ 51 %`, meaning a strong abstain-vote bloc can defeat a proposal even if for > against. This was intentional — Vaultfire governance requires affirmative supermajority participation, not just relative support.

**Math:** `forVotes × 10 000 ≥ total × 5 100` resolves to `forVotes / total ≥ 0.51`.

---

### Override Boilerplate (L136–L217)

The remaining functions (`proposalNeedsQueuing`, `_queueOperations`, `_executeOperations`, `_cancel`, `_executor`, `proposalThreshold`, `state`, `supportsInterface`) are required inheritance disambiguation overrides. Each calls `super.*` to delegate to the appropriate parent implementation per OpenZeppelin's linearisation order. No custom logic exists in any of these.

---

### Events

| Event | Trigger |
|---|---|
| `GuardianAttested(guardian, weight, memo, newBalance)` | `VaultfireGuardianToken.attest` |
| `ProposalCreated(id, proposer)` | `VaultfireDAO.propose` |
| `MissionEvoProposal(id, proposer, virtues, weights, description)` | `proposeMissionEvo` |

Plus all standard Governor events (`ProposalQueued`, `ProposalExecuted`, `VoteCast`, etc.) inherited from OpenZeppelin.

---

### Design Intent

On-chain governance where the guardian council — humans who have earned voting weight through real-world attestations — can collectively update the Vaultfire system's virtue weighting. The `RESONANCE_APPROVAL_BPS` threshold ensures changes require genuine broad consent, not just a narrow plurality.

### Why It Didn't Make Production

1. **ATTESTOR_ROLE is a centralisation risk** — one compromised attestor address can mint unlimited voting weight.
2. **Redesign to ZK attestation** — the attestation model was replaced with Dilithium + Groth16 zero-knowledge proofs. A new DAO version was written to consume those proofs directly.
3. **Two-contract file structure** — during refactoring the guardian token and DAO were separated into individual files for better auditability and deployment management.
4. **Proposal threshold = 0** — any guardian token holder can propose, which in combination with a permissioned `ATTESTOR_ROLE` concentrates power in whoever controls attestation.

---

---

# 4. VerdantAnchorBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VerdantAnchorBondsV2.sol`
**Lines:** ~427
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

V2 of the earth-regeneration bond. A landowner and regenerator partner to restore ecological health across five metrics. The contract pays the regenerator for real, verified physical work; the landowner receives 40 % of appreciation. A greenwashing penalty (less than 50 % of verifications confirming physical work) zeroes the regenerator's share.

## Why It Was Likely Deprecated

The `OPEN_SOURCE` and `PRIVACY_DEFAULT` mission checks in V2 are unrelated to land stewardship and their inclusion was a copy-paste artifact from a builder-focused template. The architectural decision to route everything through `BaseYieldPoolBond` also meant the yield pool needed funding from a source that was never defined. Superseded by a revised version integrating a dedicated ecological oracle.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L3   SPDX, pragma, imports (BaseYieldPoolBond)
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `ecologicalMetrics` | `mapping(uint256 => EcologicalMetrics[])` | Timestamped readings. |
| `verifications` | `mapping(uint256 => Verification[])` | Physical-work confirmations. |
| `bondDistributions` | `mapping(uint256 => Distribution[])` | Settlement records. |
| `earthFundBalance` | `uint256` | Accumulated 10 % earth-fund share. |
| `GREENWASHING_VERIFICATION_THRESHOLD` | `uint256` constant = `50` | % physical verifications below which penalty applies. |

---

### Structs

**`Bond`**
```
bondId          uint256
regenerator     address  — who performs the physical work
landowner       address  — land rights holder
landDescription string
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`EcologicalMetrics`**
```
timestamp               uint256
soilHealth              uint256  — 0-10000
biodiversity            uint256  — 0-10000
carbonSequestration     uint256  — 0-10000
waterQuality            uint256  — 0-10000
ecosystemResilience     uint256  — 0-10000
submitter               address
physicalWorkVerified    bool     — was in-person work confirmed?
```

**`Verification`**
```
timestamp           uint256
verifier            address
confirmsPhysicalWork bool
notes               string
localResident       bool  — is verifier local to the land?
```

---

### Functions

#### `createBond(regenerator, landowner, landDescription)`
- `payable`; only owner can call (unusual — restricts bond creation to contract owner)
- Stores bond; emits `BondCreated`

#### `submitMetrics(bondId, soil, biodiversity, carbon, water, resilience, physicalWorkVerified)`
- Only `bonds[bondId].regenerator`
- Appends `EcologicalMetrics`

#### `addVerification(bondId, confirmsPhysicalWork, notes, localResident)`
- Open to anyone
- Appends `Verification`

#### `regenerationScore(bondId) → uint256`
Average of the five ecological metrics from the latest reading:
```
score = (soilHealth + biodiversity + carbonSequestration + waterQuality + ecosystemResilience) / 5
```
Returns 5 000 if no metrics.

#### `greenwashingDetected(bondId) → bool`
```
physicalCount = count of verifications where confirmsPhysicalWork = true
physicalPercent = physicalCount * 100 / total
return physicalPercent < GREENWASHING_VERIFICATION_THRESHOLD  (50%)
```
Returns false if no verifications exist (benefit of the doubt given to new bonds).

#### `calculateBondValue(bondId) → uint256`
```
bondValue = stakeAmount × avgScore / 5000
```
Where `avgScore` is `regenerationScore(bondId)`. This is the simplified V2 formula — V1 used a multi-factor product with physical-work and local-verification multipliers.

#### `distributeBond(bondId)`
- `nonReentrant`, `whenNotPaused`
- Checks `DISTRIBUTION_TIMELOCK`
- Checks `_requireMissionCompliance()` (OPEN_SOURCE, PRIVACY_DEFAULT)
- Detects greenwashing
- On **no greenwashing:** appreciation split 50 % regenerator / 40 % landowner / 10 % earthFund
- On **greenwashing:** 0 % regenerator / 100 % landowner
- Calls `_useYieldPool` for payouts
- Emits `BondDistributed` or `GreenwashingPenalty`

---

### Math Summary

| Computation | Formula |
|---|---|
| Regeneration score | `(soil + bio + carbon + water + resilience) / 5` |
| Bond value | `stake × avgScore / 5000` |
| Greenwashing threshold | `physicalVerif% < 50` |
| Normal split | 50 / 40 / 10 regenerator / landowner / fund |
| Greenwashing split | 0 / 100 / 0 |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, regenerator, landowner, stakeAmount)` | `createBond` |
| `MetricsSubmitted(bondId, timestamp)` | `submitMetrics` |
| `VerificationAdded(bondId, verifier)` | `addVerification` |
| `BondDistributed(bondId, regeneratorShare, landownerShare, earthFundShare)` | `distributeBond` |
| `GreenwashingPenalty(bondId)` | `distributeBond` when penalty fires |

---

### Design Intent

Make landowners financially motivated to hire genuine regenerators, while regenerators earn appreciation only for physically verified ecological improvements. The 10 % earth fund accumulates protocol-level capital for further regeneration grants.

### Why It Didn't Make Production

1. **Mission principle mismatch** — checking `OPEN_SOURCE_VERIFIABLE` and `PRIVACY_DEFAULT` for a land-stewardship bond is semantically wrong; these were copy-pasted from a builder contract template.
2. **Owner-only bond creation** — restricts network growth; should be open to any regenerator/landowner pair.
3. **Simplified V2 formula** — the `stake × score / 5000` formula removed the physical-work and local-verification multipliers that gave V1 its nuance; a subsequent version restored them properly.
4. **Yield pool dependency** — appreciation payouts require the yield pool to be funded externally; no automated replenishment existed.

---

---

# 5. CommonGroundBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/CommonGroundBonds.sol`
**Lines:** ~525
**Inherits:** `ReentrancyGuard`, `MissionEnforcement` (standalone)

## What It Was Supposed to Do

A two-person bond for bridge-building across political or social divides. Both parties stake ETH. The bond appreciates when external witnesses confirm that the bridge-builders have genuinely understood each other, collaborated, and respected one another. A division penalty applies if respect or bridge quality falls below thresholds.

## Why It Was Likely Deprecated

Uses the deprecated `payable().transfer()` ETH dispatch pattern throughout, which was the primary reason for retirement and replacement by `CommonGroundBondsV2`. The five-dimensional multiplier stack also produced wildly variable bond values making the contract difficult to audit.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma, ReentrancyGuard + MissionEnforcement imports
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `bridgeMetrics` | `mapping(uint256 => BridgeMetrics[])` | Metric history. |
| `witnesses` | `mapping(uint256 => Witness[])` | Cross-community witness verifications. |
| `totalRippleEffect` | `mapping(uint256 => uint256)` | Cumulative ripple effect counter. |
| `communityBridgeFund` | `uint256` | Accumulated community share. |

---

### Structs

**`Bond`**
```
bondId          uint256
builderA        address
builderB        address
communityA      string  — what community/side is builderA from?
communityB      string
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`BridgeMetrics`**
```
timestamp           uint256
submitter           address
understandingQuality uint256  — 0-10000
collaborationScore  uint256  — 0-10000
respectLevel        uint256  — 0-10000
rippleEffect        uint256  — how many others were impacted?
notes               string
```

**`Witness`**
```
timestamp           uint256
witness             address
fromCommunityA      bool  — is witness from same side as builderA?
confirmsUnderstanding bool
confirmsRespect     bool
notes               string
```

---

### Functions

#### `createBond(builderB, communityA, communityB)`
- `payable`; requires `msg.value > 0`
- `builderB` must be a different address from `msg.sender`
- Sets `builderA = msg.sender`
- Emits `BondCreated`

#### `submitBridgeMetrics(bondId, understandingQuality, collaborationScore, respectLevel, rippleEffect, notes)`
- Only `builderA` or `builderB`
- Appends metrics; adds `rippleEffect` to `totalRippleEffect[bondId]`

#### `addWitness(bondId, fromCommunityA, confirmsUnderstanding, confirmsRespect, notes)`
- Open to anyone (intended for community members)
- Appends witness record

#### `bridgeQualityScore(bondId) → uint256`
Average of the last 10 `BridgeMetrics` entries:
```
score = (sum of avgMetric per recent entry) / count
where avgMetric = (understanding + collaboration + respect) / 3
```
Returns 5 000 if no metrics.

#### `rippleEffectMultiplier(bondId) → uint256`
```
total = totalRippleEffect[bondId]
multiplier = 100 + total × 10
return min(multiplier, 300)   (capped at 3.0×)
```
More people impacted by the bridge = higher multiplier, capped at 300 %.

#### `dualPartyMultiplier(bondId) → uint256`
Counts recent witnesses from each community side:
- Both sides represented → 100–150 based on balance
- One side only → 50–100 based on count

#### `crossCommunityWitnessMultiplier(bondId) → uint256`
Based on confirmation rates across recent witnesses:
```
avgRate = (understandingConfirmations + respectConfirmations) / (2 × totalWitnesses) × 100
≥ 80 % → 130
≥ 50 % → 100
else   → 70 + avgRate / 4
```

#### `timeMultiplier(bondId) → uint256`
```
years = age / 31_536_000
years < 1 → 100
years 1–5 → 100 + years × 30
years > 5 → 250
```

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × quality × ripple × dualParty × witnesses × time) / 10_000_000_000
```
Five multipliers multiplied together before dividing. The 10 000 000 000 divisor is a rough attempt to normalise five 100–300 range values back to ETH scale. Due to the multiplicative compounding this is numerically unstable across extreme input combinations.

#### `shouldApplyDivisionPenalty(bondId) → bool`
```
latest quality < 4000  OR  latest respectLevel < 3000  → true
```

#### `distributeBond(bondId)`
- `nonReentrant`
- Calls `_requireMissionCompliance()`
- If **no penalty:** 60 % to bridge builders (30/30 each), 40 % to `communityBridgeFund`
- If **penalty:** 50 % refunded to each builder, 0 % to community fund
- Uses `payable().transfer()` — **deprecated**
- Emits `BondDistributed` or `DivisionPenalty`

---

### Math Summary

| Computation | Formula |
|---|---|
| Bridge quality score | Average of (understanding + collaboration + respect)/3 across last 10 readings |
| Ripple multiplier | `100 + ripple × 10`, capped 300 |
| Dual party multiplier | 50–150 based on witness community balance |
| Cross-community witness multiplier | 70–130 based on confirmation rates |
| Time multiplier | 100–250 over 5 years |
| Bond value | `stake × quality × ripple × dual × witnesses × time / 10_000_000_000` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, builderA, builderB)` | `createBond` |
| `MetricsSubmitted(bondId)` | `submitBridgeMetrics` |
| `WitnessAdded(bondId, witness)` | `addWitness` |
| `BondDistributed(bondId, builderAShare, builderBShare, communityShare)` | `distributeBond` |
| `DivisionPenalty(bondId)` | `distributeBond` when penalty fires |

---

### Design Intent

Create an economic incentive for politically or culturally opposed individuals to actively build bridges rather than entrench division. Witnesses from both communities provide accountability. Long-duration bonds with wide ripple effects produce the highest yields.

### Why It Didn't Make Production

1. **`payable().transfer()` deprecated pattern** — replaced by `.call{}` in V2.
2. **Numerically unstable multiplier stack** — five compounding 100–300-range multipliers with a fixed divisor is difficult to calibrate and produces extreme outliers.
3. **No Sybil resistance on witnesses** — anyone can add a witness entry; there is no stake or identity check.
4. **Missing timelock** — no `DISTRIBUTION_TIMELOCK` check; bonds can be settled immediately after creation.
5. **Community fund has no withdrawal mechanism** — ETH in `communityBridgeFund` is permanently locked with no governance over its use.

---

---

# 6. SwapGate.sol

**Path:** `theloopbreaker-site/contracts/deprecated/SwapGate.sol`
**Lines:** 99
**Inherits:** `Ownable`

## What It Was Supposed to Do

A token swap gateway allowing holders of Vaultfire tokens to exchange them for ETH, USDC, or SOL. A 0.10 % fee is charged on each swap. KYC is enforced by default; addresses on the `trustedID` list bypass the KYC gate.

## Why It Was Likely Deprecated

`swapToSOL` is a complete stub — it collects the fee, pulls tokens, and emits an event, but performs no cross-chain bridging. The 1:1 exchange rate is also hardcoded with no price discovery, making the contract unusable in practice without manual ETH/USDC pre-funding.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
L4    import "@openzeppelin/contracts/access/Ownable.sol";
```

```
L12   IERC20 public immutable vaultfire;
L13   IERC20 public immutable usdc;
```
Both token addresses are set at construction and cannot be changed. This was intentional — prevents owner from redirecting swaps to malicious tokens.

```
L14   address public feeRecipient;
L15   uint256 public feeBps = 10;   // 0.10 %
L16   bool public kycRequired = true;
L17   mapping(address => bool) public trustedID;
```
`feeBps` is capped at 100 (1 %) by `setFee`. `kycRequired` can be toggled off by owner for testing or open deployments.

```
L27–L33 constructor(IERC20 _vaultfire, IERC20 _usdc, address _feeRecipient)
```
Validates non-zero addresses for all three parameters. Sets `Ownable` to `msg.sender`.

```
L35–L39 modifier checkKYC()
```
If `kycRequired` is true and `msg.sender` is not in `trustedID`, reverts with `"kyc required"`. This is a simple allowlist gate — no actual KYC verification occurs on-chain.

```
L42    receive() external payable {}
```
Enables the contract to receive ETH (needed to hold the ETH reserve for `swapToETH`).

---

### Admin Functions

#### `setFee(newFeeBps)`
- `onlyOwner`
- Requires `newFeeBps <= 100` (max 1 %)
- Updates `feeBps`

#### `setTrustedID(user, trusted)`
- `onlyOwner`
- Grants or revokes KYC bypass

#### `depositVaultfire(amount)` / `depositUSDC(amount)`
- `onlyOwner`
- Pulls tokens from owner's wallet into the contract reserve

---

### Swap Functions

#### `swapToETH(amount)`
```
L73   fee = amount × feeBps / 10000
L74   vaultfire.transferFrom(sender, feeRecipient, fee)         — fee portion to fee recipient
L75   vaultfire.transferFrom(sender, address(this), amount-fee) — net amount into contract
L77   ethAmount = amount - fee                                  — 1:1 minus fee
L78   require(address(this).balance >= ethAmount)               — must have ETH reserves
L79   payable(msg.sender).transfer(ethAmount)                   — send ETH, deprecated pattern
```
Assumption: 1 Vaultfire token = 1 ETH wei. There is no oracle or price feed. In practice this means the owner must pre-fund the contract with ETH equal to anticipated swap volume.

#### `swapToUSDC(amount)`
Similar to `swapToETH` but sends USDC rather than ETH. Same 1:1 ratio assumption.

#### `swapToSOL(amount, solanaAddress)`
```
L93   fee = amount × feeBps / 10000
L94   vaultfire.transferFrom(sender, feeRecipient, fee)
L95   vaultfire.transferFrom(sender, address(this), amount-fee)
L97   emit SwapToSol(msg.sender, solanaAddress, amount)
      — NO cross-chain transfer occurs
```
`solanaAddress` is a `bytes32` Solana public key stored in the event for off-chain bridge processing. The contract itself has no bridge; a listening service would need to detect the event and send SOL on the Solana side. That service was never built.

---

### Math Summary

| Computation | Formula |
|---|---|
| Fee amount | `amount × feeBps / 10000` |
| Net out amount | `amount − fee` |
| Exchange rate | 1:1 (Vaultfire:ETH/USDC/SOL), no oracle |

---

### Events

| Event | Trigger |
|---|---|
| `FeeRecipientSet(recipient)` | `setFeeRecipient` |
| `FeeUpdated(feeBps)` | `setFee` |
| `TrustedIDSet(user, trusted)` | `setTrustedID` |
| `KycRequiredSet(required)` | `setKycRequired` |
| `Swap(user, asset, amountIn, amountOut)` | `swapToETH`, `swapToUSDC` |
| `SwapToSol(user, solanaAddress, amountIn)` | `swapToSOL` |

---

### Design Intent

A lightweight swap entry point allowing Vaultfire ecosystem participants to convert their tokens to widely accepted value forms. The KYC gate was included to comply with anticipated regulatory requirements without implementing full on-chain identity verification.

### Why It Didn't Make Production

1. **`swapToSOL` is a stub** — no cross-chain execution; the off-chain bridge service was never built.
2. **Hardcoded 1:1 rate** — no price oracle; economically non-functional.
3. **Reserve pre-funding required** — owner must manually maintain ETH/USDC reserves; no AMM or automated liquidity.
4. **`.transfer()` in `swapToETH`** — deprecated pattern; should use `.call{}`.
5. **KYC is an allowlist, not verification** — `trustedID` is manually managed by owner; does not integrate with any identity provider.

---

---

# 7. BuilderBeliefBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/BuilderBeliefBondsV2.sol`
**Lines:** ~576
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

V2 of the builder belief bond. Stakers back software builders across three tiers (Supporter / Believer / Champion) with vesting periods from 90 to 365 days. The bond appreciates when builders demonstrably build (code commits, deployments, users served) rather than transact (high token volume penalises the score). The `_useYieldPool` path handles appreciation payouts; a timelock prevents instant distribution.

## Why It Was Likely Deprecated

The divisor was changed from V1's 100 000 000 to 50 000 000 as part of the 2026-01-07 math fix, but the community verification logic was not redesigned alongside — verification data from a small or absent community defaulted to 100 (neutral) in ways that masked poor builder activity. Superseded by a version with mandatory minimum verifications.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L3   SPDX, pragma ^0.8.25, import BaseYieldPoolBond
```

---

### Enums

**`BeliefTier`**
```
Supporter  = 0   (< 0.001 ETH stake, 90-day vest)
Believer   = 1   (0.001–0.01 ETH, 180-day vest)
Champion   = 2   (> 0.01 ETH, 365-day vest)
```

---

### State Variables

Same structure as V1 but includes `yieldPool` via `BaseYieldPoolBond`.

| Variable | Type | Purpose |
|---|---|---|
| `BELIEVER_THRESHOLD` | `uint256` constant = `0.001 ether` | Minimum stake for Believer tier. |
| `CHAMPION_THRESHOLD` | `uint256` constant = `0.01 ether` | Minimum stake for Champion tier. |
| `SUPPORTER_VESTING` | `uint256` constant = `7 776 000` | ~90 days in seconds. |
| `BELIEVER_VESTING` | `uint256` constant = `15 552 000` | ~180 days. |
| `CHAMPION_VESTING` | `uint256` constant = `31 536 000` | ~365 days. |
| `BUILDING_THRESHOLD` | `uint256` constant = `4000` | Building score below this = transacting penalty. |
| `TRANSACTION_PENALTY` | `uint256` constant = `5000` | Transaction volume above this = score reduction. |

---

### Functions

#### `createBond(builder, builderName, projectDescription)`
- `payable`, `whenNotPaused`
- Assigns tier and vesting based on `msg.value`:
  - `< BELIEVER_THRESHOLD` → Supporter, 90-day vest
  - `BELIEVER_THRESHOLD ≤ value < CHAMPION_THRESHOLD` → Believer, 180-day vest
  - `≥ CHAMPION_THRESHOLD` → Champion, 365-day vest
- Stores bond; emits `BondCreated`, `TierAchieved`

#### `submitBuildingMetrics(bondId, commits, deployments, users, openSource, innovation, transactionVolume, notes)`
- `bondExists` modifier
- No restriction on submitter — builder or community member can submit
- Appends `BuildingMetrics`

#### `addCommunityVerification(bondId, confirmsBuilding, confirmsUseful, confirmsOpenSource, relationship, notes)`
- Open to anyone
- Appends `CommunityVerification`

#### `buildingScore(bondId) → uint256`
Reads the **latest** `BuildingMetrics` entry and applies weighted scoring:
```
commitScore  = min(commits × 100, 10000)       — capped at 100 commits
deployScore  = min(deploys × 1000, 10000)      — capped at 10 deployments
userScore    = min(users × 10, 10000)           — capped at 1000 users

score = (commitScore × 30 + deployScore × 30 + userScore × 20
       + openSourceScore × 10 + innovationScore × 10) / 100
```

#### `buildingVsTransacting(bondId) → uint256`
```
building = buildingScore(bondId)
if transactionVolume > TRANSACTION_PENALTY (5000):
    penalty = (transactionVolume - 5000) / 100
    return max(0, building - penalty)
else:
    return building
```
High transacting behaviour directly subtracts from the building score.

#### `communityVerificationMultiplier(bondId) → uint256`
Iterates verifications within the last 180 days:
```
avgRate = avg of (building%, useful%, openSource%) confirmation rates
≥ 80 % → 130
≥ 50 % → 100
else   → 70 + avgRate / 4
```
Returns 100 if no recent verifications (neutral default — this was the identified flaw).

#### `vestingMultiplier(bondId) → uint256`
```
vestedTime = min(now, vestingUntil) - createdAt
vestedPercent = vestedTime × 100 / totalVestingPeriod
multiplier = 50 + vestedPercent          (range 50–150)
```
Fully vested bond earns a 1.5× multiplier; unvested earns a 0.5× penalty.

#### `timeMultiplier(bondId) → uint256`
```
years < 1 → 100
years 1–5 → 100 + years × 37
years ≥ 5 → 250
```

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × building × vesting × time) / 50_000_000
```
Note: V2 divisor is 50 000 000 (down from 100 000 000 in V1) per the 2026-01-07 math fix.

Community verification is **not included** in `calculateBondValue` in V2 (it was included in V1 as a fourth multiplier). This was an oversight — the verification data is collected but not used in the formula.

#### `shouldApplyTransactingPenalty(bondId) → bool`
```
building = buildingVsTransacting(bondId)
return building < BUILDING_THRESHOLD  (4000)
```

#### `distributeBond(bondId)`
- `nonReentrant`, `whenNotPaused`
- Checks `DISTRIBUTION_TIMELOCK`
- Computes appreciation
- If **no penalty:** 60 % builder, 30 % stakers, 10 % builderFund
- If **transacting penalty:** 100 % to builder (odd — should penalise builder, not reward them; this appears to be a logic inversion bug from V1)
- Calls `_useYieldPool(builderShare + stakersShare)`

---

### Math Summary

| Computation | Formula |
|---|---|
| Building score | Weighted (commits 30 + deploys 30 + users 20 + openSource 10 + innovation 10) / 100 |
| Building vs transacting | `buildingScore − max(0, (txVol − 5000) / 100)` |
| Verification multiplier | 70–130 based on community confirmation rates |
| Vesting multiplier | `50 + vestedPercent` (50–150) |
| Time multiplier | 100–250 over 5 years |
| Bond value | `(stake × building × vesting × time) / 50_000_000` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, staker, builder)` | `createBond` |
| `TierAchieved(bondId, staker, tier)` | `createBond` |
| `BuildingMetricsSubmitted(bondId, submitter)` | `submitBuildingMetrics` |
| `CommunityVerificationAdded(bondId, verifier)` | `addCommunityVerification` |
| `BondDistributed(bondId, builderShare, stakersShare)` | `distributeBond` |
| `TransactingPenalty(bondId, reason)` | `distributeBond` when penalty fires |

---

### Design Intent

Align financial return with genuine building activity. Anti-flipping vesting tiers mean short-term speculators earn the least; long-term believers in real builders earn the most.

### Why It Didn't Make Production

1. **Verification not used in bond value formula** — community verification data is collected but dropped from the `calculateBondValue` formula in V2 (present in V1), an oversight.
2. **Penalty logic inversion** — the transacting penalty sends 100 % to the builder, which rewards a misbehaving builder rather than punishing them.
3. **Neutral default for missing verifications** — returning 100 for absent verification data means unverified bonds are treated the same as well-verified ones.
4. **Divisor recalibration incomplete** — while the 2026-01-07 fix changed the divisor, the formula still produces multi-ETH outputs for mid-range inputs at Champion tier stake levels.

---

---

# 8. VaultfireRewardStream.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VaultfireRewardStream.sol`
**Lines:** 127
**Inherits:** `AccessControl`

## What It Was Supposed to Do

A token-based (ERC-20, not ETH) streaming reward contract. An admin or automation service calls `streamReward(recipient, amount)` to vest tokens linearly to a recipient over a configurable `streamDuration`. Recipients can call `claim()` at any time to pull currently vested tokens. A new stream rolls any unvested remainder forward rather than discarding it.

## Why It Was Likely Deprecated

Superseded by `RewardStream.sol` which is ETH-based (fitting Vaultfire's ETH-native bond economics) and has explicit two-step timelocked admin/governor transfer. `VaultfireRewardStream` only uses ERC-20 tokens and lacks the governor-controlled multiplier update pathway needed by `RewardMultiplier.sol`.

---

## Full Source with Line-by-Line Walkthrough

```
L7    contract VaultfireRewardStream is AccessControl {
L8        bytes32 public constant AUTOMATION_ROLE = keccak256("AUTOMATION_ROLE");
```
`DEFAULT_ADMIN_ROLE` (set to deployer) and `AUTOMATION_ROLE` are the two access tiers. Both can trigger `streamReward`.

```
L10   IERC20 public immutable rewardToken;
L11   uint64 public streamDuration;
```
`rewardToken` is fixed at deploy. `streamDuration` is the default vesting window for all new streams; can be updated by admin.

```
L13–L18 struct Stream
```
```
total    uint128  — total tokens in this stream
released uint128  — tokens already disbursed
start    uint64   — stream start timestamp
duration uint64   — stream duration in seconds
```
Packed into two storage slots (128 + 128 = 256 bits; 64 + 64 = 128 bits). Space-efficient design.

```
L20   mapping(address => Stream) private streams;
```
One stream per recipient at a time. A new `streamReward` call replaces (while rolling over) the existing stream.

---

### `claimable(address recipient) → uint256`

```
L63   if stream.total == 0 or duration == 0 → return 0
L68   if block.timestamp <= stream.start → return 0
L72   elapsed = block.timestamp − stream.start
L73   if elapsed >= duration → return total − released    (fully vested)
L76   vested = (total × elapsed) / duration               (linear vesting)
L77   if vested <= released → return 0
L79   return vested − released
```
Standard linear vesting. The `if vested <= released` guard handles the case where `claimable` is called twice in the same block without a new stream.

---

### `streamReward(recipient, amount)`
- Restricted to `DEFAULT_ADMIN_ROLE` or `AUTOMATION_ROLE`
- Pulls `amount` tokens from `msg.sender` via `transferFrom` (`_pullFunding`)
- Calls `_releaseAvailable(recipient, stream)` to disburse any currently vested tokens before resetting the stream
- Calculates `remaining = stream.total − stream.released`
- Resets stream:
  ```
  stream.total    = remaining + amount   (roll-over)
  stream.released = 0
  stream.start    = now
  stream.duration = streamDuration
  ```
- Emits `StreamScheduled`

**Roll-over design:** Unvested tokens are never lost. They are folded into the new stream. The new `total` reflects the sum of old unvested remainder and the new allocation.

---

### `claim()`
- Public; no access restriction
- Calls `_releaseAvailable(msg.sender, stream)` which reads `claimable` and sends that amount via `rewardToken.transfer`

---

### Math Summary

| Computation | Formula |
|---|---|
| Vested amount | `(total × elapsed) / duration` |
| Claimable | `vested − released` (if positive) |
| Roll-over total | `remaining + newAmount` |

---

### Events

| Event | Trigger |
|---|---|
| `StreamScheduled(recipient, amount, start, duration)` | `streamReward` |
| `StreamClaimed(recipient, amount, remaining)` | `_disburse` |
| `StreamDurationUpdated(duration)` | `setStreamDuration` |
| `AutomationRoleGranted(account)` | `grantAutomationRole` |
| `AutomationRoleRevoked(account)` | `revokeAutomationRole` |

---

### Design Intent

Provide a smooth ERC-20 reward distribution pipeline that prevents cliff-vesting. Automation bots can periodically top up streams; recipients pull at their convenience.

### Why It Didn't Make Production

1. **ERC-20 only** — Vaultfire's bond economics are ETH-native; the ETH-based `RewardStream.sol` was preferred.
2. **No governor multiplier pathway** — `RewardMultiplier.sol` calls `rewardStream.updateMultiplier(user, multiplier)` but `VaultfireRewardStream` has no such function.
3. **Single stream per recipient** — if a recipient has multiple independent reward sources they all compete for the single slot and the roll-over may lose track of which source provided which tokens.
4. **`_pullFunding` uses `msg.sender`** — the caller must pre-approve the contract to spend their tokens; this is workable but adds friction for automation bots.

---

---

# 9. VerdantAnchorBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VerdantAnchorBonds.sol`
**Lines:** ~554
**Inherits:** `ReentrancyGuard`, `MissionEnforcement` (standalone V1)

## What It Was Supposed to Do

V1 of the earth-regeneration bond. Same five ecological metrics as V2 but with a richer bond-value formula incorporating physical-work and local-verification multipliers. The V1 greenwashing penalty has an inverted split compared to V2.

## Why It Was Likely Deprecated

Uses deprecated `payable().transfer()` and has the inverted greenwashing penalty split (regenerator gets stake, landowner gets 0 — the opposite of what was intended; V2 corrected to 0/100). Also lacks timelock.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L5   SPDX, pragma ^0.8.25, ReentrancyGuard + MissionEnforcement imports
```

---

### Key Differences From V2

| Feature | V1 | V2 |
|---|---|---|
| Inheritance | Standalone | BaseYieldPoolBond |
| ETH transfer | `.transfer()` | `_useYieldPool()` |
| Timelock | No | Yes (DISTRIBUTION_TIMELOCK) |
| Greenwashing penalty | Regenerator gets stake, landowner 0 (inverted) | Regenerator 0, landowner 100 % (correct) |
| Bond value formula | Multi-factor product | Simple `stake × score / 5000` |
| `whenNotPaused` | No | Yes |

---

### Functions

#### `regenerationScore(bondId) → uint256`
Only averages entries where `physicalWorkVerified = true`:
```
count = entries where physicalWorkVerified
totalScore = sum(avgEcoScore) for those entries
return count > 0 ? totalScore / count : 5000
```
This differs from V2 where all entries are averaged; V1 deliberately discards unverified readings from the score.

#### `physicalWorkMultiplier(bondId) → uint256`
```
verifiedPercent = physicalVerifiedCount × 100 / totalCount
multiplier = verifiedPercent × 1.5     (0 to 150)
```
Returns 0 for no verifications, 150 for 100 % physical work confirmation.

#### `localVerificationMultiplier(bondId) → uint256`
Counts three confirmation types from verifications flagged `localResident = true`:
- `confirmsPhysicalWork`
- `confirmsEcological` (V1 has this extra field)
- `confirmsLongTerm`

Maps to range 50–150 based on average confirmation rate across the three types.

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × regen × physicalWork × localVerif × time) / 1_000_000_000
```
Where:
- `regen` = regeneration score (0–10 000)
- `physicalWork` = 0–150
- `localVerif` = 50–150
- `time` = 100–200

Divisor 1 000 000 000 normalises the product of four multipliers.

#### `distributeBond(bondId)` — greenwashing penalty (V1 bug)
```
if greenwashing:
    // V1 intended to punish regenerator but inverted the logic
    regeneratorShare = bond.stakeAmount    (WRONG — regenerator gets ALL)
    landownerShare = 0
    payable(bond.regenerator).transfer(regeneratorShare)   // deprecated
else:
    // Normal: 50/40/10
    regeneratorShare = appreciation × 50 / 100
    landownerShare   = appreciation × 40 / 100
    earthFundShare   = appreciation × 10 / 100
    payable(bond.regenerator).transfer(regeneratorShare)   // deprecated
    payable(bond.landowner).transfer(landownerShare)       // deprecated
```
**The greenwashing penalty is inverted.** When greenwashing is detected the regenerator receives the full stake amount — the opposite of the intended punishment. V2 corrected this.

---

### Math Summary

| Computation | Formula |
|---|---|
| Regeneration score | Average eco scores from physically-verified entries only |
| Physical work multiplier | `verifiedPercent × 1.5` (0–150) |
| Local verification multiplier | 50–150 based on local resident confirmation rates |
| Bond value | `(stake × regen × physicalWork × localVerif × time) / 1_000_000_000` |
| Normal split | 50 / 40 / 10 regenerator / landowner / earth fund |
| Greenwashing split (bug) | 100 / 0 / 0 regenerator / landowner / earth fund |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, regenerator, landowner, stake)` | `createBond` |
| `MetricsSubmitted(bondId, timestamp)` | `submitMetrics` |
| `VerificationAdded(bondId, verifier)` | `addVerification` |
| `BondDistributed(bondId, regen, landowner, earth)` | `distributeBond` |
| `GreenwashingPenalty(bondId)` | When penalty fires (with incorrect split) |

---

### Design Intent

Reward demonstrably physical ecological restoration backed by local community verification. The physical-work-only score filter was the core innovation — only metrics tied to actual ground-truthed work count.

### Why It Didn't Make Production

1. **Greenwashing penalty is inverted** — a critical logic bug rewards the bad actor.
2. **`payable().transfer()` deprecated** — all three transfer calls use the old pattern.
3. **No timelock on distribution** — bonds can be settled immediately.
4. **No `whenNotPaused` modifier** — no emergency stop mechanism.
5. **Superseded by V2** which fixed the penalty logic but simplified the formula too aggressively (removing physical-work and local-verification multipliers).

---

---

# 10. FreedomVow.sol

**Path:** `theloopbreaker-site/contracts/deprecated/FreedomVow.sol`
**Lines:** 68
**Inherits:** `BeliefOracle`

## What It Was Supposed to Do

A one-time ignition rite layered on top of the `BeliefOracle`. A guardian submits a human-readable vow text plus a zero-knowledge attestation (`zkSig`). If the oracle returns a resonance score above 50 and global resonance has not drifted, the guardian is marked as having vowed, a starter yield of 1 token (1e18) is queued in the reward stream, and a `FreedomIgnited` event is emitted containing the vow's `keccak256` hash.

## Why It Was Likely Deprecated

Archived because the `BeliefOracle` base contract itself was being redesigned to use Dilithium-based attestations. `FreedomVow` was tightly coupled to the old oracle interface and could not be migrated without a full rewrite.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L4    import {BeliefOracle} from "../BeliefOracle.sol";
L5    import {DilithiumAttestor} from "../DilithiumAttestor.sol";
L6    import {RewardStream} from "./RewardStream.sol";
```
All three imports are active (non-deprecated) production contracts. `FreedomVow` is the deprecated layer.

```
L8    contract FreedomVow is BeliefOracle {
```
Extends `BeliefOracle`. Inherits `queryBelief(vow, zkSig)`, `resonanceDrifted`, and the `rewardStream` reference.

```
L9    uint256 public constant STARTER_YIELD = 1e18;
```
1 token (denominated in 18-decimal units). This is the reward queued for each guardian on first ignition.

```
L11   uint256 private _guardianCount;
L13   mapping(address => bool) public vowed;
```
`_guardianCount` counts total ignitions (view via `freeGuardiansCount()`). `vowed` is a per-address permanent flag — once set it cannot be unset by the guardian (only through a contract upgrade).

```
L15–L19 custom errors
```
```
AlreadyVowed()      — guardian has already completed the rite
ResonanceDrifted()  — global oracle resonance is in a drift state
ResonanceTooLow()   — guardian's individual resonance score ≤ 50
```
Custom errors save gas vs string revert messages.

---

### `igniteFreedom(vow, zkSig) → resonance`

```
L39   address guardianAccount = msg.sender;
L40   if (vowed[guardianAccount]) revert AlreadyVowed();
```
Strict one-per-address gate. No batch vows.

```
L43   if (resonanceDrifted) revert ResonanceDrifted();
```
`resonanceDrifted` is a state variable in `BeliefOracle` set by the oracle admin when the system's collective belief signal is unstable. When drifted, no new vows can be ignited — the system is in a healing state.

```
L46   resonance = queryBelief(vow, zkSig);
```
Calls the parent `BeliefOracle.queryBelief` which validates the `zkSig` attestation and returns the guardian's resonance score. The vow text itself is hashed (not stored on-chain) in the emitted event.

```
L47   if (resonance <= 50) revert ResonanceTooLow();
```
Resonance must be above the midpoint. A score of exactly 50 is rejected.

```
L52   vowed[guardianAccount] = true;
L53   unchecked { _guardianCount += 1; }
```
State changes before the external interaction (correct CEI pattern). `unchecked` is safe because `_guardianCount` overflowing `uint256` in practice is not a concern.

```
L57   rewardStream.queueRewards(guardianAccount, STARTER_YIELD);
```
External interaction last (CEI-correct). Queues — does not immediately transfer — the starter yield. The guardian must later call `claimRewards` on the `RewardStream`.

```
L59   emit FreedomIgnited(guardianAccount, keccak256(bytes(vow)), resonance, STARTER_YIELD);
```
The vow's content is hashed in the event so the event log serves as a permanent commitment record without storing the full text on-chain.

---

### `freeGuardiansCount() → uint256`
Simple view returning `_guardianCount`. External systems can watch this number to assess community growth.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `STARTER_YIELD` | `uint256` constant = `1e18` | Reward queued per ignition. |
| `_guardianCount` | `uint256` private | Total ignitions. |
| `vowed` | `mapping(address → bool)` | Permanent vow record per guardian. |

### Events

| Event | Trigger |
|---|---|
| `FreedomIgnited(guardian, vowHash, resonance, starterYield)` | `igniteFreedom` |

---

### Design Intent

A lightweight ceremony contract that marks a guardian's entry into the Vaultfire belief system with an irreversible on-chain commitment. The ZK attestation ensures the vow is backed by verifiable belief state, not just a transaction.

### Why It Didn't Make Production

1. **Tightly coupled to old `BeliefOracle` interface** — the oracle redesign broke the inheritance chain.
2. **Vow is permanent** — no mechanism for a guardian to reconsider or a governance process to invalidate a vow in edge cases.
3. **Starter yield is flat** — every guardian receives exactly 1 token regardless of resonance score; a resonance-proportional reward was proposed but not implemented here.
4. **One contract, one rite** — the pattern was generalised into a composable rite system in production.

---

---

# 11. HealthCommonsBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/HealthCommonsBondsV2.sol`
**Lines:** ~532
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

A company stakes ETH on pollution reduction and health outcome improvement for a specific community. Two independent data streams — `PollutionMetrics` and `HealthOutcomes` — are submitted over time. The bond appreciates when both pollution decreases and health improves, as measured against baseline (first readings). A poisoning penalty fires if either stream falls below threshold.

## Why It Was Likely Deprecated

The divisor 100 000 000 in V2 (10× larger than the V1 divisor of 1 000 000) drastically reduced bond values; at mid-range scores a 1 ETH stake would appreciate to fractions of a wei. This overcorrection from the V1 uint256-underflow bug (see contract 33) made V2 economically inert. A subsequent version recalibrated the divisor.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma, BaseYieldPoolBond import
```

---

### Structs

**`Bond`**
```
bondId          uint256
company         address
communityName   string
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`PollutionMetrics`**
```
timestamp       uint256
airQuality      uint256  — 0-10000 (10000 = pristine)
waterQuality    uint256  — 0-10000
foodSafety      uint256  — 0-10000
submitter       address
```

**`HealthOutcomes`**
```
timestamp       uint256
lifeExpectancy  uint256  — 0-10000
cancerRate      uint256  — 0-10000 (10000 = zero cancer)
respiratoryHealth uint256
mentalHealth    uint256
childDevelopment uint256
populationCount uint256  — required for statistical validity
submitter       address
```

**`CommunityVerification`**
```
timestamp           uint256
verifier            address
confirmsImprovement bool
confirmsPhysical    bool
residencyYears      uint256
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `POISONING_POLLUTION_THRESHOLD` | `uint256` = `80` | Pollution score below this = penalty. |
| `POISONING_HEALTH_THRESHOLD` | `uint256` = `80` | Health score below this = penalty. |
| `POISONING_COMMUNITY_THRESHOLD` | `uint256` = `70` | Community verification below this = penalty. |

---

### Functions

#### `submitPollutionMetrics(bondId, air, water, food)`
- Only company
- Requires `populationCount > 0` constraint only on `HealthOutcomes` (not applicable here)
- Appends to `pollutionMetrics[bondId]`

#### `submitHealthOutcomes(bondId, life, cancer, respiratory, mental, child, population)`
- Only company
- Requires `population > 0` — prevents statistically meaningless submissions
- Appends to `healthOutcomes[bondId]`

#### `addCommunityVerification(bondId, confirmsImprovement, confirmsPhysical, residencyYears)`
- Open to anyone
- `residencyYears` adds weight to long-term residents

#### `pollutionReductionScore(bondId) → uint256`
Compares first reading vs latest reading:
```
firstAvg  = (first.air + first.water + first.food) / 3
latestAvg = (latest.air + latest.water + latest.food) / 3
improvement = int256(latestAvg) - int256(firstAvg)     // may be negative

if improvement >= 0:
    return min(10000, 5000 + improvement / 2)
else:
    return improvement > -4000 ? uint256(50 + int256(5000) + improvement / 80) : 0
```
Returns 5 000 (neutral) if fewer than 2 readings. Capped at 10 000.

#### `healthImprovementScore(bondId) → uint256`
Same pattern as `pollutionReductionScore` but averaging five health dimensions.

#### `communityVerificationMultiplier(bondId) → uint256`
```
verifiedCount = count where confirmsImprovement = true
total = all verifications
verifiedPct = verifiedCount × 100 / total

if verifiedPct >= 70: return 150
if verifiedPct >= 40: return 100
else:                 return 50 + verifiedPct
```
Returns 100 if no verifications.

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × pollution × health × community × time) / 100_000_000
```
The 100 000 000 divisor was the over-correction that caused near-zero outputs.

#### `shouldApplyPoisoningPenalty(bondId) → (bool, string)`
```
pollution < 80  → (true, "Pollution causing harm")
health < 80     → (true, "Health outcomes worsening")
community < 70  → (true, "Community not seeing improvements")
```

#### `distributeBond(bondId)`
- Requires at least one `HealthOutcomes` entry with population > 0 before distribution can proceed
- 70 % community / 30 % company on normal appreciation
- 100 % community if penalty fires
- Uses `_useYieldPool`

---

### Math Summary

| Computation | Formula |
|---|---|
| Pollution reduction score | Delta between first/latest reading, mapped to 0–10 000 |
| Health improvement score | Same pattern across five health dimensions |
| Community verification multiplier | 50–150 based on confirmation percentage |
| Time multiplier | Inherited from BaseYieldPoolBond |
| Bond value | `(stake × pollution × health × community × time) / 100_000_000` |
| Normal split | 70 / 30 community / company |
| Penalty split | 100 / 0 |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, company, stake)` | `createBond` |
| `PollutionMetricsSubmitted(bondId)` | `submitPollutionMetrics` |
| `HealthOutcomesSubmitted(bondId)` | `submitHealthOutcomes` |
| `CommunityVerificationAdded(bondId, verifier)` | `addCommunityVerification` |
| `BondDistributed(bondId, communityShare, companyShare)` | `distributeBond` |
| `PoisoningPenalty(bondId, reason)` | `distributeBond` when penalty fires |

---

### Design Intent

Hold companies financially accountable for the health consequences of their pollution. The dual data stream — pollution AND health — ensures companies cannot claim credit for population improvements unrelated to their pollution levels.

### Why It Didn't Make Production

1. **Divisor overcorrection** — 100 000 000 is too large; bond values near zero at realistic inputs.
2. **Company self-reports both data streams** — no independent oracle; a company can submit favourable metrics unilaterally.
3. **Population requirement only on health, not pollution** — asymmetric validation between the two streams.
4. **Superseded** by a version incorporating an independent health-data oracle and a recalibrated divisor.

---

---

# 12. CompetitiveIntegrityBond.sol

**Path:** `theloopbreaker-site/contracts/deprecated/CompetitiveIntegrityBond.sol`
**Lines:** ~628
**Inherits:** `ReentrancyGuard` (standalone)

## What It Was Supposed to Do

Sports team bonds that incentivise competitive integrity across a full season. A team stakes a minimum of 1 ETH. At season end, three score sources — effort metrics, anti-tanking metrics, and fan consensus — combine into an `IntegrityLevel` enum (Tanking / Questionable / Competitive / Elite). Each level determines a different appreciation percentage and distribution split between team, league, and fans.

## Why It Was Likely Deprecated

`_calculateFanConsensusScore` always returns the hardcoded value 5 000 — the fan consensus scoring layer was never implemented. The contract cannot function correctly without it.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L3   SPDX, pragma ^0.8.25, ReentrancyGuard import
```

---

### Enums

**`IntegrityLevel`**
```
Tanking      = 0
Questionable = 1
Competitive  = 2
Elite        = 3
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `MIN_STAKE` | `uint256` constant = `1 ether` | Minimum team stake. |
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `effortMetrics` | `mapping(uint256 => EffortMetrics[])` | Game-by-game effort readings. |
| `tankingMetrics` | `mapping(uint256 => TankingMetrics[])` | Anti-tanking readings. |
| `fanCompensationPool` | `mapping(uint256 => uint256)` | Held fan shares before claim. |
| `yieldPool` | `uint256` | Externally funded appreciation pool. |

---

### Structs

**`Bond`**
```
bondId          uint256
team            address
teamName        string
leagueAddress   address
stakeAmount     uint256
seasonStartDate uint256
seasonEndDate   uint256
active          bool
```

**`EffortMetrics`**
```
timestamp           uint256
hustleRating        uint256  — 0-10000
fourthQuarterEffort uint256  — effort in closing minutes
backToBackPerformance uint256 — on second game of back-to-back nights
bigGameEffort       uint256  — performance in high-stakes games
```

**`TankingMetrics`**
```
timestamp               uint256
winProbabilityDelta     int256  — positive = team improved chances
suspiciousInjuries      uint256 — count of suspicious DNPs
quitScore               uint256 — 0-10000 (0 = never quit)
performanceTrajectory   int256  — season trend direction
```

---

### Functions

#### `createBond(teamName, leagueAddress, seasonStart, seasonEnd)`
- `payable`; requires `msg.value >= MIN_STAKE (1 ETH)`
- `seasonEnd > seasonStart` required
- Emits `BondCreated`

#### `submitEffortMetrics(bondId, hustle, q4, b2b, bigGame)`
- Only `bonds[bondId].team`
- Appends `EffortMetrics`

#### `submitTankingMetrics(bondId, winProbDelta, suspiciousInjuries, quitScore, trajectory)`
- Only team
- Appends `TankingMetrics`

#### `_calculateEffortScore(bondId) → uint256`
Average of the four effort dimensions across all submitted readings:
```
for each entry:
    entryScore = (hustle + q4 + b2b + bigGame) / 4
total = sum(entryScore)
return count > 0 ? total / count : 5000
```

#### `_calculateAntiTankingScore(bondId) → uint256`
Inverts tanking signals — higher tanking indicators produce lower scores:
```
for each TankingMetrics entry:
    — winProbDelta: positive delta is good; maps −10000..+10000 → 0..10000
    — suspiciousInjuries: each injury subtracts 500, min 0
    — quitScore: inverted (10000 − quitScore)
    — trajectory: positive = good; similar mapping
    entryScore = average of four inverted metrics
return average across all entries
```

#### `_calculateFanConsensusScore(bondId) → uint256`
```
return 5000;   // STUB — always returns neutral
```
**This function is not implemented.** It was intended to aggregate fan sentiment via an external oracle or verified fan votes. The stub makes the fan consensus dimension permanently neutral, which skews `_calculateIntegrityScore` toward the midpoint regardless of actual fan perceptions.

#### `_calculateIntegrityScore(bondId) → uint256`
```
effort = _calculateEffortScore(bondId)
antiTanking = _calculateAntiTankingScore(bondId)
fanConsensus = _calculateFanConsensusScore(bondId)   // always 5000

return (effort + antiTanking + fanConsensus) / 3
```
Because `fanConsensus` is always 5 000, the effective formula is `(effort + antiTanking + 5000) / 3`, which clamps the combined score closer to neutral than the effort and anti-tanking signals alone would produce.

#### `_determineIntegrityLevel(score) → IntegrityLevel`
```
score < 3000  → Tanking
score < 5000  → Questionable
score < 7500  → Competitive
else          → Elite
```

#### `calculateBondValue(bondId) → uint256`
Uses `IntegrityLevel` to determine the appreciation percentage applied to the `yieldPool`:
```
Tanking      → 0   % appreciation
Questionable → 10  % appreciation
Competitive  → 50  % appreciation
Elite        → 100 % appreciation
```

#### `distributeBond(bondId)`
- Requires `block.timestamp >= bond.seasonEndDate`
- `nonReentrant`
- Computes integrity level and appreciation
- Distribution splits:

| Level | Team | League | Fan Pool |
|---|---|---|---|
| Tanking | 0 % | 0 % | 100 % |
| Questionable | 20 % | 10 % | 70 % |
| Competitive | 40 % | 30 % | 30 % |
| Elite | 50 % | 30 % | 20 % |

- Fan share accumulated in `fanCompensationPool[bondId]` for individual fan claims
- League and team shares transferred immediately via `.call{}` (note: this contract mixes patterns — some transfers use call, others may use transfer in helper functions)

#### `claimFanCompensation(bondId, fanAddress)`
- Allows fans to claim their share from `fanCompensationPool`
- No fan registration mechanism exists — the pool is simply divided equally among all verified fans, but there is no on-chain fan registry; the logic stubs this with a placeholder

---

### Math Summary

| Computation | Formula |
|---|---|
| Effort score | Average of (hustle + q4 + b2b + bigGame) / 4 across all readings |
| Anti-tanking score | Inverted tanking signals, averaged |
| Fan consensus score | Hardcoded 5 000 (stub) |
| Integrity score | `(effort + antiTanking + fanConsensus) / 3` |
| Bond value | `stakeAmount + yieldPool × appreciationPct / 100` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, team, stake, seasonEnd)` | `createBond` |
| `EffortSubmitted(bondId)` | `submitEffortMetrics` |
| `TankingSubmitted(bondId)` | `submitTankingMetrics` |
| `BondDistributed(bondId, level, teamShare, leagueShare, fanShare)` | `distributeBond` |

---

### Design Intent

Create financial accountability for professional sports teams to compete honestly throughout the season. The fan compensation pool acknowledges that tank-season fans who purchased tickets deserved better value for their money. The yield pool funded by the league or sponsors provides the appreciation source.

### Why It Didn't Make Production

1. **Fan consensus score is a stub** — permanently returns 5 000; the most important stakeholder perspective is absent.
2. **No fan registry** — the `claimFanCompensation` function cannot distribute to actual fans without a verified fan database.
3. **Single team self-reports effort metrics** — trivially gameable with perfect hustle scores.
4. **No external oracle** — tanking detection based on self-reported metrics is meaningless.
5. **Yield pool must be manually funded** — no automated mechanism.

---

---

# 13. EscapeVelocityBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/EscapeVelocityBonds.sol`
**Lines:** ~493
**Inherits:** `ReentrancyGuard` (standalone V1)

## What It Was Supposed to Do

A bond designed for individuals trying to escape poverty. Stake is constrained to a small range (approximately $50–$500 equivalent) so it remains accessible. The bond appreciates when the staker's income grows by 150 % or more (escape velocity) above their initial income baseline. A pay-it-forward mechanism routes 20 % of appreciation to others attempting escape.

## Why It Was Likely Deprecated

Uses deprecated `.transfer()` throughout. Superseded by `EscapeVelocityBondsV2` which upgrades to `.call{}`, adds `BaseYieldPoolBond` inheritance, and simplifies the bond value formula.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma, ReentrancyGuard import
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `MIN_STAKE` | `uint256` constant = `50000000000000` (0.00005 ETH) | ~$50 at $1 000/ETH. |
| `MAX_STAKE` | `uint256` constant = `500000000000000` (0.0005 ETH) | ~$500. |
| `ESCAPE_THRESHOLD` | `uint256` constant = `15000` | 150 % income gain. |
| `RECAPTURE_THRESHOLD` | `uint256` constant = `10000` | 100 % gain — must stay above for full payout. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `progressRecords` | `mapping(uint256 => ProgressRecord[])` | Timestamped progress entries. |
| `verifications` | `mapping(uint256 => Verification[])` | Third-party verifications. |
| `payItForwardPool` | `uint256` | Pool for funding future escape attempts. |

---

### Structs

**`Bond`**
```
bondId          uint256
escaper         address
initialIncome   uint256  — baseline income at bond creation (any unit)
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`ProgressRecord`**
```
timestamp       uint256
currentIncome   uint256
autonomyScore   uint256  — 0-10000 (control over own work/life)
stabilityScore  uint256  — 0-10000 (income predictability)
peopleHelped    uint256  — others supported during escape
notes           string
submitter       address
```

**`Verification`**
```
timestamp       uint256
verifier        address
confirmsIncome  bool
confirmsGrowth  bool
relationship    string  — "employer", "accountant", "community"
```

---

### Functions

#### `createBond(initialIncome)`
- `payable`
- Requires `msg.value >= MIN_STAKE && msg.value <= MAX_STAKE`
- `initialIncome > 0` required
- Emits `BondCreated`

#### `submitProgress(bondId, currentIncome, autonomy, stability, peopleHelped, notes)`
- Only `bonds[bondId].escaper`
- Appends `ProgressRecord`

#### `addVerification(bondId, confirmsIncome, confirmsGrowth, relationship)`
- Open to anyone (intended for trusted community members or employers)
- Appends `Verification`

#### `calculateIncomeGain(bondId) → uint256`
```
latestIncome = progressRecords[bondId][last].currentIncome
return (latestIncome - initialIncome) × 10000 / initialIncome
```
Returns 0 if no records or income decreased. Units are basis points of initial income.

#### `escapeSuccessMultiplier(bondId) → uint256`
```
gain = calculateIncomeGain(bondId)
if gain >= ESCAPE_THRESHOLD (15000):
    return 150 + min(100, (gain - 15000) / 100)   — 150 to 250
if gain >= RECAPTURE_THRESHOLD (10000):
    return 100 + (gain - 10000) / 50               — 100 to 150
if gain >= 5000:
    return 50 + gain / 100                         — 50 to 100
return 50    — still trying; base multiplier
```

#### `payItForwardMultiplier(bondId) → uint256`
```
totalPeopleHelped = sum(progressRecords[bondId][*].peopleHelped)
return 100 + min(100, totalPeopleHelped × 10)       — 100 to 200
```
Helping more people during escape increases the staker's own return.

#### `verificationMultiplier(bondId) → uint256`
```
recent = verifications within last 180 days
confirmationRate = (confirmsIncome + confirmsGrowth) / (2 × recent) × 100
≥ 80 % → 130
≥ 50 % → 100
else   → 70
```

#### `timeMultiplier(bondId) → uint256`
```
years < 1 → 100
years 1–3 → 100 + years × 50
years > 3 → 200
```

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × escapeSuccess × payItForward × verification × time) / 100_000_000
```

#### `distributeBond(bondId)`
- `nonReentrant`
- Computes appreciation; requires `appreciation != 0`
- **80 % to escaper, 20 % to payItForwardPool** (regardless of whether penalty applies)
- No penalty logic in V1 — always 80/20
- Uses deprecated `payable().transfer()`
- Emits `BondDistributed`

---

### Math Summary

| Computation | Formula |
|---|---|
| Income gain | `(current − initial) × 10000 / initial` |
| Escape success multiplier | Segmented: 50–250 based on income gain ratio |
| Pay-it-forward multiplier | `100 + min(100, peopleHelped × 10)` |
| Verification multiplier | 70–130 based on confirmation rates |
| Time multiplier | 100–200 |
| Bond value | `(stake × escape × payForward × verif × time) / 100_000_000` |
| Distribution | 80 % escaper / 20 % payItForwardPool |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, escaper, initialIncome, stake)` | `createBond` |
| `ProgressSubmitted(bondId, submitter)` | `submitProgress` |
| `VerificationAdded(bondId, verifier)` | `addVerification` |
| `BondDistributed(bondId, escaperShare, payItForwardShare)` | `distributeBond` |

---

### Design Intent

Bootstrap economic escape for low-income individuals using a self-reinforcing pool. Successful escapers fund future escapers through the pay-it-forward pool. The constrained stake range prevents wealthy participants from capturing the mechanism.

### Why It Didn't Make Production

1. **Deprecated `.transfer()` pattern** — throughout distribution.
2. **No recapture penalty in V1** — if income falls back below threshold after payout, no mechanism reclaims the appreciation.
3. **Self-reported income** — no on-chain income oracle; trivially gameable.
4. **No Sybil resistance on verifications** — any address can verify.
5. **Superseded by V2** which upgrades transfer pattern and adds `BaseYieldPoolBond`.

---

---

# 14. GhostkeyAttribution.sol

**Path:** `theloopbreaker-site/contracts/deprecated/GhostkeyAttribution.sol`
**Lines:** 35
**Inherits:** None (standalone)
**Pragma:** `^0.8.19` (older than the rest of the codebase)

## What It Was Supposed to Do

Store permanent immutable contributor metadata for the Ghostkey-316 contributor and route all ETH received (or explicitly sent via `payRoyalty()`) directly to the contributor's wallet.

## Why It Was Likely Deprecated

This is a utility/provenance contract, not a bond. It was likely superseded by `CovenantFlame.sol` which serves a similar provenance-anchor role with more sophisticated ignition tracking. The `^0.8.19` pragma predates the `^0.8.25` standard used across the rest of the codebase.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.19;
```
Older pragma. Will still compile with 0.8.25 compilers but signals this was written in an earlier development phase.

```
L9–L13 string public constants
```
```
CONTRIBUTOR = "Ghostkey-316"
ENS         = "ghostkey316.eth"
PRIMARY_WALLET = "bpow20.cb.id"
GITHUB      = "github.com/Ghostkey316"
```
Immutable string constants baked into bytecode. Future forks that include this contract preserve this attribution permanently in the deployment.

```
L15   address payable public immutable royaltyRecipient;
```
Set once at construction; cannot be changed. All ETH passing through this contract goes here.

```
L17   event RoyaltyPaid(address indexed payer, uint256 amount, string token);
```
`token` is always `"ETH"` (there is no ERC-20 path); the field is included for potential future extension.

```
L19–L21 constructor(address payable recipient)
```
```
require(recipient != address(0), "recipient zero");
royaltyRecipient = recipient;
```
Single guard. No owner stored — once deployed, attribution is immutable.

```
L23–L26 receive() external payable
```
Any ETH sent directly to the contract address is immediately forwarded to `royaltyRecipient` via `.transfer()`. Emits `RoyaltyPaid`.

```
L28–L32 function payRoyalty() external payable
```
Explicit function for callers who prefer named entry points. Requires `msg.value > 0`. Same `.transfer()` forward.

**`.transfer()` risk:** The recipient is an immutable address chosen at deploy time. If `royaltyRecipient` is a contract with a complex `receive()` function, the 2300-gas stipend from `.transfer()` may be insufficient, causing silent failure. However, because the recipient is immutable and set at deploy, this is a deployment-time risk assessment rather than a post-deployment governance issue.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `CONTRIBUTOR` | `string` constant | Human-readable contributor name. |
| `ENS` | `string` constant | ENS name for contributor. |
| `PRIMARY_WALLET` | `string` constant | Coinbase-ID wallet handle. |
| `GITHUB` | `string` constant | GitHub profile URL. |
| `royaltyRecipient` | `address payable immutable` | All ETH forwarded here. |

### Events

| Event | Trigger |
|---|---|
| `RoyaltyPaid(payer, amount, token)` | `receive()` and `payRoyalty()` |

---

### Design Intent

Create a permanent, forkable attribution record ensuring the Ghostkey-316 contributor receives recognition and royalty routing across any deployment that includes this contract.

### Why It Didn't Make Production

1. **Superseded by `CovenantFlame.sol`** which provides richer provenance anchoring.
2. **Older pragma (`^0.8.19`)** — inconsistent with codebase standard of `^0.8.25`.
3. **No owner or governance** — completely immutable; cannot correct recipient address if a key is lost.
4. **`.transfer()` pattern** — deprecated.

---

---

# 15. RewardMultiplier.sol

**Path:** `theloopbreaker-site/contracts/deprecated/RewardMultiplier.sol`
**Lines:** 209
**Inherits:** None (standalone)

## What It Was Supposed to Do

Calculate reward multipliers in basis points from three inputs — a base rate, a belief score, and a loyalty score — and push the result to a connected `RewardStream` contract. On stream failure, falls back to a configured `fallbackMultiplier`.

## Why It Was Likely Deprecated

The contract calls `rewardStream.updateMultiplier(user, computed)` via try/catch, but `RewardStream.sol` (the ETH-based version) gates `updateMultiplier` behind `onlyGovernor`. The `RewardMultiplier` contract would need to be the `governorTimelock` address to call it successfully — an architectural mismatch that was never resolved.

---

## Full Source with Line-by-Line Walkthrough

```
L8–L10 interface IRewardStream
    function updateMultiplier(address user, uint256 multiplier) external;
```
Minimal interface. Any contract with this function can be plugged in.

```
L20   address public owner;
L21   IRewardStream public rewardStream;
L22   uint256 public fallbackMultiplier;    // bps, default 10 000 = 1.0×
L23   uint256 public bonusCapBps;           // default 5 000 = +0.5× max bonus
```

```
L52–L56 constructor(address stream, uint256 initialFallbackBps)
```
Sets `owner = msg.sender`, `rewardStream`, and `fallbackMultiplier` (defaults to 10 000 if 0 passed). Sets `bonusCapBps = 5 000`.

---

### `calculateMultiplier(baseRateBps, beliefScoreBps, loyaltyScoreBps) → uint256`

```
L155  base = max(baseRateBps, 10_000)                           — floor at 1.0×
L156  beliefBonus = (beliefScoreBps × bonusCapBps) / 100_000   — belief contributes up to bonusCap
L157  loyaltyBonus = loyaltyScoreBps × 5                       — each loyalty point = 5 bps
L158  computed = base + beliefBonus + loyaltyBonus
L159  maxAllowed = base + bonusCapBps
L160  return min(computed, maxAllowed)
```

**Example at default settings:**
- base = 10 000 (1.0×)
- belief = 8 000 / 100 000 × 5 000 = 400 bps (+0.04×)
- loyalty = 6 000 × 5 = 30 000 bps — this is the overflow problem: loyalty directly multiplies without a cap, so a loyalty score of 2 000 (max is 10 000) gives 10 000 bps, which is the full bonus cap by itself. The `min(computed, maxAllowed)` saves this from overflowing, but the loyalty weighting is disproportionate.

---

### `streamMultiplier(user, baseRateBps, beliefScoreBps, loyaltyScoreBps) → uint256`

```
L194  computed = calculateMultiplier(...)
L196  if rewardStream != address(0):
L197      try rewardStream.updateMultiplier(user, computed):
L198          streamed = true
L199      catch:
L200          computed = fallbackMultiplier   — revert to fallback on any failure
L202  else:
L203      computed = fallbackMultiplier
L205  emit MultiplierStreamed(user, computed, streamed)
```
The try/catch fallback means a failed stream silently returns `fallbackMultiplier` without alerting operators. An event is emitted showing `streamedOnChain = false` but there is no separate error event.

---

### Math Summary

| Computation | Formula |
|---|---|
| Base rate | `max(baseRateBps, 10_000)` |
| Belief bonus | `(beliefScore × bonusCap) / 100_000` |
| Loyalty bonus | `loyaltyScore × 5` (uncapped before final cap) |
| Computed | `base + beliefBonus + loyaltyBonus` |
| Final | `min(computed, base + bonusCap)` |

---

### Events

| Event | Trigger |
|---|---|
| `MultiplierStreamed(user, multiplierBps, streamedOnChain)` | `streamMultiplier` |
| `RewardStreamUpdated(streamAddress)` | `setRewardStream` |
| `FallbackMultiplierUpdated(multiplierBps)` | `setFallbackMultiplier` |
| `OwnershipTransferred(previous, new)` | `transferOwnership` |
| `BonusCapUpdated(capBps)` | `setBonusCap` |

---

### Design Intent

Provide a configurable multiplier calculation layer that translates abstract belief and loyalty scores into concrete reward scaling factors, and push those factors to the stream contract without requiring callers to understand the internal math.

### Why It Didn't Make Production

1. **Access control mismatch** — `RewardStream.updateMultiplier` is gated to `onlyGovernor`; `RewardMultiplier` is not a governor, so the try/catch always catches and falls back to `fallbackMultiplier`.
2. **Silent fallback** — operators cannot distinguish a real multiplier stream from a fallback-every-time scenario without watching the `streamedOnChain` field in events.
3. **Loyalty bonus disproportionate** — at `loyaltyScore = 10 000`, loyalty bonus alone is 50 000 bps (5×), which immediately saturates the cap before belief contributes meaningfully.
4. **Ownership not two-step** — `transferOwnership` is an instant single-step transfer; a mistaken address cannot be recovered.

---

---

# 16. TeamworkIntegrityBond.sol

**Path:** `theloopbreaker-site/contracts/deprecated/TeamworkIntegrityBond.sol`
**Lines:** ~613
**Inherits:** `ReentrancyGuard` (standalone)

## What It Was Supposed to Do

Player-level bond (minimum 0.1 ETH) assessing whether a player is a genuine teammate or a stat-chaser. Chemistry metrics, winning-vs-stats performance data, and teammate verifications combine into a `PlayerRole` enum (StatChaser / Neutral / TeamPlayer / Champion). Each role determines an appreciation percentage and distribution split including a teammate compensation pool.

## Why It Was Likely Deprecated

Requires a minimum of 5 teammate verifications before distribution is allowed — there is no mechanism to source those verifications from actual teammates, making the contract practically unusable without an off-chain coordination layer. Also uses `.transfer()` throughout.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L3   SPDX, pragma, ReentrancyGuard
```

---

### Enums

**`PlayerRole`**
```
StatChaser  = 0  — prioritises personal stats over team success
Neutral     = 1
TeamPlayer  = 2  — consistent teammate contributions
Champion    = 3  — elite team-first behaviour
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `MIN_STAKE` | `uint256` constant = `0.1 ether` | Minimum team stake. |
| `MIN_VERIFICATIONS` | `uint256` constant = `5` | Required teammate verifications before distribution. |
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 => Bond)` | Bond storage. |
| `chemistryMetrics` | `mapping(uint256 => ChemistryMetrics[])` | Per-game team chemistry readings. |
| `winningVsStats` | `mapping(uint256 => WinningVsStats[])` | Winning-vs-statpadding readings. |
| `teammateVerifications` | `mapping(uint256 => TeammateVerification[])` | Verified teammate opinions. |
| `teammateCompensationPool` | `mapping(uint256 => uint256)` | Teammate shares held for claim. |

---

### Structs

**`Bond`**
```
bondId          uint256
player          address
playerName      string
teamAddress     address
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`ChemistryMetrics`**
```
timestamp               uint256
assistRatio             uint256  — 0-10000 (assists vs shot attempts)
defensiveEffort         uint256  — 0-10000
benchSupport            uint256  — 0-10000 (support of bench/younger players)
plusMinusDifferential   int256   — team +/- when player is on court
```

**`WinningVsStats`**
```
timestamp                   uint256
performanceInWins           uint256  — 0-10000
performanceInLosses         uint256  — 0-10000 (high score in losses = bad sign)
clutchPerformance           uint256  — 0-10000
sacrificeScore              uint256  — 0-10000 (willing to sacrifice stats for team?)
statPaddingDetected         bool     — flag set by team/coach
```

**`TeammateVerification`**
```
timestamp           uint256
teammate            address
makesUsBetter       uint256  — 0-10 rating
prioritisesWinning  uint256  — 0-10 rating
wouldWantInPlayoffs bool
notes               string
```

---

### Functions

#### `createBond(playerName, teamAddress)`
- `payable`; requires `msg.value >= MIN_STAKE (0.1 ETH)`
- Emits `BondCreated`

#### `submitChemistryMetrics(bondId, assistRatio, defensive, bench, plusMinus)`
- Only player
- `plusMinusDifferential` is a signed int — can be negative

#### `submitWinningVsStats(bondId, inWins, inLosses, clutch, sacrifice, statPaddingDetected)`
- Only player (player self-reports; obvious conflict of interest)

#### `addTeammateVerification(bondId, makesUsBetter, prioritisesWinning, wouldWantInPlayoffs, notes)`
- Open to any address (intended for teammates)
- No verification that the caller is actually on the team

#### `_calculateChemistryScore(bondId) → uint256`
```
for each ChemistryMetrics entry:
    entryScore = (assistRatio + defensive + bench) / 3   — plusMinus handled separately
average across all entries
```
Note: `plusMinusDifferential` (int256) is used separately in a weighting context but the base chemistry score ignores it, which loses an important signal.

#### `_calculateWinningScore(bondId) → uint256`
```
for each WinningVsStats entry:
    winVsLossDiff = performanceInWins > performanceInLosses
                    ? (performanceInWins - performanceInLosses) / 2
                    : 0
    entryScore = (winVsLossDiff + clutch + sacrifice) / 3
average across all entries
```

#### `_detectStatPadding(bondId) → bool`
```
statPaddedGames = count where statPaddingDetected = true
                  AND (performanceInLosses − performanceInWins > 3000)

return statPaddedGames × 100 / total > 25    — >25 % of games show padding
```
If more than 25 % of games have both the `statPaddingDetected` flag and a performance-in-losses exceeding performance-in-wins by 3 000 points, a 50 % penalty applies to the distribution.

#### `_calculateTeammateConsensusScore(bondId) → uint256`
```
require(verificationsLength >= MIN_VERIFICATIONS, "Insufficient verifications")
averageMakesUsBetter    = avg(makesUsBetter × 1000)   — scaled to 0-10000
averagePrioritisesWin   = avg(prioritisesWinning × 1000)
playoffWant             = count(wouldWantInPlayoffs) × 10000 / total
return (makesUsBetter + prioritisesWin + playoffWant) / 3
```
The `require` hard-blocks distribution if fewer than 5 verifications exist.

#### `_determinePlayerRole(chemistry, winning, consensus) → PlayerRole`
```
avgScore = (chemistry + winning + consensus) / 3
avgScore < 3000  → StatChaser
avgScore < 5000  → Neutral
avgScore < 7500  → TeamPlayer
else             → Champion
```

#### `distributeBond(bondId)`
- `nonReentrant`
- Calls `_calculateTeammateConsensusScore` (reverts if < 5 verifications)
- Detects stat padding
- Determines role
- Distribution splits:

| Role | Player | Team/Fund | Teammate Pool |
|---|---|---|---|
| StatChaser | 0 % | 100 % | 0 % |
| Neutral | 30 % | 50 % | 20 % (+10 % appreciation) |
| TeamPlayer | 60 % | 30 % | 10 % (+60 % appreciation) |
| Champion | 60 % | 30 % | 10 % (+120 % appreciation) |

- Stat padding detected → 50 % penalty to all shares
- Uses `payable().transfer()` throughout

---

### Math Summary

| Computation | Formula |
|---|---|
| Chemistry score | Average of (assist + defensive + bench) / 3 across readings |
| Winning score | `(winVsLossDiff + clutch + sacrifice) / 3` |
| Stat padding detection | `statPaddedGames% > 25 AND lossPerf − winPerf > 3000` |
| Teammate consensus | Average of scaled teammate ratings |
| Player role | Average of three scores mapped to enum |
| Teammate compensation | Role-based % held in pool |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, player, stake)` | `createBond` |
| `ChemistrySubmitted(bondId)` | `submitChemistryMetrics` |
| `WinningStatsSubmitted(bondId)` | `submitWinningVsStats` |
| `TeammateVerificationAdded(bondId, teammate)` | `addTeammateVerification` |
| `BondDistributed(bondId, role, playerShare, teammateShare)` | `distributeBond` |

---

### Design Intent

Reward players who make their teams better, not just their own statistics. The teammate compensation pool creates a direct financial benefit for teammates of genuinely team-first players.

### Why It Didn't Make Production

1. **`MIN_VERIFICATIONS = 5` without an enforcement mechanism** — no way to source verified teammate verifications on-chain.
2. **Player self-reports winning stats** — `statPaddingDetected` is a flag the player can choose not to set.
3. **`payable().transfer()` deprecated**.
4. **`plusMinusDifferential` collected but not used** in the primary chemistry score calculation.
5. **Teammate compensation pool has no claim function** in the source — teammates have no way to withdraw their shares.

---

---

# 17. RewardStream.sol

**Path:** `theloopbreaker-site/contracts/deprecated/RewardStream.sol`
**Lines:** 207
**Inherits:** `ReentrancyGuard`

## What It Was Supposed to Do

An ETH-based reward queuing and distribution contract with separate admin and governor roles. Admin queues and distributes rewards; governor updates per-user multipliers. Both roles have 2-day timelocked transfers. An `ethicsPause` mechanism can halt distributions.

## Why It Was Likely Deprecated

This is one of the most complete contracts in the archive — it has proper CEI patterns, timelocked role transfers, and `nonReentrant`. It is deprecated not due to bugs but because it was superseded by a version that integrates directly with the Vaultfire bond settlement system, removing the need for a separate reward queuing layer.

---

## Full Source with Line-by-Line Walkthrough

```
L6    contract RewardStream is ReentrancyGuard {
L7        address public admin;
L8        address public governorTimelock;
L9        mapping(address => uint256) private multipliers;
L10       mapping(address => uint256) private _pendingRewards;
L11       uint256 public ethicsPauseUntil;
```
`multipliers` stores per-user reward multipliers (set by governor). `_pendingRewards` holds ETH accrued to each address. `ethicsPauseUntil` is a timestamp; if `block.timestamp < ethicsPauseUntil`, distributions are blocked.

```
L13–L21 Timelock state variables
```
```
pendingAdmin          address  — staged new admin
adminTransferTimestamp uint256 — effective time for admin transfer
ADMIN_TRANSFER_DELAY  2 days   — constant
pendingGovernor       address  — staged new governor
governorTransferTimestamp uint256
GOVERNOR_TRANSFER_DELAY   2 days
```
Both role transfers use the same two-step pattern: initiate → wait 2 days → accept. Either transfer can be cancelled by the current admin before acceptance.

```
L49–L54 constructor(adminAddress, governorAddress)
```
Sets both roles; validates non-zero addresses. No timelock on initial deployment.

```
L56    receive() external payable {}
```
Allows the contract to receive ETH for the reward pool.

---

### `updateMultiplier(user, multiplier)` — `onlyGovernor`
Sets a per-user multiplier in the `multipliers` mapping. Used by `RewardMultiplier.sol` (when it has governor access). No range check on the multiplier value.

### `queueRewards(recipient, amount)` — `onlyAdmin`, `notPaused`
```
_pendingRewards[recipient] += amount
emit RewardsQueued(recipient, amount)
```
Does not transfer ETH; purely accounting. The actual ETH must already be in the contract (sent via `receive()` or `distributeRewards`).

### `distributeRewards(recipient, amount)` — `onlyAdmin`, `notPaused`, `nonReentrant`
```
pending = _pendingRewards[recipient]
require(pending >= amount)
_pendingRewards[recipient] = pending - amount    — effects first
(bool success,) = payable(recipient).call{value: amount}("")   — interaction last
require(success)
```
Correct CEI pattern. Admin pushes ETH to recipient. The comment `✅ EFFECTS before INTERACTIONS` is explicit in the source.

### `claimRewards(address payable recipient)` — `nonReentrant`, `notPaused`
```
claimer = msg.sender
amount = _pendingRewards[claimer]
require(amount > 0)
if recipient == address(0): recipient = payable(claimer)
_pendingRewards[claimer] = 0         — effects first
(bool,) = recipient.call{value: amount}("")   — interaction last
```
Pull-pattern claim. The claimer can nominate a different recipient (useful for directing rewards to a hardware wallet from a hot wallet caller).

### `setEthicsPause(untilTimestamp)` — `onlyAdmin`
```
require(untilTimestamp >= block.timestamp)
ethicsPauseUntil = untilTimestamp
```
Cannot set a pause in the past. No maximum duration cap — admin could theoretically pause indefinitely.

---

### Two-Step Admin Transfer

```
transferAdmin(newAdmin)     — onlyAdmin; sets pendingAdmin + timestamp
acceptAdmin()               — pendingAdmin only, after 2-day delay
cancelAdminTransfer()       — onlyAdmin; clears pending
```

### Two-Step Governor Transfer

```
transferGovernor(newGovernor) — onlyAdmin
acceptGovernor()              — pendingGovernor only, after 2-day delay
cancelGovernorTransfer()      — onlyAdmin
```
Note: Governor transfer is initiated by admin, not by current governor. This means if admin is compromised, both admin and governor can be redirected.

---

### Math Summary

No arithmetic beyond `pending -= amount` and `pending += amount`. All ETH accounting uses direct wei balances.

---

### Events

| Event | Trigger |
|---|---|
| `MultiplierUpdated(user, multiplier)` | `updateMultiplier` |
| `AdminTransferred(previous, new)` | `acceptAdmin` |
| `AdminTransferInitiated(current, pending, effectiveTime)` | `transferAdmin` |
| `AdminTransferCancelled(cancelled)` | `cancelAdminTransfer` |
| `GovernorTimelockUpdated(previous, new)` | `acceptGovernor` |
| `GovernorTransferInitiated(...)` | `transferGovernor` |
| `GovernorTransferCancelled(cancelled)` | `cancelGovernorTransfer` |
| `RewardsQueued(recipient, amount)` | `queueRewards` |
| `RewardsClaimed(claimer, recipient, amount)` | `distributeRewards`, `claimRewards` |
| `EthicsPauseApplied(untilTimestamp)` | `setEthicsPause` |

---

### Design Intent

A secure ETH reward pipeline separating concerns between an admin (operational) and a governor (policy). The ethics pause provides a governance lever to halt distributions during controversies or exploits while a remediation is prepared.

### Why It Didn't Make Production (as standalone)

1. **Superseded by tighter integration** — production reward flow was embedded directly into bond settlement contracts to reduce the attack surface of a separate relay contract.
2. **Indefinite pause** — admin can pause forever; production version required a maximum pause duration.
3. **Governor transfer initiated by admin** — creates a single point of failure for both critical roles.
4. **`updateMultiplier` has no range check** — a governor could set a multiplier to 0 or an astronomically high value.

---

---

# 18. ContributorUnlockKey.sol

**Path:** `theloopbreaker-site/contracts/deprecated/ContributorUnlockKey.sol`
**Lines:** 38
**Inherits:** `ERC721`, `Ownable`

## What It Was Supposed to Do

An ERC-721 NFT access token. When minted (by owner only), it optionally calls a configurable `unlockHook` contract's `onMint(to, tokenId)` function, triggering elevated feature access in downstream systems. Token name: "Contributor Unlock Key" (CUK).

## Why It Was Likely Deprecated

The contract is functional but was superseded when the access control model moved away from NFT-gated access toward the guardian token (VFG) voting-weight model. ERC-721 per-user keys also do not compose well with the multi-bond architecture.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
L4    import "@openzeppelin/contracts/access/Ownable.sol";
```

```
L11–L13 interface IUnlockHook
    function onMint(address to, uint256 tokenId) external;
```
A minimal callback interface. Any contract implementing `onMint` can be plugged in as the hook.

```
L15   contract ContributorUnlockKey is ERC721, Ownable {
L16       uint256 private _tokenId;
L17       address public unlockHook;
```
`_tokenId` is a simple counter starting at 0. Incrementing before minting (L29: `_tokenId += 1`) ensures token IDs start at 1.

```
L19   event UnlockHookSet(address indexed hook);
```
Logged when hook is updated. Allows off-chain indexers to track which contract is receiving mint callbacks.

```
L21   constructor()
    ERC721("Contributor Unlock Key", "CUK") Ownable(msg.sender) {}
```
No arguments; deployer is owner.

```
L23–L26 function setUnlockHook(address hook) external onlyOwner
```
Owner can change the hook at any time. No validation that `hook` is non-zero — `hook == address(0)` is a valid no-op setting (handled by the `if` in `mint`).

```
L28–L36 function mint(address to) external onlyOwner returns (uint256)
```
```
L29   _tokenId += 1;
L30   uint256 newId = _tokenId;
L31   _mint(to, newId);                            — ERC721 standard mint
L32   if (unlockHook != address(0)) {
L33       IUnlockHook(unlockHook).onMint(to, newId);   — external callback
L34   }
L35   return newId;
```
The hook call is **after** `_mint`, so the token is already owned by `to` when the hook fires. The hook could theoretically call back into this contract — but since no state-modifying function is unguarded, the reentrancy risk is minimal. The `onMint` callback is not wrapped in a try/catch, so a reverting hook would cause the entire `mint` to revert.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `_tokenId` | `uint256` private | Sequential token ID counter. |
| `unlockHook` | `address` public | Optional callback contract. |

### Events

| Event | Trigger |
|---|---|
| `UnlockHookSet(hook)` | `setUnlockHook` |
| Standard ERC-721 `Transfer(from, to, tokenId)` | `mint` (via `_mint`) |

---

### Design Intent

Gate elevated Vaultfire features behind an NFT that can only be minted by the contract owner. The hook enables any feature system to respond to new contributors without modifying this contract.

### Why It Didn't Make Production

1. **Hook not wrapped in try/catch** — a buggy or intentionally reverting hook breaks all minting.
2. **No burn mechanism** — once minted, access cannot be revoked; the NFT can be transferred to any wallet, losing the contributor-specific binding.
3. **Owner-only minting** — does not scale; requires manual intervention per contributor.
4. **Access model superseded** — the guardian token (ERC-20 with voting weight) was preferred over ERC-721 individual keys.

---

---

# 19. GhostkeyLoyaltyLock.sol

**Path:** `theloopbreaker-site/contracts/deprecated/GhostkeyLoyaltyLock.sol`
**Lines:** 69
**Inherits:** None (standalone)

## What It Was Supposed to Do

A simple ETH time-lock with a linear loyalty multiplier. Users stake ETH for a fixed number of weeks. After the lock period ends they can withdraw principal. The contract exposes `getMultiplier(user)` as a read-only signal for backend systems — it does not enforce or apply the multiplier on-chain.

## Why It Was Likely Deprecated

The multiplier is advisory only — there is no on-chain mechanism enforcing it against rewards. The contract is also entirely standalone with no integration into the `RewardStream` or `RewardMultiplier` systems. Uses deprecated `.transfer()`.

---

## Full Source with Line-by-Line Walkthrough

```
L9    contract GhostkeyLoyaltyLock {
L10–L14 struct LockInfo { start, duration, amount }
L16   mapping(address => LockInfo) public locks;
```
One lock per address. Attempting to stake again while a lock is active reverts with `"already staked"`.

---

### `stake(ensHolder, lockWeeks)` — `payable`

```
L27   require(lockWeeks > 0, "duration 0");
L28   require(msg.value > 0, "no value");
L30   LockInfo storage info = locks[ensHolder];
L31   require(info.amount == 0, "already staked");
L33   info.start    = block.timestamp;
L34   info.duration = lockWeeks * 1 weeks;
L35   info.amount   = msg.value;
L37   emit Staked(ensHolder, msg.value, lockWeeks);
```
Note: The lock is recorded against `ensHolder`, not `msg.sender`. The caller can lock ETH on behalf of any address. This is unusual — it means anyone can lock ETH to an address they do not control, effectively preventing that address from re-staking until the period expires.

---

### `getMultiplier(user) → multiplier`

```
L45   if info.amount == 0: return 1
L50   weeksLocked = info.duration / 1 weeks
L52   multiplier = 1 + weeksLocked / 10
```
Linear scale. A 10-week lock gives `1 + 1 = 2`. A 100-week lock gives `1 + 10 = 11`. No cap. The return type is `uint256` and units are arbitrary (the comment says "1× base plus 0.1× per week" but the implementation yields integers, not decimals — there is no fractional scaling).

---

### `withdraw()`

```
L58   require(info.amount > 0, "nothing staked")
L59   require(block.timestamp >= info.start + info.duration, "still locked")
L61   amount = info.amount
L62   delete locks[msg.sender]            — delete before transfer (CEI-correct)
L63   emit Withdrawn(msg.sender, amount)
L64   payable(msg.sender).transfer(amount)   — deprecated
```
`msg.sender` must have been the original `ensHolder` to withdraw, because the lock is indexed by address and `delete` uses `msg.sender`. If someone staked on behalf of a different `ensHolder`, only that `ensHolder` can withdraw. **This creates a potential griefing vector:** a malicious actor can lock ETH to any address they choose, temporarily blocking that address from re-staking.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `locks` | `mapping(address → LockInfo)` | One lock per address. |

### Events

| Event | Trigger |
|---|---|
| `Staked(user, amount, weeksLocked)` | `stake` |
| `Withdrawn(user, amount)` | `withdraw` |

---

### Design Intent

Provide a loyalty depth signal for backend reward systems — users who lock ETH for longer periods earn higher multipliers in off-chain reward calculations.

### Why It Didn't Make Production

1. **Multiplier is advisory only** — never used on-chain by any reward distribution contract.
2. **Third-party locking griefing vector** — caller can lock ETH to any address.
3. **No fractional multiplier** — integer division truncates; all 1–9 week locks return multiplier `1`, same as no lock.
4. **`.transfer()` deprecated**.
5. **No integration with `RewardMultiplier` or `RewardStream`**.

---

---

# 20. LaborDignityBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/LaborDignityBonds.sol`
**Lines:** ~470
**Inherits:** `ReentrancyGuard` (standalone V1)

## What It Was Supposed to Do

A company stakes ETH on six dimensions of worker flourishing: income, autonomy, dignity, work-life balance, security, and voice. Workers independently attest metrics to verify or challenge company reports. The bond appreciates when flourishing is high and workers confirm the numbers. An exploitation penalty fires if conditions fall below thresholds or workers report low scores.

## Why It Was Likely Deprecated

Uses deprecated `.transfer()`. Superseded by `LaborDignityBondsV2` which adds `BaseYieldPoolBond`, a dignity floor (minimum payout), and `.call{}` — but V2 introduced a new off-by-one bug in the worker verification loop (see contract 23).

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma ^0.8.25, ReentrancyGuard + MissionEnforcement
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `EXPLOITATION_FLOURISHING_THRESHOLD` | `uint256` = `4000` | Flourishing below this = penalty. |
| `EXPLOITATION_VERIFICATION_THRESHOLD` | `uint256` = `50` | Verification multiplier ≤ 50 = penalty. |
| `EXPLOITATION_WORKER_SCORE_THRESHOLD` | `uint256` = `4000` | Worker-reported score below this = penalty. |
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 → Bond)` | Bond storage. |
| `flourishingMetrics` | `mapping(uint256 → FlourishingMetrics[])` | Company-submitted readings. |
| `workerAttestations` | `mapping(uint256 → WorkerAttestation[])` | Worker-submitted attestations. |

---

### Structs

**`Bond`**
```
bondId          uint256
company         address
companyName     string
workerCount     uint256
stakeAmount     uint256
createdAt       uint256
active          bool
```

**`FlourishingMetrics`**
```
timestamp           uint256
income              uint256  — 0-10000
autonomy            uint256  — 0-10000
dignity             uint256  — 0-10000
workLifeBalance     uint256  — 0-10000
security            uint256  — 0-10000
voice               uint256  — 0-10000
submitter           address
workerCount         uint256  — headcount at time of submission
```

**`WorkerAttestation`**
```
timestamp           uint256
worker              address
isCurrentWorker     bool
overallScore        uint256  — worker's own assessment (0-10000)
confirmsCompany     bool     — does worker confirm company metrics?
specificConcerns    string
```

---

### Functions

#### `flourishingScore(bondId) → uint256`
Average of six dimensions from the latest `FlourishingMetrics` entry.

#### `workerVerifiedScore(bondId) → uint256`
Iterates all attestations from current workers (where `isCurrentWorker = true`) within the last 90 days:
```
sum = sum(attestation.overallScore) for qualifying attestations
return count > 0 ? sum / count : 5000
```

#### `workerVerificationMultiplier(bondId) → uint256`
```
verifiedCount = qualifying attestations
totalExpected = bond.workerCount
verificationRate = verifiedCount × 100 / totalExpected

if rate >= 50: return 150
if rate >= 25: return 100
else:          return 50
```
Returns 100 if `workerCount = 0`.

#### `timeMultiplier(bondId) → uint256`
Standard segmented formula: 100 at year 0, increasing over years.

#### `calculateBondValue(bondId) → uint256`
```
bondValue = (stake × flourishing × verification × time) / 1_000_000
```

#### `shouldApplyExploitationPenalty(bondId) → (bool, string)`
```
flourishing < 4000            → (true, "Workers not flourishing")
verificationMultiplier <= 50  → (true, "Workers not verifying")
workerVerifiedScore < 4000    → (true, "Workers reporting poor conditions")
```
Any single condition triggers the penalty.

#### `distributeBond(bondId)`
- `nonReentrant`
- Calls `_requireMissionCompliance()`
- 70 % workers / 30 % company on normal appreciation
- 100 % workers on exploitation penalty
- Uses deprecated `payable().transfer()`
- **Worker share is sent to `_useYieldPool` equivalent in V1** — which is just `payable(someAddress).transfer()` since there is no base contract; the recipient is the owner, not individual workers

---

### Math Summary

| Computation | Formula |
|---|---|
| Flourishing score | Average of 6 dimensions from latest metrics |
| Worker verified score | Average of current-worker attestation scores (90-day window) |
| Worker verification multiplier | 50/100/150 based on what % of workers attested |
| Bond value | `(stake × flourishing × verification × time) / 1_000_000` |
| Normal split | 70 / 30 workers / company |
| Exploitation split | 100 / 0 |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, company, stake)` | `createBond` |
| `MetricsSubmitted(bondId)` | `submitFlourishingMetrics` |
| `WorkerAttested(bondId, worker)` | `addWorkerAttestation` |
| `BondDistributed(bondId, workerShare, companyShare)` | `distributeBond` |
| `ExploitationPenalty(bondId, reason)` | `distributeBond` when penalty fires |

---

### Design Intent

Create corporate accountability for worker conditions by tying employer capital directly to measurable worker flourishing. The dual-report model (company submits, workers attest) creates a checks-and-balances structure where exploitation is financially costly.

### Why It Didn't Make Production

1. **`.transfer()` deprecated** throughout.
2. **Worker share goes to owner in V1** — actual individual worker distribution relies on an off-chain registry that was never built.
3. **No Sybil resistance on attestations** — any address claiming `isCurrentWorker = true` can attest; there is no employment verification.
4. **Superseded by V2** which added dignity floor and `.call{}` — but V2 introduced its own off-by-one bug.

---

---

# 21. EscapeVelocityBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/EscapeVelocityBondsV2.sol`
**Lines:** ~312
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

V2 of the escape velocity bond. Same constrained stake range and income-escape mechanics as V1. Key upgrades: inherits `BaseYieldPoolBond` (timelock, `whenNotPaused`, `.call{}` via `_useYieldPool`); simplified `calculateBondValue` formula; explicit timelock before distribution.

## Why It Was Likely Deprecated

The simplified bond value formula — `stake + stake × incomeGain / 10000` — is purely linear and does not incorporate autonomy, stability, people helped, verification, or time. All the nuance of V1's multiplier stack was dropped without designing a replacement calibrated to the new formula. This made V2 economically weaker than V1 despite being technically cleaner.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L3   SPDX, pragma, BaseYieldPoolBond import
```

---

### Key Differences From V1

| Feature | V1 | V2 |
|---|---|---|
| Inheritance | Standalone | BaseYieldPoolBond |
| Transfer pattern | `.transfer()` | `_useYieldPool()` / `.call{}` |
| Bond value formula | `stake × escape × payForward × verif × time / 100_000_000` | `stake + stake × incomeGain / 10000` |
| Timelock | No | Yes |
| `whenNotPaused` | No | Yes |
| Multiplier dimensions | 4 (escape, payForward, verification, time) | 1 (incomeGain only) |

---

### `calculateIncomeGain(bondId) → uint256`
Identical to V1:
```
gain = (latestIncome - initialIncome) × 10000 / initialIncome
```
Returns 0 if income decreased.

### `calculateBondValue(bondId) → uint256`
```
gain = calculateIncomeGain(bondId)
if gain >= ESCAPE_THRESHOLD (15000):
    return stake + stake × gain / 10000    — linear appreciation
else:
    return stake                           — no appreciation if below threshold
```
This is dramatically simpler than V1 but eliminates all pay-it-forward, community verification, and time incentives.

### `distributeBond(bondId)`
- Checks `DISTRIBUTION_TIMELOCK`
- 80 % escaper, 20 % `payItForwardPool`
- Uses `_useYieldPool(escaperShare)` for ETH routing
- Emits `BondDistributed`

The pay-it-forward pool exists as a balance but has no integrated claim mechanism within V2 — funds accumulate but distribution to new escapers must be handled externally.

---

### Math Summary

| Computation | Formula |
|---|---|
| Income gain | `(current − initial) × 10000 / initial` |
| Bond value | `stake + stake × incomeGain / 10000` (if gain ≥ escape threshold) |
| Escape threshold | 15 000 (150 % income gain) |
| Distribution | 80 % escaper / 20 % payItForwardPool |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, escaper, initialIncome, stake)` | `createBond` |
| `ProgressSubmitted(bondId)` | `submitProgress` |
| `VerificationAdded(bondId)` | `addVerification` |
| `BondDistributed(bondId, escaperShare, payForwardShare)` | `distributeBond` |

---

### Design Intent

Preserve V1's poverty-escape mission with a technically cleaner implementation that removes the deprecated transfer pattern and adds proper security controls.

### Why It Didn't Make Production

1. **Formula regression** — dropping the multiplier stack removed all incentive to help others, build over time, or maintain community verification.
2. **Pay-it-forward pool not self-distributing** — no mechanism to route pool funds to new escapers.
3. **V3 needed** — neither V1 nor V2 adequately solved the problem; a combined approach was planned but not completed before the archive.

---

---

# 22. YieldPoolHealthMonitor.sol

**Path:** `theloopbreaker-site/contracts/deprecated/YieldPoolHealthMonitor.sol`
**Lines:** 389
**Inherits:** None (standalone)

## What It Was Supposed to Do

An off-chain monitoring companion providing on-chain snapshots of yield pool health. The owner or any external caller can record health snapshots. The contract tracks reserve ratios, risk levels, and triggers rebalance events when reserves fall below threshold. Historical snapshots are stored with automatic pruning when `MAX_HISTORY = 100` is exceeded.

## Why It Was Likely Deprecated

A pure monitoring contract with no enforcement capability — it emits events and stores snapshots, but cannot pause or modify the yield pool it monitors. The production system moved health monitoring into the yield pool contract itself, eliminating the need for a separate monitor.

---

## Full Source with Line-by-Line Walkthrough

```
L12   contract YieldPoolHealthMonitor {
```
No inheritance. Minimal footprint — just owner, config, and history storage.

---

### Structs

**`YieldPoolHealth`**
```
totalReserves       uint256  — yield pool ETH balance (input)
totalActiveBonds    uint256  — total value of active bonds (input)
reserveRatio        uint256  — bps: reserves / bonds × 10000
utilizationRate     uint256  — bps: bonds / reserves × 10000
minimumRequired     uint256  — output of calculateMinimumReserve
isHealthy           bool     — pool >= minimumRequired
riskLevel           uint256  — 0=Safe, 1=Warning, 2=Critical
timestamp           uint256
```

**`ReserveRequirements`**
```
baseReserveRatio    uint256 = 5000   — 50 % of active bonds
volatilityBuffer    uint256 = 2000   — +20 % extra
emergencyReserve    uint256 = 10 ETH — absolute floor
rebalanceThreshold  uint256 = 4000   — alert trigger at <40 %
```

---

### `assessHealth(yieldPool, totalActiveBonds) → YieldPoolHealth`

```
L139  minRequired = calculateMinimumReserve(totalActiveBonds)
L141  reserveRatio = totalActiveBonds > 0
                     ? (yieldPool × 10000) / totalActiveBonds
                     : 10000
L145  utilizationRate = yieldPool > 0
                        ? (totalActiveBonds × 10000) / yieldPool
                        : 0
L150  riskLevel:
          reserveRatio < 4000 → 2 (Critical)
          reserveRatio < 6000 → 1 (Warning)
          else               → 0 (Safe)
```
A `pure`-style view (only reads inputs, not state). Can be called any time without storing a snapshot.

---

### `calculateMinimumReserve(totalActiveBonds) → uint256`

```
baseReq     = totalActiveBonds × 5000 / 10000    = 50 %
volBuffer   = totalActiveBonds × 2000 / 10000    = 20 %
totalReq    = baseReq + volBuffer                 = 70 % of bonds
return max(totalReq, 10 ether)
```
The reserve target is 70 % of total active bond value, with a hard floor of 10 ETH. This is conservative — a yield pool holding 70 % of outstanding bond value as reserves would be unusual in DeFi.

---

### `recordHealthSnapshot(yieldPool, totalActiveBonds)`

```
health = assessHealth(...)
if previous snapshot exists and riskLevel changed:
    emit RiskLevelChanged(...)
healthHistory.push(health)
if healthHistory.length > MAX_HISTORY:
    _pruneHistory()
emit HealthSnapshotRecorded(...)
if reserveRatio < rebalanceThreshold:
    emit RebalanceNeeded(...)
```
Open to any caller — no access control on snapshot recording. This is intentional: any monitoring bot or user can push a snapshot.

---

### `_pruneHistory()` — internal

```
removeCount = healthHistory.length / 2   — prune oldest 50 %
for i in 0..(length - removeCount):
    healthHistory[i] = healthHistory[i + removeCount]   — shift down
for i in 0..removeCount:
    healthHistory.pop()                                  — trim tail
```
O(n) shift algorithm — gas cost grows linearly with history size. At `MAX_HISTORY = 100` and pruning 50 at a time, maximum gas per prune is bounded. The two-loop approach avoids modifying the array during iteration.

---

### `canSafelyCoverAppreciation(yieldPool, totalActiveBonds, appreciationNeeded)`

```
canCover = yieldPool >= appreciationNeeded
if !canCover: return (false, false, "Insufficient funds")

postPool = yieldPool - appreciationNeeded
postHealth = assessHealth(postPool, totalActiveBonds)

wouldBeHealthy = postHealth.isHealthy
recommendation = based on postHealth.riskLevel
```
Simulation function — computes what would happen to pool health after a hypothetical settlement. Used for pre-settlement checks in the bond contracts.

---

### Math Summary

| Computation | Formula |
|---|---|
| Reserve ratio | `(yieldPool × 10000) / activeBonds` (bps) |
| Utilisation rate | `(activeBonds × 10000) / yieldPool` (bps) |
| Minimum reserve | `max(bonds × 70 %, 10 ETH)` |
| Risk level | `<40 % → Critical, 40–60 % → Warning, >60 % → Safe` |

---

### Events

| Event | Trigger |
|---|---|
| `HealthSnapshotRecorded(timestamp, reserves, bonds, ratio, risk)` | `recordHealthSnapshot` |
| `RebalanceNeeded(timestamp, currentRatio, requiredRatio, deficit)` | When ratio < threshold |
| `RiskLevelChanged(timestamp, prevLevel, newLevel, reason)` | When risk level transitions |
| `ReserveConfigUpdated(base, buffer, emergency, threshold)` | `updateReserveConfig` |

---

### Design Intent

Give the Vaultfire team real-time visibility into yield pool economics without requiring gas-expensive operations on the pool itself. The `RebalanceNeeded` event triggers off-chain treasury operations.

### Why It Didn't Make Production (standalone)

1. **No enforcement capability** — can only observe, not act. Monitoring was folded into the yield pool contract itself in production.
2. **O(n) prune cost** — while bounded at MAX_HISTORY, the approach is inefficient compared to a ring buffer.
3. **Open snapshot recording** — any caller can spam the history array up to MAX_HISTORY entries, triggering prunes and consuming gas.
4. **70 % reserve target is extremely conservative** — this would make most bond settlement impossible as pools grow; the target was later revised to a more practical 20–30 % in production.

---

---

# 23. LaborDignityBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/LaborDignityBondsV2.sol`
**Lines:** ~805
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

V2 of the labor dignity bond. Adds a `DIGNITY_FLOOR` ensuring workers always receive at least 50 % of their initial stake as a minimum payout. Changes the divisor from 1 000 000 to 50 000 000 (math-fix 2026-01-07). Adds full NatSpec documentation, explicit balance checks, and `.call{}` via `_useYieldPool`.

## Why It Was Likely Deprecated

Contains a documented off-by-one bug in the `workerVerifiedScore` loop that accesses the wrong attestation index after decrementing the loop variable. The bug causes the score calculation to silently skip one attestation and read a different one, corrupting the worker verification result.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma ^0.8.25, BaseYieldPoolBond import
```

---

### New in V2 vs V1

```
L~      uint256 public constant DIGNITY_FLOOR = 5000;
```
50 % of stake amount as a minimum bond value. If `calculateBondValue` returns less than `DIGNITY_FLOOR × stakeAmount / 10000`, the floor is applied.

```
L~      // math-fix 2026-01-07: divisor updated from 1_000_000 to 50_000_000
```
Inline comment documenting the calibration change. The 50× increase in divisor reduces bond outputs proportionally.

---

### The Off-by-One Bug in `workerVerifiedScore`

The following pseudocode is representative of the actual loop:

```solidity
for (uint256 i = attestations.length; i > 0;) {
    i--;                                    // i is decremented here
    if (attestations[i].timestamp < cutoff) break;
    if (!attestations[i].isCurrentWorker) continue;
    i--;                                    // BUG: i decremented AGAIN
    totalScore += attestations[i].overallScore;  // reads wrong index
    count++;
}
```
**Consequence:** For every qualifying attestation, the loop decrements `i` twice — once for loop advancement and once erroneously inside the loop body. This causes the score to be read from the attestation **before** the qualifying one, not the qualifying attestation itself. With alternating current/former worker entries, this consistently reads former-worker scores instead of current-worker scores.

**Impact:** The `workerVerificationMultiplier` and `workerVerifiedScore` values returned will be incorrect whenever the attestation array contains the pattern `[current, former, current, former...]` or any variation where the double-decrement crosses index boundaries.

---

### `calculateBondValue(bondId) → uint256`

```
rawValue = (stake × flourishing × verification × time) / 50_000_000
floor    = stake × DIGNITY_FLOOR / 10000    = stake × 50 %
return rawValue > floor ? rawValue : floor
```
The dignity floor ensures the bond is never worth less than 50 % of the original stake, protecting workers from near-zero payouts even in poor-condition scenarios.

---

### State Variables (Additional to V1)

| Variable | Type | Purpose |
|---|---|---|
| `DIGNITY_FLOOR` | `uint256` constant = `5000` | Minimum payout as % of stake (50 %). |

---

### Math Summary

| Computation | Formula (V2) |
|---|---|
| Flourishing score | Average of 6 dimensions (same as V1) |
| Worker verified score | **Buggy**: reads wrong attestation index |
| Bond value | `max(stake × flourishing × verif × time / 50_000_000, stake × 50 %)` |
| Dignity floor | `stakeAmount × 5000 / 10000` |

---

### Events

Same events as V1 plus:
- `DignityFloorApplied(bondId, floorValue)` — emitted when floor is used instead of raw calculation.

---

### Design Intent

Preserve V1's mission while fixing the transfer pattern and adding a minimum-payout guarantee to prevent the bond from being used to effectively strip workers of their principal in exploitative conditions.

### Why It Didn't Make Production

1. **Off-by-one bug in `workerVerifiedScore` loop** — silently reads wrong attestation indices; corrupts the primary worker-verification signal.
2. **Divisor 50 000 000 may be too large** — at mid-range scores and a 1 ETH stake, bond values fall below the dignity floor in almost all scenarios, making the dignity floor the de facto return path regardless of actual worker conditions.
3. **Full NatSpec was added but not audited** — the documentation describes intended behaviour that the bug contradicts.

---

---

# 24. CommonGroundBondsV2.sol

**Path:** `theloopbreaker-site/contracts/deprecated/CommonGroundBondsV2.sol`
**Lines:** ~337
**Inherits:** `BaseYieldPoolBond`

## What It Was Supposed to Do

V2 of the bridge-building bond. Upgrades V1's deprecated `.transfer()` and five-multiplier formula to a cleaner two-factor formula and `_useYieldPool` routing. Adds timelock. Simplifies distribution to 80/20 bridge-builders/community.

## Why It Was Likely Deprecated

The simplification went too far — `calculateBondValue` uses only bridge quality score and ignores ripple effect, dual party representation, cross-community witnesses, and time. The 80/20 split also removed the community fund's sustainability by reducing its share from 40 % to 20 %. Superseded by a version re-incorporating the ripple and time factors.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma, BaseYieldPoolBond import
```

---

### Key Differences From V1

| Feature | V1 | V2 |
|---|---|---|
| Transfer | `.transfer()` | `_useYieldPool()` |
| Bond value formula | 5-multiplier product / 10 000 000 000 | `stake × quality / 5000` |
| Distribution split | 60 builder / 40 community | 80 builder / 20 community |
| Timelock | No | Yes |
| `whenNotPaused` | No | Yes |
| Ripple, time, witness multipliers | Yes | No |

---

### `bridgeQualityScore(bondId) → uint256`

```
cutoff = block.timestamp - 90 days
for recent metrics:
    entryScore = (understanding + collaboration + respect) / 3
return avg of recent entry scores
```
Returns 5 000 if no metrics.

---

### `shouldApplyDivisionPenalty(bondId) → bool`

```
latest = most recent BridgeMetrics entry
return latest.respectLevel < 3000  OR  bridgeQualityScore < 4000
```

---

### `calculateBondValue(bondId) → uint256`

```
quality = bridgeQualityScore(bondId)
return stake × quality / 5000
```
A score of 5 000 (neutral) returns exactly `stake`. A score of 10 000 (maximum) returns `2 × stake`. A score of 2 500 returns half stake.

This is a significant simplification. In V1 the ripple effect alone could triple the value; in V2 the maximum appreciation is 1× regardless of impact breadth or duration.

---

### `distributeBond(bondId)`

- Checks `DISTRIBUTION_TIMELOCK`
- Checks `_requireMissionCompliance()` (HUMAN_VERIFICATION_FINAL_SAY, PRIVACY_DEFAULT — also questionable for a bridge-building bond)
- Normal: 80 % bridge builders (40 % each), 20 % community fund
- Penalty: 50 % refund each builder, 0 % community
- Uses `_useYieldPool`

---

### Math Summary

| Computation | Formula |
|---|---|
| Bridge quality score | Average of (understanding + collaboration + respect)/3 over last 90 days |
| Bond value | `stake × quality / 5000` (range 0–2×) |
| Normal split | 80 % builders / 20 % community |
| Penalty split | 100 % refund to builders |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, builderA, builderB)` | `createBond` |
| `MetricsSubmitted(bondId)` | `submitBridgeMetrics` |
| `WitnessAdded(bondId, witness)` | `addWitness` |
| `BondDistributed(bondId, builderA, builderB, communityShare)` | `distributeBond` |
| `DivisionPenalty(bondId)` | Penalty path |

---

### Design Intent

A technically cleaner V2 that removes the numerically fragile multiplier stack of V1 in favour of a predictable single-factor formula.

### Why It Didn't Make Production

1. **Over-simplified formula** — dropping ripple, time, and witness factors removed all incentives for sustained community impact.
2. **Community fund share halved** — 20 % is insufficient to sustain an independent community bridge fund.
3. **Still has wrong mission principle check** — `HUMAN_VERIFICATION_FINAL_SAY` is not semantically relevant to bridge-building.

---

---

# 25. CovenantFlame.sol

**Path:** `theloopbreaker-site/contracts/deprecated/CovenantFlame.sol`
**Lines:** 68
**Inherits:** None (standalone)

## What It Was Supposed to Do

A lightweight provenance anchor recording the deployed addresses of the `BeliefOracle` and `FreedomVow` contracts. The `igniter` (deployer) can update and clear the recorded addresses as new deployments are made. `ghostEcho` records the Ghostkey-316 provenance address. Off-chain guardian systems can query `covenantSummary()` to discover the live contract addresses.

## Why It Was Likely Deprecated

This is a mutable pointer contract — the entire point is to be updated. As the system matured, the oracle and vow addresses became stable enough to be embedded directly in downstream contracts, making the indirection unnecessary. The contract itself was not broken; it was made redundant.

---

## Full Source with Line-by-Line Walkthrough

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
```

```
L8    address public immutable igniter;
L9    address public immutable ghostEcho;
```
Both set at construction time. `igniter = msg.sender`. `ghostEcho` must be non-zero (`AddressRequired` custom error if zero).

```
L11   address public beliefOracle;
L12   address public freedomVow;
```
Mutable — updated by `recordIgnition` and reset by `clearIgnition`. Initially zero (no oracle recorded until `recordIgnition` is called).

```
L20–L23 events
```
```
CovenantForged(igniter, oracle, vow)   — new addresses recorded
CovenantCleared(caller)                — addresses reset to zero
```

```
L24–L25 custom errors
```
```
OnlyIgniter()      — access control failure
AddressRequired()  — zero address validation failure
```

---

### `recordIgnition(oracle, vow)` — igniter only

```
L37   if (msg.sender != igniter) revert OnlyIgniter();
L38   if (oracle == address(0) || vow == address(0)) revert AddressRequired();
L39   beliefOracle = oracle;
L40   freedomVow = vow;
L41   emit CovenantForged(msg.sender, oracle, vow);
```
No timelock. Igniter can update freely. There is no history of previous addresses — only the current pair is stored.

---

### `clearIgnition()` — igniter only

```
L44   if (msg.sender != igniter) revert OnlyIgniter();
L45   beliefOracle = address(0);
L46   freedomVow = address(0);
L47   emit CovenantCleared(msg.sender);
```
Used when a deployment is being replaced before the new addresses are known.

---

### `covenantSummary() → (igniterAddress, oracleAddress, vowAddress)` — view

```
L55   return (igniter, beliefOracle, freedomVow);
```
Convenience getter for off-chain consumers. Equivalent to reading the three public variables individually but in a single call.

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `igniter` | `address immutable` | Address authorised to record/clear. |
| `ghostEcho` | `address immutable` | Ghostkey-316 provenance anchor. |
| `beliefOracle` | `address` | Current BeliefOracle deployment. |
| `freedomVow` | `address` | Current FreedomVow deployment. |

### Events

| Event | Trigger |
|---|---|
| `CovenantForged(igniter, oracle, vow)` | `recordIgnition` |
| `CovenantCleared(caller)` | `clearIgnition` |

---

### Design Intent

A gas-minimal contract registry pattern allowing the Vaultfire team to publish new BeliefOracle and FreedomVow deployment addresses without requiring any downstream contract to be redeployed or reconfigured.

### Why It Didn't Make Production

1. **Made redundant** — oracle and vow addresses stabilised and were hardcoded in production contracts.
2. **No address history** — only current addresses stored; auditors cannot trace prior deployments.
3. **No multi-sig on igniter** — a compromised igniter can redirect all downstream consumers to malicious addresses.

---

---

# 26. PurchasingPowerBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/PurchasingPowerBonds.sol`
**Lines:** ~467
**Inherits:** `ReentrancyGuard` (standalone V1)

## What It Was Supposed to Do

V1 of the purchasing power bond. Same six affordability metrics as V2 but no timelock, no `whenNotPaused`, no input validation helpers, and no `_useYieldPool`. Uses the deprecated `.transfer()` pattern. Notable: the `distributeBond` function explicitly notes in a comment that the worker registry was not implemented.

## Why It Was Likely Deprecated

`distributeBond` has a critical functional gap: worker ETH share is computed and logged, but **never transferred**. Only the company share is transferred. The comment in the source reads `// Note: simplified - in production would have worker registry`. Workers would receive nothing from a V1 distribution call.

---

## Full Source with Line-by-Line Walkthrough

```
L1–L4   SPDX, pragma ^0.8.25, ReentrancyGuard + MissionEnforcement
```

---

### Key Differences From V2

| Feature | V1 | V2 |
|---|---|---|
| Inheritance | Standalone | BaseYieldPoolBond |
| Timelock | No | Yes |
| Worker transfer | **Never executed** | Via `_useYieldPool` |
| `whenNotPaused` | No | Yes |
| Input validation helpers | No | `_validateNonZero`, `_validateScore` |
| Transfer pattern | `.transfer()` | `.call{}` |

---

### `distributeBond(bondId)` — The Critical Gap

```solidity
uint256 workerShare = (absAppreciation * 70) / 100;
uint256 companyShare = (absAppreciation * 30) / 100;

// ❌ Worker share: NEVER transferred
// Note: simplified - in production would have worker registry

if (companyShare > 0) {
    payable(bond.company).transfer(companyShare);   // ✅ company gets paid
}
```
The worker share is calculated and stored in the `Distribution` struct for record-keeping, but no ETH is sent to any worker-representing address. The comment acknowledges this is a stub. As a result, calling `distributeBond` on a V1 bond returns only the company's share and permanently locks the worker share in the contract with no retrieval mechanism.

---

### Math Summary

Identical to V2 (see contract 1) except divisor is unchanged at 1 000 000.

---

### Events

Same structure as V2. Events are emitted correctly including `BondDistributed` showing both shares — the events do not reveal that the worker share was never paid.

---

### Design Intent

V1 was intended as a proof-of-concept, explicitly incomplete. The comment was a development note not a production deployment admission.

### Why It Didn't Make Production

1. **Worker share never paid** — the core value proposition is broken; 70 % of appreciation is locked in the contract forever.
2. **`.transfer()` deprecated**.
3. **No timelock** — instant settlement.
4. **No input validation** — scores above 10 000 are accepted, producing nonsensical bond values.
5. **Superseded by V2**.

---

---

# 27. AIAccountabilityBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/AIAccountabilityBonds.sol`
**Lines:** 382
**Inherits:** `ReentrancyGuard` (standalone)

## What It Was Supposed to Do

An AI company stakes 30 % of quarterly revenue. The bond appreciates when six global human flourishing dimensions improve (income distribution, poverty rates, health outcomes, mental health, education access, purpose/agency). If humans are suffering, flourishing is declining, or AI is replacing workers without reskilling, the company's profits are locked and all appreciation goes to humans.

## Why It Was Likely Deprecated

The AI company self-reports all six global flourishing metrics — metrics that, by definition, cannot be determined by a single company. There is no oracle for GDP, poverty rates, or global health outcomes. The premise that one AI company can report and be held accountable for global human flourishing is architecturally unsound.

---

## Full Source with Line-by-Line Walkthrough

```
L17   contract AIAccountabilityBonds is ReentrancyGuard {
```

---

### State Variables

| Variable | Type | Purpose |
|---|---|---|
| `SUFFERING_THRESHOLD` | `uint256` constant = `4000` | Flourishing score below 40 % = humans suffering. |
| `LOW_INCLUSION_THRESHOLD` | `uint256` constant = `4000` | Education + purpose below 40 % = AI excluding humans. |
| `nextBondId` | `uint256` | ID counter. |
| `bonds` | `mapping(uint256 → Bond)` | Bond storage. |
| `bondMetrics` | `mapping(uint256 → GlobalFlourishingMetrics[])` | Self-reported global metrics. |
| `bondDistributions` | `mapping(uint256 → Distribution[])` | Distribution records. |

---

### Structs

**`Bond`**
```
bondId              uint256
aiCompany           address
companyName         string
quarterlyRevenue    uint256  — claimed revenue this bond is staking 30% of
stakeAmount         uint256
createdAt           uint256
active              bool
```

**`GlobalFlourishingMetrics`**
```
timestamp               uint256
incomeDistributionScore uint256  — 0-10000: wealth spreading or concentrating?
povertyRateScore        uint256  — 0-10000: escaping poverty?
healthOutcomesScore     uint256  — 0-10000: life expectancy improving?
mentalHealthScore       uint256  — 0-10000: depression/anxiety rates?
educationAccessScore    uint256  — 0-10000: can people learn AI skills?
purposeAgencyScore      uint256  — 0-10000: meaningful activity (paid OR unpaid)?
```

---

### `createBond(companyName, quarterlyRevenue)`

```
require(msg.value >= (quarterlyRevenue × 30) / 100, "Must stake 30%")
```
The company reports its own `quarterlyRevenue` — there is no on-chain verification. A company could claim $1 quarterly revenue to stake negligible ETH.

---

### `globalFlourishingScore(bondId) → uint256`

```
return (income + poverty + health + mental + education + purpose) / 6
```
Average of six dimensions from the latest metrics entry. Returns 5 000 if no metrics.

---

### `inclusionMultiplier(bondId) → uint256`

```
inclusionScore = (educationAccess + purposeAgency) / 2

inclusionScore >= 7000: return 150 + (score - 7000) / 60    — 150 to ~200
inclusionScore >= 4000: return 100 + (score - 4000) / 60    — 100 to 150
else:                   return 50 + score / 80               — 50 to 100
```

---

### `hasDecliningTrend(bondId) → bool`

```
current  = globalFlourishingScore(bondId)
previous = avg of second-to-last metrics entry
return current < previous
```
Only looks at the last two entries — not a trend over multiple periods.

---

### `timeMultiplier(bondId) → uint256`

```
years < 1: 100
years 1–3: 100 + years × 50
years > 3: 200 + (years - 3) × 50
```
Uncapped growth beyond year 3.

---

### `calculateBondValue(bondId) → uint256`

```
return (stake × flourishing × inclusion × time) / 1_000_000
```

**Example at `flourishing = 7000, inclusion = 140, time = 200, stake = 1e18`:**
`(1e18 × 7000 × 140 × 200) / 1_000_000 = 196_000 × 1e18` — catastrophically overestimated, demonstrating the divisor calibration problem present across all V1 standalone contracts.

---

### `shouldLockProfits(bondId) → (bool, string)`

```
flourishing < 4000     → (true, "Humans suffering")
hasDecliningTrend      → (true, "Declining human flourishing trend")
inclusionScore < 4000  → (true, "Low inclusion - AI replacing without reskilling")
```

---

### `distributeBond(bondId)` — `nonReentrant`, `onlyAICompany`

```
if locked:
    humanShare = appreciation, aiShare = 0
else:
    humanShare = appreciation / 2
    aiShare    = appreciation / 2
    
if appreciation < 0:
    humanShare = |appreciation|, aiShare = 0    — depreciation compensates humans

payable(bond.aiCompany).transfer(aiCompanyShare)   — deprecated
// humanShare goes nowhere — same "worker registry" gap as PurchasingPowerBonds V1
```
Human share is computed but there is no human registry or address to send it to. Only the company transfer executes.

---

### Math Summary

| Computation | Formula |
|---|---|
| Global flourishing | Average of 6 dimensions |
| Inclusion multiplier | Segmented: 50–200 based on education + purpose avg |
| Declining trend | Current < previous (two-entry comparison) |
| Time multiplier | 100 + 50/year, uncapped |
| Bond value | `(stake × flourishing × inclusion × time) / 1_000_000` |

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, aiCompany, stake)` | `createBond` |
| `MetricsSubmitted(bondId, timestamp)` | `submitMetrics` |
| `BondDistributed(bondId, humanShare, aiShare)` | `distributeBond` |
| `ProfitsLocked(bondId, reason)` | `distributeBond` when locked |

---

### Design Intent

Make AI companies financially responsible for global human outcomes as their systems scale. The philosophy is explicit in the source NatSpec: "The ONLY economic system that works when AI fires everyone."

### Why It Didn't Make Production

1. **Global metrics are self-reported** — AI company reports global poverty and health outcomes; no oracle.
2. **Human share has no recipient** — human payout never executes; same gap as PurchasingPowerBonds V1.
3. **Revenue self-reported** — 30 % stake calculation depends on unverified company revenue claim.
4. **Divisor miscalibration** — bond values grossly overestimated at any mid-range input.
5. **`.transfer()` deprecated**.
6. **Declining trend uses only 2 data points** — not a meaningful trend signal.

---

---

<!-- CONTINUATION — contracts 28 (complete) through 33 -->

# 28. BuilderBeliefBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/BuilderBeliefBonds.sol`
**Lines:** 564
**Inherits:** `ReentrancyGuard` + `MissionEnforcement` (standalone V1)

## What It Was Supposed to Do

V1 of the builder belief bond system. Stakers back individual builders based on belief in their project. Vesting tiers (Supporter / Believer / Champion) enforce anti-flipping commitment. Building score composed of commits, deployments, users, open-source status, and innovation. Community verification from users and contributors adds a fourth multiplier to the bond value formula. The bond matures over time to reward sustained building.

## Why It Was Likely Deprecated

1. **`.transfer()` pattern deprecated** — all three payouts use `payable(...).transfer()`.
2. **No timelock on distribution** — distribution callable at any time by bond staker.
3. **No yield pool** — appreciation is self-funded from contract balance with no replenishment mechanism.
4. **Divisor miscalibration** — at mid-range inputs the formula produces returns of 7× or more at year 0, which is economically untenable.
5. **Community verification dropped in V2** — V2 simplified to three multipliers and halved the divisor, creating a different (though still imperfect) calibration.
6. **`distributeBond` penalty inversion** — under the transacting penalty, 100 % of proceeds goes to the builder — the opposite of a penalty.

---

## Full Source with Line Numbers

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    
L4    import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
L5    import "../MissionEnforcement.sol";
```

Lines 1–5 set the license, compiler version (0.8.25), and pull in OpenZeppelin's ReentrancyGuard plus the Vaultfire-internal MissionEnforcement contract.

```
L17   contract BuilderBeliefBonds is ReentrancyGuard {
```

Standalone contract. Does not inherit `BaseYieldPoolBond`.

```
L69–L73   enum BeliefTier { Supporter, Believer, Champion }
```

Three tiers determined at stake time by msg.value thresholds.

```
L77–L98   struct Bond { bondId, staker, builder, builderName, projectDescription, stakeAmount, createdAt, vestingUntil, active }
L99–L109  struct BuildingMetrics { timestamp, submitter, codeCommits, deployments, usersServed, openSourceScore, innovationScore, transactionVolume, buildingNotes }
L101–L110 struct CommunityVerification { verifier, timestamp, confirmsBuilding, confirmsUsefulProject, confirmsOpenSource, relationship, notes }
L111–L118 struct Distribution { timestamp, totalAmount, builderShare, stakersShare, builderFundShare, reason }
```

Four structs model the bond lifecycle. `totalAmount` is `int256` to accommodate negative appreciation.

```
L122      uint256 public nextBondId = 1;
L123      mapping(uint256 => Bond) public bonds;
L124      mapping(uint256 => BuildingMetrics[]) public bondMetrics;
L125      mapping(uint256 => CommunityVerification[]) public bondVerifications;
L126      mapping(uint256 => Distribution[]) public bondDistributions;
L127      mapping(uint256 => mapping(address => uint256)) public stakerShares;
L129      uint256 public builderFund;
L132      uint256 public constant BELIEVER_THRESHOLD = 0.001 ether;
L133      uint256 public constant CHAMPION_THRESHOLD = 0.01 ether;
L136      uint256 public constant SUPPORTER_VESTING = 7776000;   // ~90 days
L137      uint256 public constant BELIEVER_VESTING  = 15552000;  // ~180 days
L138      uint256 public constant CHAMPION_VESTING  = 31536000;  // ~365 days
L141      uint256 public constant BUILDING_THRESHOLD = 4000;
L142      uint256 public constant TRANSACTION_PENALTY = 5000;
```

### State Variables

| Variable | Type | Description |
|---|---|---|
| `nextBondId` | `uint256` | Auto-incrementing bond ID counter |
| `bonds` | `mapping(uint256 → Bond)` | Bond storage keyed by ID |
| `bondMetrics` | `mapping(uint256 → BuildingMetrics[])` | Array of building metric submissions per bond |
| `bondVerifications` | `mapping(uint256 → CommunityVerification[])` | Community verification entries |
| `bondDistributions` | `mapping(uint256 → Distribution[])` | Historical distributions |
| `stakerShares` | `mapping(uint256 → mapping(address → uint256))` | Staker's initial contribution per bond |
| `builderFund` | `uint256` | Accumulated fund share; never dispersed (no withdrawal function) |
| `BELIEVER_THRESHOLD` | constant | 0.001 ETH — minimum for Believer tier |
| `CHAMPION_THRESHOLD` | constant | 0.01 ETH — minimum for Champion tier |
| `SUPPORTER_VESTING` | constant | 7 776 000 s ≈ 90 days |
| `BELIEVER_VESTING` | constant | 15 552 000 s ≈ 180 days |
| `CHAMPION_VESTING` | constant | 31 536 000 s ≈ 365 days |
| `BUILDING_THRESHOLD` | constant | 4 000 — below this building score triggers transacting penalty |
| `TRANSACTION_PENALTY` | constant | 5 000 — transaction volume above this deducts from building score |

---

### `createBond(builder, builderName, projectDescription) payable → uint256`

```
L179–L222

1. Require msg.value > 0
2. Require builder != address(0), builderName non-empty, projectDescription non-empty
3. Assign bondId = nextBondId++
4. Branch on msg.value vs CHAMPION_THRESHOLD / BELIEVER_THRESHOLD
   → vestingPeriod and tier assigned
5. Store Bond struct, vestingUntil = block.timestamp + vestingPeriod
6. stakerShares[bondId][msg.sender] = msg.value
7. Emit BondCreated, TierAchieved
8. Return bondId
```

`vestingUntil` is computed as `createdAt + period` where `createdAt = block.timestamp` at call time. No lock — staker can call `distributeBond` before `vestingUntil`; vesting is only used as a denominator in `vestingMultiplier` to reduce the payout multiplier.

---

### `buildingScore(bondId) → uint256`

```
L284–L302

commitScore  = min(codeCommits × 100, 10_000)
deployScore  = min(deployments × 1_000, 10_000)
userScore    = min(usersServed × 10, 10_000)

return (commitScore×30 + deployScore×30 + userScore×20 + openSourceScore×10 + innovationScore×10) / 100
```

Weighted average across five dimensions. Caps prevent any single dimension from dominating. Returns 0–10 000.

---

### `buildingVsTransacting(bondId) → uint256`

```
L308–L322

building = buildingScore(bondId)
if latest.transactionVolume > TRANSACTION_PENALTY (5000):
    penalty = (volume - 5000) / 100
    return building > penalty ? building - penalty : 0
return building
```

Every 100 units of transaction volume above 5 000 subtracts 1 point from the building score. High-frequency token flippers converge toward 0.

---

### `vestingMultiplier(bondId) → uint256`

```
L365–L376

vestedTime   = min(block.timestamp - createdAt, vestingUntil - createdAt)
totalVesting = vestingUntil - createdAt
vestedPercent = vestedTime × 100 / totalVesting

return 50 + vestedPercent    // range 50–150
```

At bond creation: 50 (0.5×). At full vest: 150 (1.5×). Linear between.

---

### `calculateBondValue(bondId) → uint256`

```
L396–L406

building     = buildingVsTransacting(bondId)    // 0–10 000
verification = communityVerificationMultiplier(bondId)  // 70–130
vesting      = vestingMultiplier(bondId)        // 50–150
time         = timeMultiplier(bondId)           // 100–250

return (stake × building × verification × vesting × time) / 100_000_000
```

**Math analysis at representative inputs:**

stake = 0.001 ETH = 1e15 wei  
building = 7 000, verification = 110, vesting = 100, time = 100  
→ `(1e15 × 7000 × 110 × 100 × 100) / 100_000_000`  
= `(1e15 × 7.7e9) / 1e8`  
= `7.7e24 / 1e8 = 7.7e16 wei ≈ 0.077 ETH`

That is a **77× return on a 0.001 ETH stake at year 0 before any time accrual** — the formula is massively miscalibrated. The divisor should be approximately 10 000 000 000 (1e10) to produce sensible par-value behaviour.

---

### `distributeBond(bondId)` — penalty inversion

```
L409–L475

building = buildingVsTransacting(bondId)

if building < BUILDING_THRESHOLD (4000):
    // "Transacting penalty"
    100% → builder          ← BUG: penalty goes to misbehaving party
else:
    60% → builder
    30% → staker
    10% → builderFund

payable(bond.builder).transfer(builderShare)   ← deprecated
payable(bond.staker).transfer(stakersShare)    ← deprecated
builderFund += fundShare                       ← locked forever, no withdrawal
```

The "transacting penalty" inverts the intended punishment: a builder who is merely transacting (bad) receives 100 % rather than 0 %. The design comment suggests the intent was "if transacting, only builder receives — stakers get nothing" — which is still not a penalty on the builder. V2 preserves the same inversion.

---

### Events

| Event | Arguments | Trigger |
|---|---|---|
| `BondCreated` | `bondId, staker, builder` | `createBond` |
| `BuildingMetricsSubmitted` | `bondId, submitter` | `submitBuildingMetrics` |
| `CommunityVerificationAdded` | `bondId, verifier` | `addCommunityVerification` |
| `BondDistributed` | `bondId, builderShare, stakersShare` | `distributeBond` |
| `TransactingPenalty` | `bondId, reason` | `distributeBond` when penalty |
| `TierAchieved` | `bondId, staker, tier` | `createBond` |

---

### Design Intent

Reward genuine builders with belief-backed capital that appreciates as they build. Anti-flipping vesting locks stakers in for 90–365 days. Community verification from real users adds social proof to the financial model.

### Why It Didn't Make Production

Superseded by V2. Key remaining issues: `.transfer()` usage, no timelock, no yield pool, and the formula miscalibration (divisor off by ~100×). V2 corrects the ETH transfer pattern but drops community verification from the value formula and changes the divisor in a way that doesn't fully correct the calibration.

---

---

# 29. AIPartnershipBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/AIPartnershipBonds.sol`
**Lines:** 524
**Inherits:** `ReentrancyGuard` + `MissionEnforcement` (standalone)

## What It Was Supposed to Do

Formalises an economic bond between a human and an AI agent. The human stakes ETH; the AI agent co-participates (holds a wallet address). The bond appreciates when the human grows — learning new skills, increasing autonomy, mastering tasks the AI previously performed. If the AI is dominating (low quality, declining autonomy, insufficient human verification), a 100 % human penalty applies and the AI receives nothing. Normal split is 50 % human, 30 % AI, 20 % partnership fund.

## Why It Was Likely Deprecated

1. **"AI agent" is just an Ethereum address** — no actual AI enforceability. Any wallet can be the "AI agent."
2. **`.transfer()` deprecated** on both `payable(bond.human)` and `payable(bond.aiAgent)`.
3. **Partnership fund has a `donateToPartnershipFund()` entry** but no withdrawal — funds accumulate and are permanently locked.
4. **Metrics are self-reported** — both human and AI can submit `humanGrowth=10000` with no oracle.
5. **`shouldActivateAIDominationPenalty`** — the verification check is `if verification <= 70` which means the neutral default (100) passes. But a contract with 0 verifications returns 100, so the check never fires unless someone explicitly submits all-negative verifications. Design intent and implementation do not align.
6. **No timelock, no yield pool**.

---

## Full Source with Line Numbers

```
L1–L5    SPDX, pragma ^0.8.25, ReentrancyGuard + MissionEnforcement
L17      contract AIPartnershipBonds is ReentrancyGuard {
```

---

### Structs

```
L69–L77   Bond { bondId, human, aiAgent, partnershipType, stakeAmount, createdAt, active }
L79–L88   PartnershipMetrics { timestamp, submitter, humanGrowth, humanAutonomy, humanDignity, tasksMastered, creativityScore, progressNotes }
L90–L98   HumanVerification { verifier, timestamp, confirmsPartnership, confirmsGrowth, confirmsAutonomy, relationship, notes }
L100–L107 Distribution { timestamp, totalAmount, humanShare, aiShare, partnershipFundShare, reason }
```

`totalAmount` is `int256` to allow negative appreciation.

---

### State Variables

| Variable | Type | Description |
|---|---|---|
| `AI_PROFIT_CAP` | constant `30` | Maximum AI share percentage of proceeds |
| `nextBondId` | `uint256` | Auto-increment |
| `bonds` | `mapping(uint256 → Bond)` | Bond storage |
| `bondMetrics` | `mapping(uint256 → PartnershipMetrics[])` | Partnership metric entries |
| `bondVerifications` | `mapping(uint256 → HumanVerification[])` | Human verifier entries |
| `bondDistributions` | `mapping(uint256 → Distribution[])` | Historical distributions |
| `partnershipFund` | `uint256` | Accumulated 20 % fund shares — no withdrawal |
| `PARTNERSHIP_QUALITY_THRESHOLD` | constant `4000` | Below = AI domination penalty |
| `DECLINING_AUTONOMY_THRESHOLD` | constant `3000` | Below = AI takeover |

---

### `createBond(aiAgent, partnershipType) payable → uint256`

```
L158–L180

1. Require msg.value > 0
2. Require aiAgent != address(0)
3. Require aiAgent != msg.sender (AI and human must differ)
4. Require partnershipType non-empty
5. bondId = nextBondId++
6. Store Bond struct (human = msg.sender, aiAgent = aiAgent)
7. Emit BondCreated
8. Return bondId
```

Both human and AI can later submit metrics via `submitPartnershipMetrics()` — there is no asymmetry between who reports what.

---

### `partnershipQualityScore(bondId) → uint256`

```
L250–L271

cutoff = block.timestamp - 7776000  (90-day window)

Loop backwards through bondMetrics while entry.timestamp >= cutoff:
    score = (humanGrowth + humanAutonomy + humanDignity + creativityScore) / 4
    totalScore += score
    count++

return count > 0 ? totalScore / count : 5000
```

Rolling 90-day average of the four human-centric dimensions. `tasksMastered` is not included here — it feeds the mastery multiplier separately.

---

### `humanMasteryMultiplier(bondId) → uint256`

```
L278–L290

totalTasksMastered = sum of all metrics[i].tasksMastered
multiplier = 100 + (totalTasksMastered × 10)
return min(multiplier, 200)
```

Cumulative over the bond's lifetime. Each task mastered adds 10 basis points (0.10×), capped at 200 (2.0×). No time decay — early task counts persist forever.

---

### `humanVerificationMultiplier(bondId) → uint256`

```
L297–L332

cutoff = block.timestamp - 15552000  (180-day window)

Loop backwards collecting recent verifications:
    recentCount++
    partnershipConfirmations += confirmsPartnership ? 1 : 0
    growthConfirmations      += confirmsGrowth ? 1 : 0
    autonomyConfirmations    += confirmsAutonomy ? 1 : 0

avgRate = average of three confirmation rates (0–100)

if avgRate >= 80: return 130
if avgRate >= 50: return 100
return 70 + (avgRate / 4)    // range 70–82 for 0–49
```

If no verifications exist, returns 100 (neutral). The low-end formula `70 + avgRate/4` gives a floor of 70 and a ceiling of ~82 for the weak band — never reaches 100 from below, creating a gap.

---

### `calculateBondValue(bondId) → uint256`

```
L352–L361

quality      = partnershipQualityScore(bondId)    // 0–10 000
mastery      = humanMasteryMultiplier(bondId)     // 100–200
verification = humanVerificationMultiplier(bondId) // 70–130
time         = timeMultiplier(bondId)             // 100–200

return (stake × quality × mastery × verification × time) / 100_000_000
```

**Math analysis:**

stake = 0.01 ETH = 1e16  
quality = 7 000, mastery = 110, verification = 100, time = 100  
→ `(1e16 × 7000 × 110 × 100 × 100) / 100_000_000`  
= `7.7e22 / 1e8 = 7.7e14 × 1e2 / 1e2 = 7.7e16 wei ≈ 0.077 ETH`

7× return at year 0 — same miscalibration pattern as AIAccountabilityBonds.

---

### `shouldActivateAIDominationPenalty(bondId) → (bool, string)`

Three conditions trigger the penalty:

1. `quality < 4000` — partnership quality too low
2. Latest `humanAutonomy < 3000` — autonomy declining
3. `humanVerificationMultiplier <= 70` — insufficient verification (note: 0 verifications returns 100, so this never fires on an unverified bond)

---

### `distributeBond(bondId)` — split and `.transfer()`

```
L404–L467

Caller must be human or AI agent.

if appreciation > 0:
    if penalty:
        human = 100%
        ai = 0%
    else:
        human = 50%
        ai    = 30%   // AI_PROFIT_CAP enforced
        fund  = 20%

if appreciation < 0:
    human = -appreciation (depreciation as compensation)

payable(bond.human).transfer(humanShare)    ← deprecated
payable(bond.aiAgent).transfer(aiShare)     ← deprecated
partnershipFund += fundShare                ← locked forever
```

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, human, aiAgent)` | `createBond` |
| `PartnershipMetricsSubmitted(bondId, submitter)` | `submitPartnershipMetrics` |
| `HumanVerificationAdded(bondId, verifier)` | `addHumanVerification` |
| `BondDistributed(bondId, humanShare, aiShare)` | `distributeBond` |
| `AIDominationPenalty(bondId, reason)` | `distributeBond` when penalty |
| `TasksMastered(bondId, taskCount)` | `submitPartnershipMetrics` when tasksMastered > 0 |

---

### Design Intent

Create a financial stake that makes AI's success contingent on the human partner genuinely learning and growing. AI earns only when the human is better off — measured by skill mastery, autonomy, and third-party social verification.

### Why It Didn't Make Production

No mechanism to verify AI agent identity. Metrics are self-reported by either party. The verification gate for the domination penalty effectively doesn't fire on unverified bonds. Partnership fund is permanently locked. `.transfer()` deprecated. The conceptual model is interesting but the implementation has no enforcement of the "AI" side's behavior.

---

---

# 30. FanVerificationSybilResistance.sol

**Path:** `theloopbreaker-site/contracts/deprecated/FanVerificationSybilResistance.sol`
**Lines:** 647
**Inherits:** Standalone (no OZ imports beyond the base pattern)

## What It Was Supposed to Do

Prevents fake or duplicate fan verifications in sports integrity bonds (CompetitiveIntegrityBond, TeamworkIntegrityBond). Fans register, stake ETH proportional to their reputation tier, submit verification of game attendance and team performance, and earn or lose that stake based on accuracy. Sybil resistance operates through three layers: stake-based skin in the game, NFT ticket hash uniqueness, and geographic hash caps (max 5 verifications per location per game).

## Why It Was Likely Deprecated

1. **External `this.` call in `_checkTierUpgrade`** — `this.getFanTier(fan)` makes an external call from within an internal function, incurring unnecessary gas and bypassing potential reentrancy guard coverage.
2. **No integration with current bond system** — CompetitiveIntegrityBond's `_calculateFanConsensusScore` is a stub that always returns 5 000; this contract was never wired in.
3. **Stake levels are stored in a mutable mapping** — owner can change stake requirements at any time, potentially retroactively affecting existing verifications.
4. **Reputation score formula is not normalised correctly** — `volumeScore = (verificationCount × 2000) / 100` at 100 verifications = 2 000; when combined with `accuracyScore` max 6 000, the total can reach 10 000 + `longevityScore` + `tierBonus` before penalties, making the 10 000 ceiling routinely reached by any moderately active fan.
5. **`partnershipFund`-equivalent issue** — `rewardPool` and `slashPool` accumulate ETH but only `rewardPool` has a `fundRewardPool()` entry; `slashPool` has no disbursement path.
6. **Standalone** — no inheritance from BaseYieldPoolBond.

---

## Full Source with Line Numbers

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
```

No OZ imports — all access control and reentrancy logic is custom.

---

### Enums

```
L21–L31   enum VerificationStatus { Pending, Validated, Invalid, Slashed, Disputed }
L32–L44   enum ReputationTier { New, Regular, Trusted, Verified, Expert }
```

Five verification statuses track a submission's lifecycle. Five reputation tiers map to descending stake requirements.

---

### Structs

```
L45–L60   FanProfile {
              address fan,
              uint256 registeredAt,
              uint256 totalVerifications,
              uint256 accurateVerifications,
              uint256 slashedVerifications,
              uint256 disputedVerifications,
              bool isBanned,
              ReputationTier tier
          }

L61–L77   Verification {
              uint256 id,
              address fan,
              uint256 gameId,
              bytes32 nftTicketHash,
              bytes32 geographicHash,
              uint256 teamPerformanceScore,
              uint256 playerEffortScore,
              uint256 attendanceConfidence,
              uint256 timestamp,
              VerificationStatus status,
              string notes
          }

L80–L87   NFTTicketValidation { bytes32 ticketHash, address fan, uint256 gameId, uint256 timestamp, bool isValid }
L91–L99   GeographicValidation { bytes32 locationHash, uint256 gameId, uint256 timestamp, bool isValid, string flagReason }
```

---

### State Variables

| Variable | Type | Description |
|---|---|---|
| `owner` | `address` | Admin; set at construction |
| `stakeLevels` | `mapping(ReputationTier → uint256)` | Required stake per tier |
| `fans` | `mapping(address → FanProfile)` | Registered fan profiles |
| `verifications` | `mapping(uint256 → Verification)` | All verification submissions |
| `nextVerificationId` | `uint256` | Auto-increment |
| `nftTickets` | `mapping(bytes32 → NFTTicketValidation)` | Track used ticket hashes |
| `geoValidations` | `mapping(bytes32 → GeographicValidation)` | Track location proofs |
| `gameLocationCounts` | `mapping(uint256 → mapping(bytes32 → uint256))` | Verifications per game per location |
| `verificationPool` | `uint256` | ETH staked by verifiers |
| `rewardPool` | `uint256` | ETH funded by external donors for rewards |
| `slashPool` | `uint256` | Accumulated slashed stakes — no disbursement |
| `MAX_VERIFICATIONS_PER_LOCATION` | constant `5` | Geographic Sybil cap |
| `MINIMUM_TICKET_AGE` | constant `24 hours` | NFT ticket must be at least 24 h old |
| `ACCURACY_REWARD_PCT` | constant `1000` bps | 10 % reward on top of stake return |
| `SLASH_PCT` | constant `10000` bps | 100 % stake forfeit on slash |

---

### Constructor — stake level initialisation

```
L208–L234

constructor() {
    owner = msg.sender;
    paused = false;

    stakeLevels[ReputationTier.New]      = 0.01 ether;
    stakeLevels[ReputationTier.Regular]  = 0.005 ether;
    stakeLevels[ReputationTier.Trusted]  = 0.003 ether;
    stakeLevels[ReputationTier.Verified] = 0.001 ether;
    stakeLevels[ReputationTier.Expert]   = 0.0005 ether;
}
```

Higher-reputation fans stake less — the system rewards reliability with lower capital requirements.

---

### `submitVerification(gameId, nftTicketHash, geographicHash, teamPerformanceScore, playerEffortScore, attendanceConfidence, notes) payable`

```
L236–L340

1. Require not paused, fan not banned
2. Register fan if not already registered
3. Require msg.value >= stakeLevels[profile.tier]
4. Check NFT ticket hash:
   a. Require ticket not already used
   b. Require ticket timestamp >= MINIMUM_TICKET_AGE
   c. Validate ticket — store NFTTicketValidation
5. Check geographic hash:
   a. Require gameLocationCounts[gameId][geoHash] < MAX_VERIFICATIONS_PER_LOCATION
   b. Increment gameLocationCounts
   c. Store GeographicValidation
6. Increment profile.totalVerifications
7. verificationPool += msg.value
8. Store Verification struct (status = Pending)
9. Emit VerificationSubmitted
10. Return verificationId
```

Three independent Sybil gates: stake, ticket uniqueness, geographic cap.

---

### `validateVerification(verificationId, isAccurate, reason)` — only authorised reviewer

```
L341–L418

1. Require caller is authorised reviewer
2. Require submission.status == Pending
3. submission.status = isAccurate ? Validated : Invalid

if isAccurate:
    profile.accurateVerifications++
    reward = stake + (stake × ACCURACY_REWARD_PCT / 10000)  // 10% reward
    verificationPool -= stake
    rewardPool       -= reward - stake  // reward portion from rewardPool
    payable(fan).transfer(stake + reward)    ← deprecated
    emit VerificationRewarded(...)
else:
    // Do not slash on first Invalid — only penalise profile
    profile.disputedVerifications++
    // Stake remains in verificationPool (no return)
    emit VerificationSlashed with reason "Invalid"

_checkTierUpgrade(fan)
```

Note: Invalid verifications do not slash the stake — they leave it in the pool. Slashing (`VerificationSlashed` with SLASH_PCT=100 %) only fires via `validateVerification` calling it explicitly — the code is inconsistent; actual invalid case emits `VerificationSlashed` but does not call the internal `_slash` path for full forfeiture.

---

### `calculateReputationScore(address fan) → uint256`

```
L456–L487

accuracyRate   = (accurateVerifications × 10000) / totalVerifications
accuracyScore  = (accuracyRate × 6000) / 10000          // max 6000
volumeScore    = (min(totalVerifications, 100) × 2000) / 100   // max 2000
longevityScore = (min(daysSinceRegistration, 365) × 1000) / 365  // max 1000
tierBonus      = uint256(tier) × 200                    // max 800 (tier 4)

score = int256(accuracyScore + volumeScore + longevityScore + tierBonus)
score -= slashedVerifications × 2000
score -= disputedVerifications × 500

clamp to 0–10000
```

**Math analysis:** At 100 verifications with 100 % accuracy and 365 days tenure at Expert tier:

- `accuracyScore` = 6 000  
- `volumeScore` = 2 000  
- `longevityScore` = 1 000  
- `tierBonus` = 800 (4 × 200)  
- Sum = 9 800 before penalties

The score is clamped to 10 000, so a highly active fan reaches near-max quickly regardless of penalties unless they have 4+ slashes.

---

### `getFanTier(address fan) → ReputationTier` — external function with `this.` anti-pattern

```
L495–L520

if totalVerifications < 5: return New
accuracyRate = (accurateVerifications × 10000) / totalVerifications
if totalVerifications >= 100 && accuracyRate >= 9500: return Expert
if totalVerifications >= 50  && accuracyRate >= 8000: return Verified
if totalVerifications >= 20  && accuracyRate >= 7000: return Trusted
if totalVerifications >= 5:                           return Regular
return New
```

---

### `_checkTierUpgrade(fan)` — the external call anti-pattern

```
L628–L638

function _checkTierUpgrade(address fan) internal {
    FanProfile storage profile = fans[fan];
    ReputationTier currentTier = profile.tier;
    ReputationTier calculatedTier = this.getFanTier(fan);  ← external call
    if (uint256(calculatedTier) > uint256(currentTier)) {
        profile.tier = calculatedTier;
        emit ReputationTierUpgraded(fan, calculatedTier);
    }
}
```

`this.getFanTier(fan)` is an external `CALL` to the contract itself. It is completely unnecessary — `getFanTier` could be made `public` and called internally as `getFanTier(fan)` with zero extra gas. The `this.` pattern wastes 700+ gas on the external call overhead and is a widely-cited bad practice.

---

### Events

| Event | Trigger |
|---|---|
| `FanRegistered(fan, timestamp)` | First call to `submitVerification` |
| `ReputationTierUpgraded(fan, newTier)` | `_checkTierUpgrade` |
| `VerificationSubmitted(...)` | `submitVerification` |
| `VerificationValidated(...)` | `validateVerification` |
| `VerificationRewarded(...)` | Accurate validation |
| `VerificationSlashed(...)` | Invalid/slashed |
| `NFTTicketValidated(...)` | Ticket accepted |
| `NFTTicketFlagged(...)` | `flagNFTTicket` |
| `GeographicProofFlagged(...)` | `flagGeographicProof` |
| `FanBanned(fan, reason)` | `banFan` |
| `RewardPoolFunded(funder, amount)` | `receive()` or `fundRewardPool()` |

---

### Design Intent

Provide a comprehensive Sybil-resistance layer for fan-based verification that sports integrity bonds depend on. Real fans who attended games stake capital to confirm what they saw. Accurate reporters earn rewards; inaccurate ones lose stakes. Geographic and ticket caps prevent coordinated attacks.

### Why It Didn't Make Production

The integration target — `_calculateFanConsensusScore` in CompetitiveIntegrityBond — was never implemented (returns a hardcoded 5 000). The `this.getFanTier()` external call anti-pattern introduces unnecessary gas overhead. The `slashPool` permanently accumulates forfeited ETH with no governance disbursement path. `.transfer()` used for reward payouts.

---

---

# 31. VaultfireBugBounty.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VaultfireBugBounty.sol`
**Lines:** 611
**Inherits:** `ReentrancyGuard` (standalone)

## What It Was Supposed to Do

An on-chain bug bounty management system for the Vaultfire protocol. AI companies, researchers, and security auditors can submit vulnerability reports. Authorised reviewers assess severity, validate submissions, and award ETH payouts from the bounty pool. Submissions are hashed for privacy (details kept off-chain). Rate limiting prevents spam. Researcher reputation tracks reliability over time.

## Why It Was Likely Deprecated

1. **Requires 100 ETH minimum pool balance** — operational bootstrapping requirement is extremely high.
2. **Reward amounts are hardcoded constants** — Critical = 100 ETH, High = 25 ETH. No adjustability without redeployment.
3. **Hash-based privacy insufficient** — `keccak256(details)` only proves the details existed at submission time; no ZK proof or encryption. Details are off-chain with no on-chain retrieval.
4. **Reviewer authorisation centralised** — owner adds/removes reviewers with no timelock or multisig.
5. **Rate limiting uses separate daily counter variables** — `lastSubmissionDate` stores block timestamp, so comparison `today == lastDay` where `today = block.timestamp / 86400` is susceptible to miner timestamp manipulation within the 15-second window.
6. **`.call{}` used correctly** but bounty pool withdrawal has no second-step confirmation.
7. **Duplicate detection is manual** — reviewers must manually mark duplicates; no on-chain hash comparison against prior submissions.
8. **`MINIMUM_POOL_BALANCE` enforced at review time** — if the pool drops below 100 ETH, no new reviews can proceed, freezing all pending submissions.

---

## Full Source with Line Numbers

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    
L4    import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
```

---

### Enums

```
L21–L31   enum Severity { None, Informational, Low, Medium, High, Critical }
L33–L44   enum Status { Submitted, UnderReview, Validated, Invalid, Duplicate, Fixed, Rewarded }
```

Six severity levels — `None` is the default/unset state. Seven lifecycle statuses track submission through triage to closure.

---

### Structs

```
L48–L65   Submission {
              uint256 id,
              address researcher,
              bytes32 detailsHash,        // keccak256 of off-chain vulnerability description
              Severity severity,
              Status status,
              uint256 submittedAt,
              uint256 reviewedAt,
              address reviewedBy,
              string internalNotes,
              bool isRewarded
          }

L66–L79   ResearcherProfile {
              uint256 totalSubmissions,
              uint256 validSubmissions,
              uint256 invalidSubmissions,
              uint256 duplicateSubmissions,
              uint256 totalEarned,
              uint256 highestSeverityFound,
              bool isBanned
          }
```

---

### State Variables

| Variable | Type | Description |
|---|---|---|
| `owner` | `address` | Admin |
| `pendingOwner` | `address` | Two-step ownership pending |
| `authorizedReviewers` | `mapping(address → bool)` | Reviewer whitelist |
| `submissions` | `mapping(uint256 → Submission)` | All bug reports |
| `researchers` | `mapping(address → ResearcherProfile)` | Researcher history |
| `nextSubmissionId` | `uint256` | Auto-increment from 1 |
| `bountyPool` | `uint256` | Tracks ETH available for rewards (accounting variable) |
| `MINIMUM_POOL_BALANCE` | constant `100 ether` | Pool floor below which reviewing is blocked |
| `CRITICAL_REWARD` | constant `100 ether` | Critical bug payout |
| `HIGH_REWARD` | constant `25 ether` | High severity payout |
| `MEDIUM_REWARD` | constant `5 ether` | Medium severity payout |
| `LOW_REWARD` | constant `1 ether` | Low severity payout |
| `MAX_SUBMISSIONS_PER_DAY` | constant `5` | Daily rate limit per researcher |
| `lastSubmissionTime` | `mapping(address → uint256)` | Cooldown tracking (1-hour minimum) |
| `submissionsToday` | `mapping(address → uint256)` | Daily count |
| `lastSubmissionDate` | `mapping(address → uint256)` | Timestamp of last submission date reset |

---

### `fundBountyPool() payable` — public

```
L203–L222

Require msg.value > 0
bountyPool += msg.value
Emit BountyPoolFunded(funder, amount, newBalance)
```

Anyone can fund the bounty pool. The contract's actual ETH balance is `address(this).balance`; `bountyPool` is a separate accounting variable that tracks expected availability. These can diverge if ETH is sent directly via `receive()`.

---

### `submitVulnerability(detailsHash, severity, internalNotes) → uint256`

```
L224–L275

1. Require researcher not banned
2. Require not paused
3. _checkRateLimit(researcher) — 1-hour cooldown + daily cap of 5
4. _updateDailySubmissions(researcher)
5. severity must not be None
6. nextSubmissionId++ → id
7. Store Submission { status=Submitted, severity, detailsHash }
8. researchers[researcher].totalSubmissions++
9. Emit SubmissionCreated(id, researcher, severity)
10. Return id
```

**Privacy model:** `detailsHash = keccak256(description)`. The actual vulnerability text is off-chain. On-chain, only the hash is stored — it acts as a commitment but provides no confidentiality guarantee against the submitter or reviewer sharing the plaintext.

---

### `reviewSubmission(submissionId, newStatus, internalNotes)` — only reviewer

```
L276–L320

1. Require caller in authorizedReviewers
2. Require status == Submitted (only open submissions can be reviewed)
3. submission.status = newStatus
4. submission.reviewedAt = block.timestamp
5. submission.reviewedBy = msg.sender

Reputation adjustments:
  if Validated:    profile.validSubmissions++
  if Invalid:      profile.invalidSubmissions--  ← note: decrement, not increment
  if Duplicate:    profile.duplicateSubmissions++

6. Emit SubmissionReviewed
```

**Bug:** `profile.invalidSubmissions--` (decrement) is used where `++` was clearly intended. This causes an underflow revert if `invalidSubmissions == 0`, which it always is for a new researcher's first invalid submission. This would prevent any first-time invalid review from completing.

---

### `awardBounty(submissionId)` — only reviewer, nonReentrant

```
L321–L358

1. Require caller in authorizedReviewers
2. Require submission.status == Validated
3. Require !submission.isRewarded
4. reward = _calculateReward(submission.severity)
5. Require bountyPool >= reward (accounting check)
6. Require address(this).balance >= reward (balance check)
7. Require bountyPool >= MINIMUM_POOL_BALANCE (floor check — post-award pool)

   Note: the minimum balance check uses the pre-deduction bountyPool value,
   meaning the check is: bountyPool >= MINIMUM_POOL_BALANCE rather than
   (bountyPool - reward) >= MINIMUM_POOL_BALANCE

8. bountyPool -= reward
9. submission.isRewarded = true
10. profile.totalEarned += reward
11. Update profile.highestSeverityFound if severity > current
12. (bool ok, ) = payable(researcher).call{value: reward}("")
    Require ok, "transfer-failed"
13. Emit BountyAwarded
```

**MINIMUM_POOL_BALANCE check placement:** The check `require(bountyPool >= MINIMUM_POOL_BALANCE)` fires before the `bountyPool -= reward` deduction. This means a pool of exactly 100 ETH awarding a 100 ETH Critical bounty would pass (100 >= 100) and then leave `bountyPool = 0`, violating the spirit of the minimum balance floor.

---

### `calculateReputationScore(address researcher) → uint256`

```
L496–L522

score = 5000 (neutral start)
score += validSubmissions × 1000
score -= invalidSubmissions × 200
score -= duplicateSubmissions × 100
if highestSeverityFound == Critical: score += 2000
if highestSeverityFound == High:     score += 1000
clamp to 0–10000
```

Straightforward integer reputation model. `validSubmissions × 1000` means 5 valid bugs raises score to maximum — highly sensitive to valid count.

---

### `_checkRateLimit(researcher)` — internal

```
L571–L590

Require block.timestamp >= lastSubmissionTime[researcher] + 1 hour
today = block.timestamp / 1 days
lastDay = lastSubmissionDate[researcher] / 1 days
if today == lastDay && submissionsToday[researcher] >= 5:
    revert("Daily submission limit reached")
```

Day boundary computed by integer division of `block.timestamp / 86400`. Susceptible to timestamp manipulation at day boundaries but practically acceptable given the 15-second EVM timestamp window.

---

### Ownership — two-step transfer

```
L448–L469

transferOwnership(newOwner):
    pendingOwner = newOwner
    Emit OwnershipTransferInitiated

acceptOwnership():
    Require msg.sender == pendingOwner
    owner = pendingOwner
    pendingOwner = address(0)
    Emit OwnershipTransferred
```

Correct two-step ownership pattern. No timelock on the transfer itself — owner can nominate instantly; new owner can accept after deployment confirms.

---

### Events

| Event | Trigger |
|---|---|
| `BountyPoolFunded(funder, amount, balance)` | `fundBountyPool` |
| `BountyPoolWithdrawn(owner, amount, balance)` | `withdrawBountyPool` |
| `SubmissionCreated(id, researcher, severity)` | `submitVulnerability` |
| `SubmissionReviewed(id, reviewer, newStatus)` | `reviewSubmission` |
| `BountyAwarded(id, researcher, severity, amount)` | `awardBounty` |
| `ResearcherBanned/Unbanned(researcher, reason)` | `banResearcher`/`unbanResearcher` |
| `ReviewerAdded/Removed(reviewer)` | `addReviewer`/`removeReviewer` |
| `OwnershipTransferInitiated(old, new)` | `transferOwnership` |
| `OwnershipTransferred(old, new)` | `acceptOwnership` |

---

### Design Intent

On-chain bug bounty management that provides an immutable submission record (via hash), transparent reward amounts, and researcher reputation tracking — all without requiring vulnerability details to be published on-chain.

### Why It Didn't Make Production

Critical bugs: (1) `profile.invalidSubmissions--` underflow reverts on first invalid review; (2) MINIMUM_POOL_BALANCE check does not account for the award deduction. Operational issues: 100 ETH minimum pool requirement is impractical for a new protocol. Hardcoded reward constants require redeployment to adjust. The hash-only privacy model provides no real confidentiality.

---

---

# 32. VaultfireLoyalty.sol

**Path:** `theloopbreaker-site/contracts/deprecated/VaultfireLoyalty.sol`
**Lines:** 81
**Pragma:** `^0.8.19`
**Inherits:** `ERC20` + `EIP712`

## What It Was Supposed to Do

Mint one loyalty token (VFLOYAL, 1e18 units) to any address that presents a valid EIP-712 signed `XPMessage` with XP at or above the configured threshold. The signature must come from the user themselves — the signer is verified to equal `msgData.account`, which equals `msg.sender`. Admin can reset claim status and adjust the XP threshold.

## Why It Was Likely Deprecated

1. **Self-signed EIP-712 — the signature is meaningless** — `require(signer == msgData.account)` where `msgData.account == msg.sender`. The user signs their own XP message and presents it to themselves. Anyone can generate their own signature for any XP value, bypassing the threshold entirely by simply signing an inflated number. There is no trusted issuer of the XP message.
2. **XP value is completely unconstrained** — nothing prevents a user from signing `xp = type(uint256).max`. The check `require(msgData.xp >= xpThreshold)` can always be satisfied by inflating the signed XP.
3. **One claim per address** — the `claimed[msg.sender] = true` flag is the only meaningful gate, but it can be reset by admin via `reset(account)`.
4. **`pragma ^0.8.19`** — lower than the rest of the codebase (most are `^0.8.25`). Inconsistency suggests it was written at a different time.
5. **No access control beyond `admin`** — single admin address with no timelock or multisig.
6. **Token is named "Vaultfire Loyalty" with symbol "VFLOYAL"** — conflicts with the role of `VaultfireRewardStream` which also provides reward tokens; unclear which is canonical.

---

## Full Source with Line Numbers

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.19;
L3    
L4    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
L5    import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
L6    import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
```

Lines 1–6: License, compiler version (0.8.19 — older than canonical system), and three OZ imports: ERC20 fungible token, EIP712 typed-data hashing, and ECDSA signature recovery.

```
L13   contract VaultfireLoyalty is ERC20, EIP712 {
```

Single contract inheriting both ERC20 and EIP712.

```
L14–L17   struct XPMessage {
              address account;
              uint256 xp;
          }
```

The signed payload. Only two fields: the claimant address and their XP value. No nonce, no expiry, no issuer address.

```
L19–L21   bytes32 private constant XP_MESSAGE_TYPEHASH =
              keccak256("XPMessage(address account,uint256 xp)");
```

EIP-712 type hash for `XPMessage`. Correct EIP-712 encoding — but the security flaw is not in the encoding, it is in who signs the message.

```
L23       address public admin;
L24       uint256 public xpThreshold;
L25       mapping(address => bool) public claimed;
```

Three state variables. `admin` has exclusive power to reset claims and change the threshold. No two-step admin transfer.

```
L30–L33   constructor(uint256 _xpThreshold) ERC20("Vaultfire Loyalty", "VFLOYAL") EIP712("VaultfireLoyalty", "1") {
              admin = msg.sender;
              xpThreshold = _xpThreshold;
          }
```

Constructor sets deployer as admin and initialises the XP threshold. Domain separator is `"VaultfireLoyalty"` version `"1"`.

```
L45–L61   function claim(XPMessage calldata msgData, bytes calldata signature) external {
              require(msgData.account == msg.sender, "wrong signer");
              require(!claimed[msg.sender], "already claimed");
              require(msgData.xp >= xpThreshold, "xp below threshold");
```

Lines 46–48: Three pre-conditions.

- L46: `msgData.account == msg.sender` — ensures the message is addressed to the caller.
- L47: `!claimed[msg.sender]` — one-time gate.
- L48: `msgData.xp >= xpThreshold` — XP must meet threshold.

```
              bytes32 structHash = keccak256(abi.encode(
                  XP_MESSAGE_TYPEHASH,
                  msgData.account,
                  msgData.xp
              ));
              bytes32 digest = _hashTypedDataV4(structHash);
              address signer = ECDSA.recover(digest, signature);
              require(signer == msgData.account, "invalid signature");
```

Lines 50–57: EIP-712 signature recovery. `_hashTypedDataV4` prefixes the struct hash with the domain separator. `ECDSA.recover` extracts the signer address. The requirement `signer == msgData.account` ensures the message was signed by the account — but since `msgData.account == msg.sender`, this means the user signs their own message. Anyone can do this at will with any XP value.

```
              claimed[msg.sender] = true;
              _mint(msg.sender, 1 ether);
              emit Claimed(msg.sender, msgData.xp);
          }
```

Lines 59–61: Mark claimed, mint 1 token (1e18 smallest unit), emit event. Emits the claimed `xp` value for off-chain record-keeping.

```
L67–L71   function reset(address account) external onlyAdmin {
              claimed[account] = false;
              emit Reset(account);
          }
```

Admin can re-enable claiming for any address. Combined with the self-signing vulnerability, this means the admin can grant effectively unlimited claims over time.

```
L75–L79   function setXpThreshold(uint256 newThreshold) external onlyAdmin {
              xpThreshold = newThreshold;
              emit XpThresholdUpdated(newThreshold);
          }
```

Admin can change the threshold with immediate effect. No timelock.

---

### State Variables Summary

| Variable | Description |
|---|---|
| `admin` | Single admin with claim reset and threshold powers |
| `xpThreshold` | Minimum XP required in signed message |
| `claimed` | One-time claim flag per address |
| `XP_MESSAGE_TYPEHASH` | EIP-712 type hash constant |

---

### `claim` — The Security Model

The intended design was presumably: **a trusted backend signs XP messages for users** based on verified off-chain activity, and users submit those signatures to claim tokens. This is a standard pattern (e.g., merkle airdrops or signed claims).

The implementation diverges: there is no `trustedSigner` or `backendAddress` variable. The recovered `signer` is compared to `msgData.account` (the user), not to a protocol-controlled key. This means the XP system has no trusted issuer — it is purely self-attestation.

**Correct implementation** would replace:
```
require(signer == msgData.account, "invalid signature");
```
with:
```
require(signer == trustedBackend, "invalid signature");
```
where `trustedBackend` is a protocol-controlled key that issues signed XP certificates off-chain.

---

### Events

| Event | Arguments | Trigger |
|---|---|---|
| `Claimed(account, xp)` | Account and XP at claim time | `claim` |
| `Reset(account)` | Account whose claim was reset | `reset` |
| `XpThresholdUpdated(newThreshold)` | New threshold value | `setXpThreshold` |

---

### Design Intent

Reward protocol participants who have accumulated XP (experience points in off-chain Vaultfire engagement) with a transferable loyalty token. EIP-712 structured data signing provides a clean user experience (compatible with MetaMask's `eth_signTypedData`).

### Why It Didn't Make Production

The core security model is broken: users self-sign their own XP claims with any value they choose. The contract does not enforce any trusted issuer. Any address can mint the loyalty token by signing a message with `xp = type(uint256).max`. This would need to be redesigned with a backend signing key before deployment.

---

---

# 33. HealthCommonsBonds.sol

**Path:** `theloopbreaker-site/contracts/deprecated/HealthCommonsBonds.sol`
**Lines:** 436
**Inherits:** `ReentrancyGuard` + `MissionEnforcement` (standalone V1)

## What It Was Supposed to Do

V1 of the health commons bond. A company stakes ETH against its commitment to reduce pollution and improve community health outcomes. The contract tracks two separate data streams — `PollutionMetrics` (air/water/food quality) and `HealthOutcomes` (respiratory, cancer, chronic disease, life expectancy, community health scores) — submitted by the company and attested by community members. Bond value is tied to both improvement trends. If pollution rises or health declines, the company's bond is penalised.

## Why It Was Likely Deprecated

1. **Uint256 underflow risk in `pollutionReductionScore` and `healthImprovementScore`** — line 256 (and analogous health line): `return improvement > -4000 ? uint256(50 + improvement / 80) : 0`. When `improvement` is a negative `int256` in the range `[-4000, -1000)`, the expression `50 + improvement/80` can be negative. Casting a negative `int256` to `uint256` wraps to a very large number, causing overflow. For example, `improvement = -2000`: `50 + (-2000/80) = 50 - 25 = 25` — that is fine. But `improvement = -3999`: `50 + (-3999/80) = 50 - 49 = 1` — also fine. Wait — let us check boundary: `improvement = -4000` is caught by the `> -4000` guard and returns 0. At `improvement = -3999`: `50 + (-3999/80) = 50 - 49 = 1`. At `improvement = -1000` (boundary of stable range): `50 + (-1000/80) = 50 - 12 = 38`. The formula is actually safe within the range `(-4000, -1000)` because integer division rounds toward zero in Solidity. The real risk is if Solidity ever computes `50 + negative_int` as negative before the cast — but since `int256` subtraction here cannot underflow to below 0 in the range -4000 to 0, the cast risk was overstated. However, the code is still confusing and relies on implicit range assumptions that are not documented.
2. **Divisor is 1 000 000** — V2 changes to 100 000 000 (×100), dramatically reducing output values. V1's divisor produces bond values orders of magnitude larger than stake at mid-range inputs.
3. **No input validation** — scores are accepted without range checks (e.g., `airQualityScore = 999999` is accepted).
4. **No `whenNotPaused`** — no circuit breaker.
5. **No timelock on distribution**.
6. **No yield pool** — `distributeBond` uses `.transfer()` directly from contract balance.
7. **Community share has no direct transfer recipient** — `communityShare` is recorded but no per-capita transfer executes (funds remain in contract after company share is transferred).

---

## Full Source with Line Numbers

```
L1    // SPDX-License-Identifier: MIT
L2    pragma solidity ^0.8.25;
L3    
L4    import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
L5    import "../MissionEnforcement.sol";
```

```
L17   contract HealthCommonsBonds is ReentrancyGuard {
```

Standalone, no `BaseYieldPoolBond`.

---

### Structs

```
L69–L77   Bond { bondId, company, affectedRegion, stakeAmount, createdAt, active }
L79–L86   PollutionMetrics { timestamp, airQualityScore, waterPurityScore, foodSafetyScore }
L88–L96   HealthOutcomes { timestamp, respiratoryHealthScore, cancerHealthScore, chronicDiseaseScore, lifeExpectancyScore, communityHealthScore, affectedPopulation }
L100–L106 CommunityAttestation { attestor, timestamp, confirmsPollutionReduction, confirmsHealthImprovement, notes }
L109–L115 Distribution { timestamp, totalAmount, communityShare, companyShare, perCapitaAmount, reason }
```

---

### State Variables

| Variable | Type | Description |
|---|---|---|
| `nextBondId` | `uint256` | Auto-increment |
| `bonds` | `mapping(uint256 → Bond)` | Bond storage |
| `bondPollutionData` | `mapping(uint256 → PollutionMetrics[])` | Pollution reading history |
| `bondHealthData` | `mapping(uint256 → HealthOutcomes[])` | Health outcome history |
| `bondAttestations` | `mapping(uint256 → CommunityAttestation[])` | Community attestations |
| `bondDistributions` | `mapping(uint256 → Distribution[])` | Distribution history |

No threshold constants are declared (unlike V2 which defines them explicitly). Threshold values are hardcoded inline in `shouldActivatePoisoningPenalty`: `pollution < 80 || health < 80 || community < 70`.

---

### `pollutionReductionScore(bondId) → uint256`

```
L230–L258 (approximate line range)

Require >= 2 pollution data entries.

initialAvg = (initial.air + initial.water + initial.food) / 3
latestAvg  = (latest.air + latest.water + latest.food) / 3
improvement = int256(latestAvg) - int256(initialAvg)

if improvement >= 3000:  return 150 + uint256((improvement - 3000) / 100)
if improvement >= 1000:  return 100 + uint256((improvement - 1000) / 40)
if improvement >= -1000: return 100
return improvement > -4000 ? uint256(50 + improvement / 80) : 0
```

**The cast analysis (line 256):**

The expression is: `uint256(50 + improvement / 80)`

- `improvement` is `int256`, range assumed `(-4000, -1000)` by this branch.
- `improvement / 80` is `int256` division (rounds toward zero): range `(-50, -12)`.
- `50 + improvement/80` is `int256` in range `(0, 38)` — always non-negative within the valid range.
- Therefore `uint256(...)` cast is safe within the intended range.

However: if `improvement` could somehow be `<= -4001` and the `improvement > -4000` guard is incorrect, the expression `50 + improvement/80` could be negative (e.g., `improvement = -10000`: `50 + (-125) = -75`), and `uint256(-75)` wraps to `2^256 - 75` — a catastrophic overflow. The guard prevents this in normal operation but relies on correct `int256` comparison semantics. The code is fragile — a well-designed implementation would use an explicit `int256` cast for the intermediate computation.

**The deeper issue:** Unlike V2 which adds this comment and uses the same pattern, V1 has no NatSpec explaining the invariants, making the safety argument hard to audit.

---

### `healthImprovementScore(bondId) → uint256`

Same piecewise formula applied to the five-dimensional health outcome average:

```
if improvement >= 2000:  return 150 + uint256((improvement - 2000) / 60)
if improvement >= 500:   return 100 + uint256((improvement - 500) / 30)
if improvement >= -500:  return 100
return improvement > -4000 ? uint256(50 + improvement / 80) : 0
```

Different threshold breakpoints than the pollution version (2000/500 vs 3000/1000), presumably because health scores change more slowly than pollution readings.

---

### `calculateBondValue(bondId) → uint256`

```
pollution  = pollutionReductionScore(bondId)    // 0–200+
health     = healthImprovementScore(bondId)     // 0–200+
community  = communityVerificationMultiplier(bondId)  // 50–150
time       = timeMultiplier(bondId)             // 100–200

return (stake × pollution × health × community × time) / 1_000_000
```

**Divisor calibration — V1 vs V2:**

V1 divisor: `1_000_000` (1e6)  
V2 divisor: `100_000_000` (1e8) — ×100 larger

At representative mid-values (pollution=100, health=100, community=100, time=100, stake=0.01 ETH=1e16):

V1: `(1e16 × 100 × 100 × 100 × 100) / 1e6 = 1e24 / 1e6 = 1e18 wei = 1 ETH`

That is a **100× return on a 0.01 ETH stake at baseline (no improvement, no degradation, year 0)**. The formula is massively miscalibrated. V2's ×100 correction brings this to 0.01 ETH — par value — which is the correct baseline.

---

### `distributeBond(bondId)` — community share is stuck

```
L355–L416

Require health data with affectedPopulation > 0.

if appreciation > 0:
    if penalty:
        communityShare = 100%
        companyShare   = 0%
    else:
        communityShare = 70%
        companyShare   = 30%

if appreciation < 0:
    communityShare = uint256(-appreciation)  // full depreciation to community

perCapitaAmount = communityShare / population  // stored in Distribution

payable(bond.company).transfer(companyShare)   ← deprecated

// communityShare is NEVER transferred — funds remain in the contract
```

The `perCapitaAmount` is computed and stored in the Distribution struct, but no loop distributes community shares to individual community members. There is no community registry. This is the same gap as PurchasingPowerBonds V1 — the per-capita calculation exists purely as a record-keeping artefact.

---

### `shouldActivatePoisoningPenalty(bondId) → bool`

```
pollution < 80 || health < 80 || community < 70
```

Any one of three conditions triggers the full penalty. The thresholds (80, 80, 70) are hardcoded inline — no named constants, making them invisible to external auditors scanning state variables.

---

### `communityVerificationMultiplier(bondId) → uint256`

```
if 0 attestations:      return 50     // penalty for no verification
if 0 recent (<180d):    return 70

avgRate = average of (pollutionConfirmations/count, healthConfirmations/count)

if avgRate >= 80: return 150
if avgRate >= 50: return 100
return 50 + avgRate / 2
```

V1 default of 50 (instead of V2's 100) means unverified bonds immediately suffer a 50 % multiplier reduction on bond value. This is a stricter penalty for unverified bonds than V2 applies.

---

### Events

| Event | Trigger |
|---|---|
| `BondCreated(bondId, company, affectedRegion)` | `createBond` |
| `PollutionDataSubmitted(bondId, timestamp)` | `submitPollutionData` |
| `HealthDataSubmitted(bondId, timestamp)` | `submitHealthData` |
| `CommunityAttestationAdded(bondId, attestor)` | `addCommunityAttestation` |
| `BondDistributed(bondId, communityShare, companyShare)` | `distributeBond` |

---

### Design Intent

Make environmental remediation profitable. Companies that reduce the pollution they cause and improve community health outcomes earn bond appreciation. Community members attest to real-world changes, providing social proof. Per-capita distribution to affected residents creates a direct compensation mechanism for historical harm.

### Why It Didn't Make Production

Three compounding issues eliminated this version: (1) community share is computed but never transferred — affected residents cannot claim funds; (2) divisor miscalibration produces absurd returns (100× at baseline); (3) `.transfer()` deprecated. V2 corrects all three: community share goes to a yield pool for distribution, divisor is ×100 larger, and `.call{}` replaces `.transfer()`. The cast fragility in `pollutionReductionScore` also migrated to V2, making it a known technical debt item inherited by the successor.

---

---

# Cross-Reference Index

## Contracts by Pattern

### V1 → V2 Pairs

| V1 | V2 | Key Changes in V2 |
|---|---|---|
| VerdantAnchorBonds | VerdantAnchorBondsV2 | BaseYieldPoolBond, `.call{}`, timelock |
| HealthCommonsBonds | HealthCommonsBondsV2 | Divisor ×100, BaseYieldPoolBond, `.call{}` |
| LaborDignityBonds | LaborDignityBondsV2 | Dignity floor, BaseYieldPoolBond, off-by-one bug introduced |
| EscapeVelocityBonds | EscapeVelocityBondsV2 | Simplified formula, BaseYieldPoolBond |
| CommonGroundBonds | CommonGroundBondsV2 | Simplified formula, BaseYieldPoolBond |
| PurchasingPowerBonds | PurchasingPowerBondsV2 | Timelock, BaseYieldPoolBond, `whenNotPaused` |
| BuilderBeliefBonds | BuilderBeliefBondsV2 | Divisor halved, BaseYieldPoolBond, verification dropped |
| VerdantAnchorBonds | VerdantAnchorBondsV2 | Greenwashing penalty inversion corrected in V2 |

### Infrastructure Contracts

| Contract | Role |
|---|---|
| VaultfireDAO | Governance — guardian token + Governor stack |
| RewardStream | ETH-based reward distribution (admin + governor roles) |
| VaultfireRewardStream | Token-based linear vesting stream (ERC20) |
| RewardMultiplier | Belief + loyalty score → basis-point multiplier |
| SwapGate | Token swap with KYC bypass for trusted IDs |
| YieldPoolHealthMonitor | Off-bond monitoring of yield pool reserves |
| VaultfireBugBounty | On-chain bug report registry with ETH bounties |
| VaultfireLoyalty | ERC20 loyalty token with XP-threshold claim |

### Provenance / Identity Contracts

| Contract | Role |
|---|---|
| GhostkeyAttribution | Immutable contributor metadata + royalty routing |
| CovenantFlame | Lightweight provenance anchor for Chapter 3 deployments |
| ContributorUnlockKey | ERC721 access token with optional hook callback |
| GhostkeyLoyaltyLock | ETH lock with linearly scaling loyalty multiplier |
| FreedomVow | One-time guardian vow ritual on top of BeliefOracle |

### Sports Integrity Contracts

| Contract | Role |
|---|---|
| CompetitiveIntegrityBond | Team-level season bond |
| TeamworkIntegrityBond | Player-level season bond |
| FanBeliefBond | Fan-staked integrity bond on players/teams |
| FanVerificationSybilResistance | Sybil-resistant fan verification layer |

---

## Known Bugs and Issues by Contract

| Contract | Issue | Severity |
|---|---|---|
| LaborDignityBondsV2 | Off-by-one in `workerVerifiedScore` loop | High — silently uses wrong attestation index |
| VaultfireBugBounty | `profile.invalidSubmissions--` underflow | High — reverts on first invalid review of any researcher |
| VaultfireBugBounty | `MINIMUM_POOL_BALANCE` check before deduction | Medium — floor check does not account for award |
| VaultfireLoyalty | Self-signed EIP-712 — users sign their own XP | Critical — entire auth model is bypassed |
| CompetitiveIntegrityBond | `_calculateFanConsensusScore` always returns 5 000 | High — stub, fan scoring not implemented |
| FanVerificationSybilResistance | `this.getFanTier()` unnecessary external call | Low — gas waste, bad practice |
| HealthCommonsBonds (V1) | `distributeBond` never transfers community share | High — community funds locked in contract |
| PurchasingPowerBonds (V1) | `distributeBond` never transfers worker share | High — workers never receive funds |
| AIAccountabilityBonds | Human share has no recipient — locked | High — same gap |
| All V1 standalones | `payable().transfer()` deprecated | Medium — 2300 gas limit, breaks smart contract recipients |
| BuilderBeliefBonds (both) | Transacting penalty pays misbehaving party | Medium — inversion of intent |
| SwapGate | `swapToSOL` does not execute cross-chain transfer | High — emits event only, no actual SOL movement |
| GhostkeyAttribution | `.transfer()` in `receive()` and `payRoyalty()` | Low — same gas limit issue |

---

## Deprecation Reasons by Category

### Replaced by V2 with BaseYieldPoolBond

VerdantAnchorBonds, HealthCommonsBonds, LaborDignityBonds, EscapeVelocityBonds, CommonGroundBonds, PurchasingPowerBonds, BuilderBeliefBonds — all V1 versions superseded by V2 variants that inherit `BaseYieldPoolBond`, use `_useYieldPool()` for distribution, add `DISTRIBUTION_TIMELOCK`, replace `.transfer()` with `.call{}`, and add `whenNotPaused`.

### Design Concept Unimplemented

CompetitiveIntegrityBond (fan consensus stub), FanVerificationSybilResistance (no bond integration), SwapGate (no cross-chain execution for SOL), AIAccountabilityBonds (human share never transferred), AIPartnershipBonds (partnership fund locked, AI identity unenforced).

### Critical Security Issues

VaultfireLoyalty (self-signed XP), VaultfireBugBounty (underflow on invalid review, pool floor miscalculation).

### Infrastructure Replaced / Evolved

RewardStream → absorbed into BaseYieldPoolBond pattern. VaultfireRewardStream → separate ERC20 streaming path. RewardMultiplier → multiplier logic moved closer to bond contracts. GhostkeyLoyaltyLock → standalone loyalty primitive superseded by more integrated approaches.

---

*End of Vaultfire Codex — Batch 8: Deprecated Archive*
