> For the complete documentation index, see [llms.txt](https://myorg-41.gitbook.io/myorg-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://myorg-41.gitbook.io/myorg-docs/avox/documentation.md).

# DOCUMENTATION

## Next-Generation Web3 Trading Card Game (TCG) Powered by Live Market Volatility & Verifiable On-Chain Mechanics

> **Network:** Robinhood \
> **Web3 Wallet Stack:** Reown AppKit (`@reown/appkit` + `@reown/appkit-adapter-wagmi`) \
> **Smart Contract Framework:** Solidity 0.8.24 / Foundry / Viem \
> **Frontend Architecture:** Next.js 16 (App Router) + TypeScript + Tailwind CSS + Web Audio Engine

### 1. Executive Summary

Avox is an on-chain competitive trading card game that bridges decentralized finance (DeFi) market telemetry with tactical turn-based battle gameplay.

In traditional TCGs, card attributes remain static post-mint. Avox introduces Live Volatility Scaling: each card represents a real-world cryptocurrency (e.g., BTC, ETH, SOL, DOGE, AVAX, LINK, BNB, PEPE, NEAR, SUI). Mid-battle, the card's base attack, defense, and speed values dynamically scale in real-time based on live 5-minute and 24-hour price deltas streamed from live market feeds. A rally in the underlying asset supercharges a card's damage output, while market downturns weaken enemy barriers.

Every asset within the Avox ecosystem is verifiable on Robinhood Testnet:

* Cards are standard ERC-721 tokens with immutable base stats minted on-chain.
* Pack Openings execute directly against a Chainlink VRF-compatible smart contract, with verifiable seeds and cryptographic proof generation.
* Secondary Trading occurs through a non-custodial atomic marketplace contract.
* Prize Pools are transparently funded: 20% of every pack purchase and 2.5% of secondary market trades route automatically into the seasonal prize pool contract.

### 2. High-Level Architecture

The Avox ecosystem consists of four synchronized architectural tiers:

```
flowchart TB
    subgraph Client ["Frontend & Presentation Layer (Next.js 16 + Tailwind)"]
        UI["Cyberpunk HUD & Colosseum UI"]
        Audio["Procedural Web Audio Synthesizer"]
        Store["State Stores (userStore, walletStore, marketplaceStore)"]
        Combat["Battle Engine (Elemental Mechanics & Status Conditions)"]
    end

    subgraph Web3 ["Web3 & Connectivity Layer"]
        AppKit["Reown AppKit (@reown/appkit + Wagmi)"]
        ViemClient["Viem Public & Wallet Clients"]
        RPC["Multi-Tier Fallback RPCs (Tenderly, 1RPC, PublicNode)"]
    end

    subgraph Blockchain ["Robinhood Testnet"]
        CardContract["AvoxCard.sol\n(ERC-721 NFT)"]
        PackContract["AvoxPackVRF.sol\n(Verifiable Pack Minting)"]
        MarketContract["AvoxMarketplace.sol\n(Non-Custodial Trading)"]
        PoolContract["AvoxPrizePool.sol\n(Seasonal Prize Pool)"]
    end

    subgraph Oracle ["Live Market Telemetry & Oracles"]
        PriceStream["WebSocket Price Stream (Binance / Pyth / CoinGecko)"]
        StatEngine["Stat Modifier Engine (Clamped Volatility Formula)"]
    end

    PriceStream --> StatEngine
    StatEngine --> Combat
    Client <--> AppKit
    AppKit --> ViemClient
    ViemClient --> RPC
    RPC <--> Blockchain
    PackContract -- "20% Cut" --> PoolContract
    MarketContract -- "2.5% Fee" --> PoolContract
    PackContract -- "Mints NFTs" --> CardContract
    MarketContract -- "Escrows & Transfers" --> CardContract
```

### 3. Smart Contract System & On-Chain Deployments

All 4 smart contracts are deployed and verified on Robinhood Testnet:

#### AvoxCard.sol (ERC-721)

The core NFT contract governing all collectible battle cards. Implements ERC-721 with immutable base attribute storage.

**Storage Structure:**

```solidity
struct CardMetadata {
    string assetSymbol; // e.g. "BTC", "ETH", "SOL", "DOGE"
    Rarity rarity;       // Common (0), Rare (1), Epic (2), Legendary (3)
    FoilType foilType;   // Standard (0), Holo (1), GoldFoil (2)
    uint16 baseAtk;      // 50 - 180
    uint16 baseDef;      // 50 - 180
    uint16 baseSpd;      // 50 - 180
    uint64 mintedAt;     // Timestamp
}
```

**Access Control**

* `mintCard(...)` is restricted to authorized minters (`onlyMinter`), granting the AvoxPackVRF contract exclusive minting permissions.
* `setPackContract(...)` and `setMarketplaceContract(...)` allow the owner to wire dependent game contracts.

**Events**

```solidity
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)
event CardMinted(uint256 indexed tokenId, address indexed to, string assetSymbol, Rarity rarity, FoilType foilType)
```

#### AvoxPackVRF.sol (Pack Minting & VRF)

Governs booster pack purchases, verifiable randomness, and card minting.

**Pack Configurations**

* Starter: 0.005 ether, 3 cards, standard odds (3% Legendary, 12% Epic, 25% Rare, 8% Holo).
* Alpha: 0.02 ether, 5 cards, enhanced odds (6% Legendary, 20% Epic, 35% Rare, 18% Holo).
* Whale: 0.05 ether, 5 cards, elite odds (15% Legendary, 35% Epic, 45% Rare, 40% Holo).

**Core Functions**

* `buyPack(PackTier tier) external payable returns (uint256)`:
  * Validates sufficient `msg.value` matching the tier price.
  * Routes 20% of `msg.value` directly to `AvoxPrizePool.recordInflow`.
  * Generates unique `requestId` and records the purchase.
  * Executes `_fulfillPack(...)` to roll on-chain randomness, determine rarities, foils, and asset symbols, and calls `cardContract.mintCard(...)` for each card.
* `getRequest(uint256 requestId) external view returns (PackRequest memory)`: Enables off-chain proof inspection.

**Events**

```solidity
event PackPurchased(uint256 indexed requestId, address indexed buyer, PackTier tier, uint256 price)
event PackFulfilled(uint256 indexed requestId, address indexed buyer, uint256 randomSeed, uint256[] tokenIds)
```

#### AvoxMarketplace.sol (Secondary Market)

Facilitates peer-to-peer trading of minted ERC-721 cards without intermediary custody until listing settlement.

**Trading Mechanics**

* `listCard(uint256 tokenId, uint256 price)`: Validates ownership and ERC-721 allowance, then marks the listing active.
* `buyCard(uint256 tokenId) external payable`:
  * Validates payment matching `listing.price`.
  * Calculates protocol fee (2.5%).
  * Transfers 2.5% to `prizePool.recordInflow`.
  * Sends 97.5% net proceeds to the seller.
  * Transfers ERC-721 token from seller to buyer.
* `cancelListing(uint256 tokenId)`: Allows the seller to remove an active listing.

**Events**

```solidity
event ItemListed(uint256 indexed tokenId, address indexed seller, uint256 price, uint64 timestamp)
event ItemSold(uint256 indexed tokenId, address indexed seller, address indexed buyer, uint256 price, uint256 fee)
event ListingCancelled(uint256 indexed tokenId, address indexed seller)
```

#### AvoxPrizePool.sol (Community Inflows)

A transparent community treasury contract that pools player inflows and distributes seasonal competitive rewards.

**Inflow Sources**

* Automatic 20% cut from every booster pack purchased via AvoxPackVRF.
* Automatic 2.5% trading fee from every secondary market sale via AvoxMarketplace.
* Direct community donations via fallback `receive()` function.

**Core Functions**

* `recordInflow(string calldata source) external payable`: Only callable by authorized pack or marketplace contracts.
* `getRecentInflows(uint256 limit) external view returns (InflowRecord[] memory)`: Returns live chronological inflow telemetry.

**Events**

```solidity
event InflowReceived(address indexed contributor, uint256 amount, string source, uint256 season)
event SeasonRolled(uint256 oldSeason, uint256 newSeason, uint256 distributedAmount)
event PrizeDistributed(uint256 indexed season, address indexed winner, uint256 rank, uint256 amount)
```

**On-Chain Permissions & Wiring**

Smart contract permissions are configured via `contracts/deploy.ts`:

1. Grant pack minting permissions — `card.setPackContract(packAddress)`: Grants AvoxPackVRF exclusive rights to mint new cards.
2. Authorize marketplace transfers — `card.setMarketplaceContract(marketplaceAddress)`: Authorizes AvoxMarketplace for atomic transfers.
3. Authorize prize-pool inflows — `prizePool.setAuthorizedContracts(packAddress, marketplaceAddress)`: Authorizes both contracts to call `recordInflow`.

### 4. Live Volatility Oracle & Stat Scaling Engine

Avox integrates real-time crypto price movement directly into game statistics.

**Mathematical Formula**

The live in-match stat modifier is determined by a blended rolling price delta. The raw modifier applies a sensitivity factor ($k = 0.02$).

**Trend Clamping & Sensitivity Curves**

To maintain competitive game balance and prevent runaway stats while rewarding market volatility:

* Maximum Rally Buff: +60% (1.60x)
* Maximum Dump Debuff: -40% (0.60x)
* Pump Threshold: Δ\_effective ≥ +3.0% (Triggers emerald glow, neon border aura)
* Dump Threshold: Δ\_effective ≤ -3.0% (Triggers crimson debuff aura)

**Data Pipeline & WebSocket Feeds**

Price streams are managed in `src/lib/market/priceFeed.ts`:

* Primary: Direct Binance / Pyth real-time WebSocket connection streaming 24h ticker updates.
* Failover: Polling REST endpoints against CoinGecko and public crypto tickers.
* Local Fallback Simulation: If offline, smooth brownian motion generator sustains continuous match play.

### 5. Combat Engine & Elemental Battle System

Combat is a fast-paced 3v3 arena battle designed to resolve in 4–7 high-intensity rounds (under 90 seconds).

**Pacing & Battle Attributes**

* Card Max HP yields \~170 to 215 HP per card, eliminating slow HP chip battles.
* Market Strike Damage averages 100–160 DMG; critical strikes roll 1.5x to 2.0x.

**Energy / Mana Economy**

* Starting Energy: 70 MP (Allows immediate turn-1 or turn-2 special moves).
* Energy per Market Strike: +20 MP.
* Skill Cost: 25–40 MP.

**Pokémon-Style Elemental Status Effects**

Four status effects are mapped across the roster.

**Procedural Web Audio Engine**

Sound effects are synthesized dynamically using the browser's native Web Audio API in `src/lib/audio/soundEngine.ts` with zero external MP3/WAV assets:

* `sound.playFreeze()`: Dual-oscillator FM bell with crystal high-pass reverberation.
* `sound.playBurn()`: Band-pass filtered white noise burst with rising pitch envelope.
* `sound.playShock()`: Rapid square-wave frequency modulation simulating an electric arc.
* `sound.playPoison()`: Low-frequency sizzling bubbling noise synthesizer.
* `sound.playStrike()`, `sound.playPackTear()`, `sound.playLegendaryReveal()`: Custom spatial audio cues.

### 6. Pack Economy, Rarity & Odds Matrix

Card booster packs mint verifiable NFTs directly to the user's Robinhood Testnet address.

**Randomness Commitment & Proof Verification**

Each pack purchase produces a verifiable `VRFProofData` payload stored in memory and displayed in the `VRFVerifyModal`:

* `requestId`: Unique on-chain identifier.
* `commitHash`: Robinhood Testnet transaction hash.
* `randomSeedHex`: 256-bit cryptographic seed.
* `rolls`: Per-card deterministic derivation showing raw sub-seeds, threshold comparison, and final attributes.

### 7. Secondary Marketplace & Escrow Mechanics

The secondary marketplace operates with non-custodial listings:

**Listing Creation**

1. The user selects an on-chain minted card from their collection.
2. User signs an ERC-721 `approve(marketplaceAddress, tokenId)` transaction.
3. User signs `listCard(tokenId, price)` specifying the listing price in Robinhood testnet ETH.

**Purchase Settlement**

1. The buyer calls `buyCard(tokenId)` sending the exact amount in Robinhood testnet ETH.
2. The contract verifies the listing is active.
3. 2.5% protocol fee is routed directly to AvoxPrizePool.
4. 97.5% net proceeds are transferred to the seller.
5. The NFT is transferred to the buyer's wallet.
6. Both user collections update in real time.

### 8. Web3 Connectivity & Reown AppKit Integration

Avox uses Reown AppKit (`@reown/appkit` + `@reown/appkit-adapter-wagmi`) to provide non-custodial wallet connectivity.

**Multi-Chain Handling & Network Switching**

To prevent errors when users connect wallets configured to Ethereum Mainnet or L2s:

* Wagmi Config (`wagmiConfig.ts`): Configured with multi-chain awareness, allowing Wagmi to recognize any initial wallet network without throwing `ChainNotConfiguredError`.
* AppKit Provider (`AppKitProvider.tsx`): `allowUnsupportedChain: true` and `defaultNetwork: robinhoodTestnet` ensure users are never trapped in uncloseable network loops.
* Active Network Verification: Every on-chain operation checks `ensureRobinhoodNetwork()`, triggering an automatic network switch request if the user is on another chain.

**3-Tier Robinhood Testnet Balance Fetching**

In `walletStore.ts` and `Navbar.tsx`, balances are fetched across three fallback layers:

1. **Wagmi `useBalance` Hook** — Reactive hook targeting the Robinhood Testnet chain ID with automatic Viem `formatEther` parsing.
2. **EIP-1193 Direct Call** — `window.ethereum.request({ method: 'eth_getBalance', params: [address, 'latest'] })`.
3. **Public Client Fallback** — Viem `publicClient.getBalance({ address })`.

**RPC Fallback Architecture**

In `client.ts`, public RPC transport uses high-availability, zero-CORS endpoints with automatic failover across the standard Robinhood Testnet public gateways (Tenderly, 1RPC, PublicNode equivalents).

### 9. Developer Guide & Local Setup

**Prerequisites**

* Node.js: v20.x or v22.x
* Package Manager: npm or pnpm
* Web3 Wallet: MetaMask, Coinbase Wallet, or Rabby with testnet funds on Robinhood Testnet.

**Installation & Environment Setup**

```
git clone <repo>
cd avox
npm install
```

Create `.env.local` in the project root:

```
NEXT_PUBLIC_REOWN_PROJECT_ID=912198beeaebbbd8ecf6655c63be1884
NEXT_PUBLIC_DEFAULT_CHAIN_ID=<robinhood-testnet-chain-id>
NEXT_PUBLIC_CARD_CONTRACT=0x209139a7c49a2ea834daf5ff496008ea02b2fbba
NEXT_PUBLIC_PRIZEPOOL_CONTRACT=0xdb2db0f2bd83cfb8d5f1db480caf661978624f56
NEXT_PUBLIC_PACK_CONTRACT=0x1dc2656a699c1bf6d827c555c994f5fd89e1ff75
NEXT_PUBLIC_MARKETPLACE_CONTRACT=0xb20655cb8160350ece1897a86ebbf832b4c26851
```

Start Development Server:

```
npx next dev --webpack
```

Open <http://localhost:3000> in your browser.

**Compilation, Typechecking & Testing**

TypeScript Type Verification:

```
npx tsc --noEmit
```

Run Core Game Engine Test Suite:

```
npm test
```

Executes all 12 validation checks: stat modifier clamping, pack configurations, 20% prize pool cuts, battle creation, elemental status resolutions, and bot matchmaking.

**Smart Contract Deployment Script**

To deploy new contract iterations to Robinhood Testnet or other target testnets:

```
# Provide deployer private key in contracts/.env
npx tsx contracts/deploy.ts
```

The script compiles artifacts, deploys the 4 contracts, configures permissions, and synchronizes `.env.local` and `contracts.ts` automatically.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://myorg-41.gitbook.io/myorg-docs/avox/documentation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
