️ Guild Treasury Wars - DAO-Governed Factions with stellar-zk Commitments

Other Transitional
authprivacycommit-revealecs

Transitional example: This example uses an older Cougr pattern and is preserved for compatibility reference. For the current recommended approach, see snake.

Build Status Tests Stellar

A guild-based strategy game implemented as a Soroban smart contract using cougr-core's ECS framework. Guilds manage shared treasuries, vote on strategic actions through DAO mechanics, and compete through hidden strategic commitments powered by stellar-zk.

Why stellar-zk?

In strategy games, revealing your plans to the enemy is a losing move. stellar-zk enables sealed war plans - players commit to strategies without revealing them, then prove their commitments on-chain when it's time to resolve battles.

Without stellar-zkWith stellar-zk
All actions are public on-chainStrategies are hidden until reveal
Opponents can counter every moveSealed commitments prevent scouting
No strategic depthReal hidden-information gameplay
Generic DAO demoStellar-native governance game

Gameplay Flow

┌─────────────────────────────────────────────────────────┐
│ 1. GUILD CREATION                                        │
│    Admin creates a guild with INITIAL_TREASURY (1000)     │
│    → Members join the guild (up to 10)                    │
│    → cougr-core ECS World tracks entities                 │
├─────────────────────────────────────────────────────────┤
│ 2. GOVERNANCE (DAO-style proposals)                       │
│    Members submit proposals: Defend, Attack, Upgrade,     │
│    or Allocate resources from the shared treasury          │
│    → 51% vote threshold for approval/rejection             │
│    → Inspired by Stellar governance (governance.script3)   │
├─────────────────────────────────────────────────────────┤
│ 3. TREASURY EXECUTION                                     │
│    Approved proposals deduct treasury and apply effects:   │
│    → Defend (100): +10 defense strength                   │
│    → Attack (200): Launch campaign against enemy guild     │
│    → Upgrade (150): +10 attack strength                   │
│    → Allocate: Custom resource allocation                  │
├─────────────────────────────────────────────────────────┤
│ 4. SEALED WAR PLANS (stellar-zk commit-reveal)            │
│    Members commit: SHA256(action || target || amount ||    │
│    salt) → hash stored on-chain, strategy hidden           │
│    Reveal: provide preimage, contract verifies hash        │
│    → Nullifier consumed (anti-replay protection)           │
├─────────────────────────────────────────────────────────┤
│ 5. BATTLE RESOLUTION                                      │
│    Attack strength vs defense strength                     │
│    → Winner plunders defender's treasury                   │
│    → Game round incremented                                │
└─────────────────────────────────────────────────────────┘

stellar-zk Integration

This example uses stellar-zk for real hidden-strategy gameplay, not just narrative flavor. The integration follows stellar-zk's on-chain verification patterns:

Where stellar-zk Fits

Phasestellar-zk RoleContract Function
CommitSHA256 hash seals the war plansubmit_strategy_commitment()
RevealPreimage verification proves the planreveal_strategy()
NullifierAnti-replay prevents double-revealDataKey::Nullifier(hash)
ResolveDeterministic outcome after verificationresolve_battle()

Commitment Hash

commitment = SHA256(action_type ∥ target_guild_id ∥ resource_amount ∥ salt)

The salt (32-byte random value) ensures that identical strategies produce different hashes, preventing pattern analysis by opponents.

Nullifier Pattern

Each commitment hash acts as a nullifier (following stellar-zk's verifier contract design). Once revealed:

  1. The commitment is marked as revealed = true
  2. The hash is stored in DataKey::Nullifier(hash) → true
  3. Any attempt to reuse the same commitment is rejected

References


Cougr-Core Integration

ECS Components

ComponentFieldsPurpose
Guildadmin, name, treasury, member_count, defense/attack_strengthOn-chain faction
Proposalproposer, action, votes_for/against, statusDAO governance
StrategyCommitmentcommitment_hash, committer, revealedSealed war plan
StrategyRevealaction_type, target_guild_id, resource_amount, saltRevealed preimage
GameStatetotal_guilds, total_proposals, active_campaigns, roundGlobal state

ECS World

#![allow(unused)]
fn main() {
// cougr-core ECS entity management
let mut world = cougr_core::SimpleWorld::new(&env);
let _guild_entity = world.spawn_entity();
}

Contract API

Guild Management

FunctionParametersReturnsDescription
init_guildguild_adminu32Create guild with treasury
join_guildguild_id, member-Join an existing guild

Governance

FunctionParametersReturnsDescription
submit_proposalproposer, proposal: ProposalInputu32Create a DAO proposal
votevoter, proposal_id, support: bool-Cast a vote
execute_proposalproposal_id-Execute approved proposal

Strategy (stellar-zk)

FunctionParametersReturnsDescription
submit_strategy_commitmentguild_member, proof_input: ProofInput-Seal a war plan
reveal_strategyguild_member, guild_id, reveal: StrategyReveal-Reveal and verify
resolve_battleattacker_member, defender_member, attacker_guild_id, defender_guild_id-Resolve outcome

Queries

FunctionParametersReturnsDescription
get_state-GameStateGlobal game state
get_guildguild_idGuildGuild info
get_proposalproposal_idProposalProposal info

️ Quick Start

Prerequisites

ToolVersionInstallation
Rust1.88.0+rustup.rs
Stellar CLILatestStellar Docs
WASM Target-rustup target add wasm32v1-none

Build

# Standard Rust build
cargo build

# Build WASM for Soroban deployment
stellar contract build

Test

cargo test

Validation

# Full validation suite
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test
stellar contract build

Test Results: 14 tests passing ✅

TestDescription
test_init_guildGuild creates with correct treasury and state
test_join_guildMember joins and count increments
test_submit_proposalProposal created with correct fields
test_unauthorized_proposalNon-member rejected
test_vote_counting_and_threshold51% threshold approves
test_vote_rejectionMajority-against rejects
test_unauthorized_voteNon-member vote rejected
test_double_voteDouble-voting prevented
test_treasury_execution_approvedTreasury deducted, effects applied
test_execute_unapprovedNon-approved execution rejected
test_strategy_commitment_and_revealFull commit-reveal flow
test_invalid_revealWrong preimage rejected
test_double_reveal_preventionNullifier blocks re-reveal
test_battle_resolutionAttack resolves, resources transfer

Project Structure

examples/guild_treasury_wars/
├── Cargo.toml          # Dependencies: cougr-core + soroban-sdk
├── README.md           # This documentation
└── src/
    ├── lib.rs          # Contract entry points
    ├── types.rs        # ECS Components (Guild, Proposal, Strategy, etc.)
    ├── governance.rs   # ProposalSystem, VotingSystem, TreasuryExecutionSystem
    ├── strategy.rs     # StrategyProofSystem, ResolutionSystem (stellar-zk)
    └── test.rs         # Unit tests (14 tests)

License

MIT OR Apache-2.0