Warriors AI-rena
WarriorsAI-rena is a groundbreaking blockchain-based battle arena
Problem Statement
WarriorsAI-rena: Complete Technical Documentation🏛️⚔️🤖Table of ContentsPCATRBPSCEWCFTProject OverviewWhat WarriorsAI-rena Actually IsWarriorsAI-renais the world's firstAI-orchestrated blockchain battle arenawhere real artificial intelligence agents make strategic combat decisions while players bet, influence, and participate in epic warrior battles. Think of it as a fusion of:Chess(strategic depth)Pokémon(creature collection and battles)DeFi(financial mechanics)AI Research(autonomous decision-making)Esports(competitive gaming)But it'sentirely on blockchainwithreal AI agentscontrolling the action.Key InnovationsReal AI Decision-Making: Not scripted NPCs, but actual AI agents analyzing and decidingSustainable Token Economics: 1:1 FLOW backing prevents death spiralsPlayer Agency: Direct influence on battle outcomes through strategic mechanicsCross-Chain Architecture: Flow Testnet + 0G Network integrationCryptographic Verification: All AI decisions are signed and verified on-chainCore Gaming ExperienceThe Player Journey - Step by StepConnect Your Walletto Flow TestnetMint Crown Tokens (CRwN)with a 1:1 FLOW backing ratioAcquire Warrior NFTs- each with unique traits and abilitiesEnter an Arenabased on your warrior's rank (Unranked → Platinum)Place Strategic Betson warriors in upcoming battlesInfluence the Battleby boosting your favored warrior's powerWatch AI Agentsmake real-time combat decisionsCollect Rewardsbased on battle outcomes and your participationWhat Makes Each Battle UniqueEvery single battle is a5-round strategic combatwhere:AI agents analyzewarrior traits in real-timePlayers can influenceoutcomes mid-battleNo two battles are identicaldue to AI decision-makingCryptographic signaturesensure AI decisions are legitimateComplex damage calculationsbased on multiple factorsBattle Flow SequenceAI Revolution in GamingHow the AI Actually WorksThis isn't fake AI or scripted behavior. Here's what's happening:0G Network hosts real AI agentsthat analyze warrior dataAI examines warrior traits: Strength, Wit, Charisma, Defense, LuckAI considers battle context: Current round, damage taken, opponent statusAI selects optimal movesfrom 5 combat optionsAI decisions are cryptographically signedand verified on-chainBattle outcomes are calculatedusing complex formulasThe 5 Combat Moves (AI-Selected)enum PlayerMoves { STRIKE, // Pure strength attack - high damage potential TAUNT, // Psychological warfare using Charisma + Wit DODGE, // Defensive evasion based on Defense stat SPECIAL, // Ultimate move combining Personality + Strength RECOVER // Healing move using Defense + Charisma }Each move has different success rates and effects based on:Warrior's traitsOpponent's traitsLuck factorCurrent battle stateAI strategic analysisAI Decision Processinterface AIDecisionProcess { analyzeWarriorTraits(warrior1: Warrior, warrior2: Warrior): TraitAnalysis; evaluateBattleContext(battleState: BattleState): ContextAnalysis; calculateOptimalMove(analysis: TraitAnalysis, context: ContextAnalysis): PlayerMoves; signDecision(move: PlayerMoves): CryptographicSignature; }Technical ArchitectureLayer 1: Blockchain Foundation (Flow Testnet)Flow Testnetserves as the primary blockchain because:EVM Compatible: Works with existing Ethereum toolsLow Gas Fees: Affordable for gaming transactionsHigh Throughput: Can handle rapid battle transactionsDeveloper Friendly: Excellent tooling and documentationSmart Contracts Deployed:Arena.sol: The battle engine (1,029 lines of complex logic)WarriorsNFT.sol: Character system (535 lines)CrownToken.sol: Economic engine (118 lines)ArenaFactory.sol: Arena creation system (302 lines)Layer 2: AI & Storage (0G Network)0G Network provides:Decentralized AI Hosting: AI agents run on distributed infrastructureStorage Layer: Warrior metadata, battle history, encrypted assetsHigh-Performance Inference: Real-time AI decision makingCryptographic Verification: All AI outputs are signed and verifiableLayer 3: Frontend Experience (Next.js 15)Modern Web3 Interface:Real-time Battle Visualization: Watch AI decisions unfoldWallet Integration: RainbowKit + Wagmi for seamless connectionResponsive Design: Works on desktop and mobileTypeScript: Type-safe development for reliabilityComplete Architecture DiagramRevolutionary EconomicsCrown Token (CRwN) - The BreakthroughMost gaming tokens fail because they have no real backing.CRwN is different:// Mint Function - 1:1 FLOW backing function mint(uint256 _amount) public payable { require(msg.value == _amount); // Must send FLOW equal to tokens _mint(msg.sender, _amount); } // Burn Function - Redeem FLOW function burn(uint256 _amount) public { _burn(msg.sender, _amount); payable(msg.sender).transfer(_amount); // Get FLOW back }This creates:Price Floor: CRwN can never go below 1 FLOWSustainable Economics: No death spiralsReal Utility: Tokens are spent in gameplay, not just tradedDeflationary Pressure: Influence/defluence burns tokensMulti-Tier Economy| Rank | Bet Amount | Influence Cost | Defluence Cost | Potential Rewards | |------|------------|----------------|----------------|-------------------| | Unranked | 1x | 1x | 1x | 1x | | Bronze | 2x | 2x | 2x | 2x | | Silver | 3x | 3x | 3x | 3x | | Gold | 4x | 4x | 4x | 4x | | Platinum | 5x | 5x | 5x | 5x |Higher ranks = higher stakes = higher rewardsToken Utility FlowBattle System Deep DiveBattle Initializationfunction initializeGame(uint256 _warriorOneId, uint256 _warriorTwoId) { // Verify warriors are same rank require(warriorsNFT.getWarriorRanking(_warriorOneId) == warriorsNFT.getWarriorRanking(_warriorTwoId), "Warriors must be same rank"); // Set up betting period (60 seconds minimum) bettingStartTime = block.timestamp; bettingEndTime = block.timestamp + BETTING_PERIOD; // Initialize battle state battleState = BattleState.BETTING; currentRound = 0; emit GameInitialized(_warriorOneId, _warriorTwoId); }The Betting Phase60 seconds minimumfor players to analyze and betFixed bet amountsprevent whale manipulationMultiple bets allowedwith multiplier systemMust have bets on both sidesor game is refundedfunction betOnWarriorOne(uint256 _multiplier) external { require(battleState == BattleState.BETTING, "Not in betting phase"); require(block.timestamp < bettingEndTime, "Betting period ended"); require(_multiplier > 0 && _multiplier <= MAX_MULTIPLIER, "Invalid multiplier"); uint256 betAmount = getBaseBetAmount() * _multiplier; require(crownToken.transferFrom(msg.sender, address(this), betAmount), "Transfer failed"); betsOnWarriorOne[msg.sender] += betAmount; totalBetsOnWarriorOne += betAmount; emit BetPlaced(msg.sender, 1, betAmount); }The Battle Roundsfunction battle( PlayerMoves _warriorOneMove, PlayerMoves _warriorTwoMove, bytes memory _aiSignature ) external onlyGameMaster { require(battleState == BattleState.ACTIVE, "Battle not active"); require(currentRound < MAX_ROUNDS, "Battle ended"); // Verify AI signature bytes32 dataHash = keccak256(abi.encodePacked(_warriorOneMove, _warriorTwoMove)); bytes32 ethSignedMessage = MessageHashUtils.toEthSignedMessageHash(dataHash); address recovered = ECDSA.recover(ethSignedMessage, _aiSignature); require(recovered == aiPublicKey, "Invalid AI signature"); // Execute battle logic (uint256 damageToTwo, uint256 damageToOne) = calculateDamage( _warriorOneMove, _warriorTwoMove, warriorOneId, warriorTwoId ); // Apply damage warriorOneHealth = warriorOneHealth > damageToOne ? warriorOneHealth - damageToOne : 0; warriorTwoHealth = warriorTwoHealth > damageToTwo ? warriorTwoHealth - damageToTwo : 0; currentRound++; emit RoundCompleted(currentRound, _warriorOneMove, _warriorTwoMove, damageToOne, damageToTwo); // Check for battle end if (warriorOneHealth == 0 || warriorTwoHealth == 0 || currentRound >= MAX_ROUNDS) { endBattle(); } }Damage Calculation Formulafunction calculateDamage( PlayerMoves _moveOne, PlayerMoves _moveTwo, uint256 _warriorOneId, uint256 _warriorTwoId ) internal view returns (uint256 damageToTwo, uint256 damageToOne) { // Get warrior traits (uint16 str1, uint16 wit1, uint16 cha1, uint16 def1, uint16 luck1) = warriorsNFT.getWarriorTraits(_warriorOneId); (uint16 str2, uint16 wit2, uint16 cha2, uint16 def2, uint16 luck2) = warriorsNFT.getWarriorTraits(_warriorTwoId); // Apply influence/defluence modifiers uint256 modifiedStr1 = applyInfluenceModifiers(str1, _warriorOneId); uint256 modifiedStr2 = applyInfluenceModifiers(str2, _warriorTwoId); // Calculate base damage based on moves damageToTwo = calculateMoveDamage(_moveOne, modifiedStr1, wit1, cha1, def2, luck1); damageToOne = calculateMoveDamage(_moveTwo, modifiedStr2, wit2, cha2, def1, luck2); // Apply random factors damageToTwo = applyRandomFactor(damageToTwo); damageToOne = applyRandomFactor(damageToOne); }Player Agency System1. Strategic BettingNot just gambling -informed investmentbased on:Warrior trait analysisBattle historyCurrent influence/defluence levelsAI behavioral patternsstruct BettingInfo { uint256 totalBetsOnWarriorOne; uint256 totalBetsOnWarriorTwo; mapping(address => uint256) betsOnWarriorOne; mapping(address => uint256) betsOnWarriorTwo; uint256 bettingStartTime; uint256 bettingEndTime; }2. Influence Systemfunction influenceWarriorOne() external { require(battleState == BattleState.ACTIVE, "Battle not active"); require(currentRound < MAX_ROUNDS, "Battle ended"); uint256 influenceCost = getInfluenceCost(); require(crownToken.transferFrom(msg.sender, address(this), influenceCost), "Transfer failed"); // Burn the tokens (deflationary mechanism) crownToken.burn(influenceCost); // Apply influence boost warriorOneInfluence += INFLUENCE_BOOST; playerInfluences[msg.sender]++; emit InfluenceApplied(msg.sender, 1, influenceCost); }3. Defluence Mechanicsfunction defluenceWarriorOne() external { require(battleState == BattleState.ACTIVE, "Battle not active"); require(currentRound < MAX_ROUNDS, "Battle ended"); require(!hasDefluenced[msg.sender], "Already defluenced this game"); uint256 defluenceCost = getDefluenceCost(); require(crownToken.transferFrom(msg.sender, address(this), defluenceCost), "Transfer failed"); // Burn the tokens (deflationary mechanism) crownToken.burn(defluenceCost); // Apply defluence debuff warriorOneDefluence += DEFLUENCE_DEBUFF; hasDefluenced[msg.sender] = true; emit DefluenceApplied(msg.sender, 1, defluenceCost); }4. Real-Time ParticipationWatch battles unfold liveSee AI decision-making processTrack influence effectsParticipate in community discussionsSecurity & FairnessAI Decision Verificationfunction verifyAISignature( PlayerMoves _moveOne, PlayerMoves _moveTwo, bytes memory _signature ) internal view returns (bool) { bytes32 dataHash = keccak256(abi.encodePacked(_moveOne, _moveTwo)); bytes32 ethSignedMessage = MessageHashUtils.toEthSignedMessageHash(dataHash); address recovered = ECDSA.recover(ethSignedMessage, _signature); return recovered == aiPublicKey; }Economic SafeguardsFixed bet amountseliminate manipulationTime-locked periodsprevent front-runningDefluence limitsensure balanceTransparent calculationson-chainTechnical Security// Reentrancy protection modifier nonReentrant() { require(!_reentrancyGuard, "Reentrant call"); _reentrancyGuard = true; _; _reentrancyGuard = false; } // Role-based access control modifier onlyGameMaster() { require(msg.sender == gameMaster, "Only game master"); _; } // Time-based constraints modifier onlyDuringBetting() { require(battleState == BattleState.BETTING, "Not in betting phase"); require(block.timestamp < bettingEndTime, "Betting period ended"); _; }Cross-Chain InnovationFlow Testnet + 0G Network IntegrationThis is genuinely innovative because:Flow handlesthe financial transactions and game state0G Network providesthe AI computation and storageSeamless integrationbetween chainsBest of both worlds- security + performanceThe Technical Bridge// AI agents on 0G Network make decisions const aiDecision = await 0gNetwork.getAIDecision(battleState); // Decisions are signed and verified const signature = await aiAgent.signDecision(aiDecision); // Executed on Flow blockchain await flowContract.executeBattle(moves, signature);Multi-Chain Architecturegraph LR A[Flow Testnet] --> D[Battle Contracts] B[0G Network] --> E[AI Agents] B --> F[Storage Layer] C[Ethereum] --> G[Future Expansion] D --> H[Unified Experience] E --> H F --> H G --> HEconomic SustainabilityTraditional Gaming Token Problems:No real utility beyond speculationInfinite supply leading to inflationNo price floor or backingDeath spirals when hype diesWarriorsAI-rena Solutions:Real utility: Tokens spent in gameplayDeflationary mechanics: Influence/defluence burns tokensPrice floor: 1:1 FLOW backingSustainable revenue: 5% of betting pools (future)Revenue Streams:Battle fees(5% of betting pools)Influence costs(token burns)Defluence costs(token burns)NFT marketplace feesArena creation feesEconomic Model Analysiscontract EconomicModel { // Revenue calculation function calculateRevenue(uint256 totalBets) public pure returns (uint256) { return totalBets * PROTOCOL_FEE / 100; // 5% fee } // Deflationary pressure function calculateTokenBurn(uint256 influences, uint256 defluences) public pure returns (uint256) { return (influences * INFLUENCE_COST) + (defluences * DEFLUENCE_COST); } // Sustainability metrics function calculateSustainabilityRatio() public view returns (uint256) { uint256 totalBurned = getTotalTokensBurned(); uint256 totalMinted = getTotalTokensMinted(); return totalBurned * 100 / totalMinted; // Percentage burned } }Why This Project Will Succeed1. Technical InnovationFirst real AI-blockchain gaming integrationProduction-ready codewith comprehensive testingScalable architecturesupporting millions of usersCross-chain compatibilityfrom day one2. Economic InnovationSustainable tokenomicssolving gaming token problemsReal utilitybeyond speculationDeflationary mechanicscreating scarcityRevenue sharingaligning stakeholders3. Gaming InnovationUnpredictable gameplaythrough AIStrategic depthbeyond simple mechanicsCommunity participationin battle outcomesProgressive character development4. Market TimingAI boomcreating mainstream interestBlockchain gamingreaching maturityCross-chain infrastructurenow viableGaming NFTsseeking real utilityCultural ImpactThis project is creating a new category of entertainment:For Gamers:Skill-based competitionwith financial stakesTrue ownershipof digital assetsCommunity governanceof game evolutionAI-powered experiencespreviously impossibleFor Developers:Blueprint for AI-blockchain integrationSustainable gaming economics modelCross-chain architecture patternsCommunity-driven developmentFor the Industry:Proof of conceptfor AI in gamingNew revenue modelsfor game developersPlayer empowermentthrough ownershipDecentralized gaming infrastructureFuture VisionPhase 1: Foundation(Current)Core battle system operationalAI agents making decisionsToken economics functioningCommunity growingPhase 2: ExpansionTournament systemsGuild mechanicsAdvanced AI strategiesMobile applicationsPhase 3: EcosystemThird-party arena creationAI marketplaceBreeding systemsEsports integrationPhase 4: RevolutionFull DAO governanceAI training by communityCross-game compatibilityIndustry standardTechnical SpecificationsSmart Contract DetailsArena.solLines of Code: 1,029Key Functions: 47Gas Optimization: AdvancedSecurity Features: ComprehensiveWarriorsNFT.solLines of Code: 535Trait System: 5 attributes (0-10000 precision)Ranking System: 5 tiersMetadata: IPFS + 0G StorageCrownToken.solLines of Code: 118Token Standard: ERC20 + BurnableBacking Mechanism: 1:1 FLOWDeflationary: YesArenaFactory.solLines of Code: 302Arena Creation: AutomatedRank Management: IntegratedAccess Control: Role-basedDeployed Contract Addresses (Flow Testnet)| Contract | Address | Verification | |----------|---------|-------------| | MockOracle |0x56d7060B080A6d5bF77aB610600e5ab70365696A| ✅ Verified | | CrownToken |0x9Fd6CCEE1243EaC173490323Ed6B8b8E0c15e8e6| ✅ Verified | | WarriorsNFT |0x3838510eCa30EdeF7b264499F2B590ab4ED4afB1| ✅ Verified | | ArenaFactory |0xf77840febD42325F83cB93F9deaE0F8b14Eececf| ✅ Verified |Frontend Architecture// Tech Stack interface FrontendStack { framework: "Next.js 15"; language: "TypeScript"; styling: "Tailwind CSS"; walletIntegration: "RainbowKit + Wagmi"; stateManagement: "Zustand"; realTimeUpdates: "Socket.IO"; aiIntegration: "0G Network SDK"; storage: "0G Storage"; } // Key Components interface ComponentArchitecture { battleVisualization: "Real-time battle renderer"; walletConnection: "Multi-wallet support"; warriorManagement: "NFT collection interface"; bettingInterface: "Strategic betting UI"; influenceSystem: "Real-time influence controls"; economicsDashboard: "Token economics tracking"; }AI Integration Specificationsinterface AIIntegration { network: "0G Network"; decisionLatency: "< 2 seconds"; signatureVerification: "ECDSA"; battlesPerSecond: "10+"; aiModels: "Custom trained for battle strategy"; dataStorage: "Encrypted on 0G Storage"; }ConclusionWarriorsAI-renarepresents afundamental breakthroughin blockchain gaming, combining:Real AI decision-making(not scripted NPCs)Sustainable economics(backed tokens, not speculation)Player agency(direct influence on outcomes)Technical innovation(cross-chain AI integration)Community governance(players control evolution)This isn't just innovative - it's revolutionary.🏛️⚔️🤖Built by the Seeers Team at ETH Global Cannes - Where AI meets blockchain, and every battle tells a story.
Solution
🛠️ WarriorsAI-rena: Technical Build Guide🎯 Core InnovationAI-Powered Blockchain Gamingwith cryptographically verified AI decisions, decentralized storage, and multi-chain architecture.🔧 Technology StackSmart Contracts (Solidity)Flow TestnetdeploymentECDSA signature verificationfor AI decisionsFlow VRF integrationfor true randomnessDynamic economic modelwith influence/defluence mechanicsAI Layer (0G Network)0G Compute Networkfor decentralized AIGPT-4 integrationvia 0G providersCryptographic authenticationfor each AI queryPay-per-inferencemicropaymentsStorage Layer (0G + IPFS)0G Storage Networkfor decentralized metadataMerkle tree validationfor file integrityIPFS fallbackfor legacy supportRoot hash as Token URIinnovationFrontend (Next.js 14)TypeScriptfor type safetyWagmi + Viemfor Web3 integrationRainbowKitfor wallet connectionsTailwind CSSfor styling🚀 Key Innovations1. AI Signature Verification// Every AI decision is cryptographically verified bytes32 dataHash = keccak256(abi.encodePacked(_WarriorsOneMove, _WarriorsTwoMove)); address recovered = ECDSA.recover(ethSignedMessage, _signedData); require(recovered == i_AiPublicKey, "Invalid AI signature");2. Flow VRF Integration// Native blockchain randomness without oracles function _revertibleRandom() private view returns (uint64) { (bool ok, bytes memory data) = i_cadenceArch.staticcall( abi.encodeWithSignature("revertibleRandom()") ); return abi.decode(data, (uint64)); }3. 0G Storage with Root Hash URIs// NFT metadata stored as 0G root hashes const zgFile = await ZgFile.fromFilePath(req.file.path); const [tree] = await zgFile.merkleTree(); const rootHash = tree?.rootHash(); // Used as tokenURI4. Dynamic AI Prompting// AI adapts to battle state and personality const battlePrompt = ` BATTLE SITUATION: Round ${currentRound} Agent 1 Stats: STR:${strength} WIT:${wit} Battle History: ${history} TACTICAL SITUATION: ${tacticalAnalysis} Generate optimal moves avoiding repetitive patterns. `;5. Multi-Storage Fallback System// Intelligent storage detection if (tokenURI.startsWith('0x')) { metadata = await fetchMetadataFrom0G(tokenURI); } else { metadata = await fetchMetadataFromIPFS(tokenURI); }🎮 Battle System ArchitectureAI Decision FlowBattle State Analysis→ 0G Compute NetworkAI Move Generation→ GPT-4 via 0G providersCryptographic Signing→ AI private keyOn-Chain Verification→ ECDSA.recover()Battle Execution→ Smart contract logicEconomic ModelCRwN Tokenfor betting and influenceDynamic Pricingbased on battle outcomesInfluence/Defluencemechanics affect costsWinner-takes-allbetting system🔥 Notable "Hacks"1. 0G Root Hash as Token URIInstead of IPFS URLs, directly use 0G storage root hashes:tokenURI = "0x1234567890abcdef..."; // 0G root hash2. AI Provider Fallbackconst OFFICIAL_PROVIDERS = { "llama-3.3-70b-instruct": "0xf07240Efa67755B5311bc75784a061eDB47165Dd", "deepseek-r1-70b": "0x3feE5a4dd5FDb8a32dDA97Bed899830605dBD9D3" };3. Dynamic Economic Parameters// Battle outcomes affect future costs s_costToInfluenceWarriorsOne = baseInfluenceCost * (1 + battlePerformance);4. Personality-Driven AIEach warrior's AI reflects their unique traits and knowledge areas.🌐 Partner Technology Benefits0G Network✅Decentralized AI- No single point of failure✅Cryptographic Verification- All AI responses verifiable✅Cost Efficiency- Pay-per-inference vs. subscriptions✅Censorship Resistance- No central authorityFlow Testnet✅Native VRF- Built-in randomness without oracles✅Low Gas Costs- Affordable gaming transactions✅EVM Compatibility- Seamless Solidity integration✅Cadence Access- Unique Flow features📊 Contract Addresses (Flow Testnet)const contracts = { MockOracle: "0x8464135c8F25Da09e49BC8782676a84730C318bC", CrownToken: "0x959922bE3CAee4b8Cd9a407cc3ac1C251C2007B1", WarriorsNFT: "0xA51c1fc2f0D1a1b8494Ed1FE312d7C3a78Ed91C0", ArenaFactory: "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82" };🚀 Quick Start# Clone and install git clone <repo> cd WarriorsAI-rena npm install # Setup environment cp .env.example .env # Add PRIVATE_KEY and RPC_URL # Deploy contracts forge build forge deploy --network flow-testnet # Start frontend cd frontend npm run dev # Start 0G services cd 0G && npm start cd 0g-storage && npm start🎯 Technical AchievementsFirst AI-Verified Gaming- Cryptographically verifiable AI decisionsMulti-Chain Storage- Seamless 0G + IPFS integrationDynamic NFT Economics- Battle outcomes affect token economicsDecentralized AI- No single point of failure for AI servicesFlow VRF Integration- Native blockchain randomnessPersonality-Driven AI- Each warrior has unique AI behaviorWarriorsAI-renapushes the boundaries of blockchain gaming by combining cutting-edge AI, decentralized storage, and innovative smart contract design into a single, cohesive gaming experience.
Hackathon
ETHGlobal Cannes
2025
Prizes
- 🏆
Most Innovative Use of 0G Ecosystem
0G
Contributors
- yug49
10 contributions
- kaustubh76
5 contributions