The world's first platform combining competitive domain trading with a comprehensive DeFi suite and deep Doma Protocol integration. Trade fractional domain tokens with AI-powered valuations, compete in tournaments, access professional trading tools, and leverage Doma's cross-chain infrastructure - all in one unified ecosystem.
π― Track 2: Trading Competitions & Portfolio Tools
π Deep Doma Integration: Subgraph queries, fractional tokens, AI oracle, real-time event indexing (5-second polling)
- Time-bound tournaments with prize pools and dynamic leaderboards
- Real-time performance tracking and analytics
- Strategy sharing and social features
- Collateral Vaults: Deposit domains as collateral to borrow funds at competitive APY rates
- Perpetual Futures: Trade domain futures with up to 20x leverage
- Professional Charts: TradingView integration with advanced technical indicators
- Risk Management: Health factor monitoring, liquidation warnings, and portfolio analytics
- SEO-Optimized Pages: Each domain gets its own indexed landing page for maximum visibility
- XMTP Chat: Instant P2P communication between buyers and sellers
- Time-Boxed Offers: Create urgency with expiring deals
- Live Orderbooks: Real-time bid/ask spreads with depth visualization
- Multi-chain domain trading powered by Doma Protocol
- Seamless bridge integration for cross-chain liquidity
- Unified wallet experience across all supported chains
| Feature | Description | Status |
|---|---|---|
| Collateral Vaults | Use domains as collateral to unlock liquidity | β Live |
| Futures Trading | Perpetual futures with leverage up to 20x | β Live |
| TradingView Charts | Professional charting with indicators | β Live |
| Lending/Borrowing | Competitive APY rates on domain-backed loans | β Live |
| Risk Dashboard | Portfolio health monitoring and alerts | β Live |
| Order Book | Real-time depth and liquidity visualization | β Live |
| Feature | Description | Status |
|---|---|---|
| Tournaments | Time-bound competitions with entry fees | β Live |
| Leaderboards | Dynamic ranking by performance metrics | β Live |
| Prize Pools | Automated distribution to winners | β Live |
| Strategy Sharing | Learn from top traders | β Live |
| Performance Analytics | Detailed trading metrics | β Live |
| Feature | Description | Status |
|---|---|---|
| XMTP Chat | Encrypted P2P messaging | β Live |
| SEO Domain Pages | Individual indexed pages per domain | β Live |
| Time-boxed Offers | Expiring deals with urgency | β Live |
| Domain Listings | Zero-friction listing creation | β Live |
| Alert System | Beautiful toast notifications | β Live |
| Feature | Description | Status |
|---|---|---|
| Doma Subgraph | Real-time GraphQL queries for fractional tokens | β Live |
| Fractional Tokens | Full support for Doma ERC-20 domain tokens | β Live |
| DomaRank AI Oracle | Multi-factor domain valuation (Age + Demand + Keywords) | β Live |
| Event Indexer | 5-second polling (24x faster than standard) | β Live |
| Domain Metadata | Images, descriptions, social links from Doma CDN | β Live |
| Trading History | Live orderbook and historical trades | β Live |
| Market Stats | Volume, TVL, top gainers/losers | β Live |
| Requirement / Element | Status | Location / Link / Notes |
|---|---|---|
| Track Selected | β | Track 2 β Trading Competitions & Portfolio Tools |
| Public GitHub Repo | β | This repository (MIT licensed) |
| Doma Protocol Usage (explicit) | β | Deep Integration: Subgraph (GraphQL), Poll API (5s indexing), Fractional Tokens, DomaRank AI Oracle - See DOMA_INTEGRATION_SUMMARY.md |
| Competition & Leaderboard Implementation | β | Live: backend + websocket events (leaderboard_delta) |
| OnβChain / Contract Layer | β | Smart contracts + Doma fractionalization support |
| Valuation Heuristics / Oracles | β | DomaRank AI Oracle: Multi-factor (Age 20% + Demand 50% + Keywords 30%), 10-min updates, conservative pricing |
| Whitelisted Operations / Policy Hooks | β (API / policy endpoints) | policy/* endpoints + whitelist gating logic (contracts whitelist pending) |
| Derived / Basket / ETF Mechanic | β (ETF service scaffold), π§ (on-chain basket token) | NAV computation + fee events; basket tokenization roadmap Phase 11 |
| Prize Escrow & Automated Distribution | π§ | Manual/stub flow; escrow contract in roadmap Phase 10 |
| Promotion / Strategy Vault Path | β (event & stub design) | Winner promotion hook (StrategyVault stub) planned post-settlement |
| Replay & Deterministic Dataset | β | seed_demo_dataset + demo-manifest.*.jsonl |
| Metrics Snapshot (tx count, participants) | β | psql $DATABASE_URL -c "select count(*) from trades; select count(distinct wallet_address) from competition_participants;" |
| Integrity / Auditability | β | Rolling hash + Merkle snapshots + audit export endpoints |
| Risk / AntiβAbuse Controls | β (backend) | Wash / rapid flip / self-cross / circular pattern flags |
| KYC / Governance Hooks | β (API) | Policy & KYC endpoints; gating of reward claims |
| Demo Video (Recorded) | π§ (TODO) | Placeholder: https://youtu.be/VIDEO_ID_TODO |
| Live / Test Deployment (Optional) | π§ | Placeholder: https://demo.domacross.xyz |
| Project X/Twitter Account | π§ (TODO) | Placeholder: https://twitter.com/DomaCrossApp |
| Contract Addresses Table | π§ | Add table below before submission |
| Metrics Snapshot (tx count, participants) | π§ | Provide quick script outputs (see Metrics Collection section) |
| Ambassador Challenges (Bonus) | Optional | Note any completed in PR description if done |
| Contract | Address | Notes |
|---|---|---|
| CompetitionFactory | 0x________ |
Deploy via Hardhat script; emits CompetitionCreated |
| Competition (example) | 0x________ |
Created instance for demo (ID 1) |
| ValuationOracle (stub) | 0x________ |
Emits factor events (planned) |
| PrizeEscrow (planned) | β |
To deploy Phase 10 |
| BasketToken / NAV (planned) | β |
Snapshot or dynamic basket token |
Keep this table minimal & accurate; remove planned rows if not deployed.
| Aspect | Implemented Now | Roadmap Extension |
|---|---|---|
| Domain Entity Ingestion | SDK / API stubs + local dataset | Live streaming from Doma marketplace events |
| Valuation Factors | Heuristic multi-factor (see list) | External oracle weighting + ML confidence refinement |
| Competition Lifecycle | Backend state + events | Fully on-chain custody / settlement proofs |
| Whitelist & Policy | API enforced | Contract-level operation allow-list + timelock governance |
| Derived Instruments | NAV service scaffold | Basket token mint/redeem + secondary liquidity pool |
| Prize Flow | Manual claim stub | Automated escrow contract + PrizeClaimed event |
Run after a realistic 5β10 minute session (scripted or replay) to produce transparent numbers:
# Count total trades (fills)
psql $DATABASE_URL -c "select count(*) from trades;"
# Unique active participants
psql $DATABASE_URL -c "select count(distinct wallet_address) from competition_participants;"
# Valuation snapshots produced
psql $DATABASE_URL -c "select count(*) from valuations;"
# Current leaderboard (top 5)
psql $DATABASE_URL -c "select wallet_address, score from leaderboard_entries order by score desc limit 5;"Paste the outputs into a short βMetrics Snapshotβ subsection or attach as an image in the demo video description.
- Insert final demo video URL
- Insert Twitter handle & ensure at least 1 pinned teaser tweet
- Populate contract addresses table
- Capture metrics snapshot & insert outputs
- (Optional) Deploy temporary public demo & add URL
- Verify LICENSE & README unchanged except for completion updates
- Run replay script successfully (document exit code 0)
| Criteria | Weight | How Addressed |
|---|---|---|
| Innovation | 40% | ETF abstraction + dispute-aware valuation + deterministic replay + integrity chain + ensemble roadmap (multiβoracle + ML confidence) + execution & risk telemetry. |
| Doma Integration & Onchain Impact | 30% | Domain valuation & trading events reference Doma tokenized domains; ingestion & orderbook snapshot stubs ready; settlement verification, whitelist/KYC, policy governance, NAV + fee accrual designed for on-chain metrics (tx volume, NAV churn). |
| Usability | 20% | Next.js dashboard: live leaderboard, valuation panel, ETF NAV/flow charts, replay mode (Sample/Full manifests), compact risk/execution charts, pause & refresh controls. Deterministic seed script = zero-friction spinβup. |
| Demo Quality | 10% | Full JSONL manifest + toggle, scripted dataset seeding, panels synchronized to replay, EVENTS.md schemas, clear demo path below. |
| Milestone | Date (UTC) |
|---|---|
| PreβRegistration Open | Aug 9 2025 |
| Submissions Open | Aug 16 2025 |
| Submission Deadline | Sept 12 2025 |
| Winners Announced | Oct 3 2025 |
| Requirement | Status | Location / Notes |
|---|---|---|
| Public GitHub Repo | β | This repository |
| Doma Usage Description | β | Sections: Doma Integration & Architecture, Track Fit guide |
| Track Goal Alignment | β | This README (Track Fit) +docs/hackathon-track2-summary.md |
| Demo & Walkthrough (recording) | π§ | To be added (/docs/demo-playbook.md) β script + commands present |
| Active Project X/Twitter | π§ | Placeholder handle to be inserted before submission |
| Ensemble / Valuation Evidence | β | Transparency endpoint + factors + chosen_source (ensemble stub) |
| Replay / Deterministic Dataset | β | seed_demo_dataset.py + demo-manifest.*.jsonl |
| Governance / Policy + KYC | β | Policy & KYC endpoints (README section) |
| On-Chain Settlement Proof Path | β | Competition settlement contract + backend verification endpoints |
License: MIT license included (see
LICENSE).
- Executive Summary
- Hackathon Alignment
- Quick Start
- Architecture Layering
- Valuation Methodology & Ensemble Roadmap
- Competition Lifecycle & Data Flows
- Integrity & Audit Chain
- Economic & Incentive Loop
- Policy / KYC / Governance & Risk Controls
- Events & API Surface
- Replay & Demo Guide
- Roadmap (Phase Matrix)
- Deployment & Production Notes
- Testing & Performance
- Contributing / License / Support
- Node.js 18+
- Python 3.11+
- PostgreSQL
- Redis (optional)
- Docker & Docker Compose
# Clone the repository
git clone https://github.com/your-org/domacross
cd domacross
# Copy environment file
cp .env.example .env
# Edit .env with your configuration
# Required: Database credentials, API URLs
# Optional: Blockchain RPC URLs, API keys# Start databases and services
docker-compose up -d db redis
# Wait for services to be ready
sleep 10cd apps/api
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Initialize database
python seed_domains.py # Seeds demo domains
# Start API server
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000cd apps/web
# Install dependencies
npm install
# Start development server
npm run dev
# Access the application
open http://localhost:3000π Landing Page: http://localhost:3000
π Marketplace: http://localhost:3000/marketplace
π° DeFi Suite: http://localhost:3000/defi
π Competitions: http://localhost:3000/competitions
π Trading Dashboard: http://localhost:3000/trading
π Domain Pages: http://localhost:3000/domains/[name]
π Alert Demo: http://localhost:3000/demo/alerts
| Layer | Responsibility | Key Artifacts |
|---|---|---|
| UI / App | User workflows, telemetry visualization, replay, optimistic UX | Next.js app, React Query hooks (useOrderbookActions, valuation panel, risk charts) |
| API Core | Competition lifecycle, valuation batches, ETF NAV, rewards, risk metrics, policy, KYC | FastAPI routers & services (valuation_service, metrics_service, audit_service) |
| Persistence | Durable state & analytical factors | PostgreSQL (domains, trades, listings/offers, valuations, audit_events, merkle_snapshots, governance, competitions, escrow) |
| Integrity | Tamper evidence & cryptographic summarization | Rolling SHA-256 integrity hash + periodic Merkle snapshots + (stub) signature |
| Valuation Oracle | Multi-factor fair value & dispute dampening | Heuristic blend + orderbook mid + top bid + last sale median + decay + ensemble stub |
| Incentives | Emissions + retroactive KYC claim gating | Epoch reward processing, gated reward claim endpoints |
| Contracts (current) | Competition / oracle scaffolding | Solidity stubs (Hardhat) |
| Contracts (next) | Custody, prize escrow, basket tokenization, multi-oracle commit | Roadmap phases 10β12 |
- Framework: Next.js 15 with App Router
- Styling: Tailwind CSS with glassmorphism effects
- Web3: Wagmi, Viem, RainbowKit
- Real-time: WebSocket for live updates
- Charts: TradingView integration
- Chat: XMTP protocol
- API: FastAPI (Python)
- Database: PostgreSQL + SQLAlchemy
- Caching: Redis (optional)
- Authentication: JWT + wallet signatures
- SDK: @doma-protocol/orderbook-sdk
- Smart Contracts: Solidity + Hardhat
- Networks: Multi-chain support via Doma Protocol
-
All-in-One Platform: Unlike competitors that focus on single features, DomaCross combines:
- Marketplace with SEO-optimized domain pages
- DeFi lending and futures trading
- Competitive tournaments with prizes
- Professional trading tools
-
Zero-Friction Philosophy:
- Each domain gets an indexed landing page
- Time-boxed offers create urgency
- XMTP chat enables instant negotiation
- On-chain offer IDs linked to chat threads
-
Advanced DeFi Features:
- Use domains as collateral (first platform to offer this)
- Trade perpetual futures with up to 20x leverage
- Professional TradingView charts
- Comprehensive risk management
-
Beautiful Dark Theme UI:
- Glassmorphism effects throughout
- Smooth animations and transitions
- Responsive design for all devices
- Custom alert system with toast notifications
- Page β Offer Rate: Conversion from domain page visits to offers
- Chat β Deal Closure: Success rate of XMTP negotiations
- Indexed Pages: SEO performance of domain landing pages
- Liquidity Depth: Order book thickness and spread
- Health Factors: Collateral position safety
- Trading Volume: 24h and historical trends
- Location:
apps/web/ - Features: Wallet connection, competition browsing, dashboard
- Tech Stack: Next.js, React, Tailwind CSS, Wagmi, React Query
- Location:
apps/api/ - Features: Authentication, competition management, portfolio tracking
- Tech Stack: FastAPI, SQLAlchemy, PostgreSQL, Redis
- Location:
contracts/ - Features: Competition logic, portfolio tracking, prize distribution
- Tech Stack: Hardhat, OpenZeppelin, Solidity
βββ apps/
β βββ api/ # FastAPI backend
β β βββ app/
β β β βββ models/ # Database models
β β β βββ routers/ # API endpoints
β β β β βββ domains.py # Domain trading endpoints
β β β βββ services/ # Business logic
β β β βββ main.py # FastAPI app
β β βββ seed_domains.py # Database seeder
β βββ web/ # Next.js frontend
β βββ app/
β β βββ marketplace/ # Marketplace pages
β β βββ defi/ # DeFi dashboard
β β βββ trading/ # Trading center
β β βββ domains/[name]/ # SEO domain pages
β β βββ competitions/ # Tournament pages
β βββ components/
β β βββ defi/ # DeFi components
β β β βββ CollateralVault.tsx
β β β βββ FuturesTrading.tsx
β β β βββ TradingChart.tsx
β β βββ ui/ # UI components
β β β βββ Alert.tsx # Toast notifications
β β βββ XMTPChat.tsx # Chat integration
β βββ lib/
β βββ orderbook/ # SDK integration
β βββ defi/ # DeFi types
βββ contracts/ # Smart contracts
βββ docker-compose.yml # Local development
βββ README.md # This file
| Topic | Path | Notes |
|---|---|---|
| Track 2 Summary | docs/hackathon-track2-summary.md |
Condensed judging alignment |
| Demo Playbook | docs/demo-playbook.md |
Narrated 3β5 min script & flow |
| Architecture Overview | docs/architecture-overview.md |
Diagram placeholder (to finalize) |
| Secret Handling | docs/secret-handling.md |
Dev vs prod guidance & rotation roadmap |
| Performance Report | docs/perf-report.md |
Populate with p50/p95 using scripts |
| Ensemble Sample | docs/samples/ensemble-sample.json |
Chosen source + confidence example |
| Valuation ADR | docs/adr/adr-001-valuation-heuristic.md |
Accepted (heuristic + ensemble stub) |
| Incentives ADR | docs/adr/adr-002-incentives-emissions.md |
Accepted (composite metrics) |
| Events Schema | EVENTS.md |
Completed (v1.1 valuation + placeholders) |
Pending before submission: diagrams, ADRs, EVENTS.md, populated perf metrics.
# Build frontend for production
cd apps/web
npm run build
npm run start
# Deploy API with PM2
cd apps/api
pm2 start app.main:app --name domacross-api
# Or use Docker
docker-compose -f docker-compose.prod.yml up -d# Frontend (.env.local)
NEXT_PUBLIC_API_BASE_URL=http://localhost:8000
NEXT_PUBLIC_WS_URL=ws://localhost:8000/ws
# Backend (.env)
DATABASE_URL=postgresql://user:pass@localhost/domacross
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-secret-keyWe welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Frontend: ESLint + Prettier configuration
- Backend: Black + isort for Python
- Commits: Conventional Commits format
| Driver | Mechanism | Outcome |
|---|---|---|
| Transparency | Factor + confidence panel | Trust & fair pricing perception |
| Replay Dataset | Instant walkthrough & analytics reproducibility | Faster onboarding |
| ETF Wrapper | Aggregates domain set into single NAV share | Attracts passive liquidity |
| Emissions | Rewards diversified, performant activity | Sustains early liquidity |
| Settlement Provenance | Cryptographic audit chain + Merkle roots | Verifiable integrity |
- Page Load: < 2s (Lighthouse score > 90)
- API Response: p50 < 100ms, p95 < 500ms
- WebSocket Latency: < 50ms
- Chart Rendering: 60 FPS
- Wallet-based authentication (EIP-191)
- JWT tokens for API access
- Rate limiting on all endpoints
- SQL injection prevention via ORM
- XSS protection with React
- CORS configuration for production
MIT License - see LICENSE file
- Doma Protocol for the domain trading infrastructure
- TradingView for professional charting
- XMTP for decentralized messaging
- OpenZeppelin for smart contract libraries
- GitHub Issues: Report bugs or request features
- Discord: Join our community
- Twitter: @DomaCrossApp
- Email: support@domacross.xyz
- Core marketplace functionality
- DeFi lending/borrowing
- Futures trading
- Competition system
- XMTP chat integration
- Mobile app (React Native)
- Advanced analytics dashboard
- Governance token launch
- Cross-chain bridge integration
- AI-powered domain valuation
- Institutional trading features
- API for third-party integrations
- Domain index funds
- Automated market makers
- Social trading features
Transforming domain trading into a comprehensive DeFi experience
flowchart LR
subgraph User & Client
A[User Actions]
UI[Next.js Dashboard]
end
A --> UI
UI -->|REST / WS| API[(FastAPI Backend)]
subgraph Trading
L[Listings]
O[Offers]
T[Trades]
DS[(Domain State)]
end
API --> L
API --> O
L --> T
O --> T
T --> DS
L --> DS
O --> DS
subgraph Valuation
VE[Valuation Engine\n(factors)] --> EN[Ensemble Stub]
end
DS --> VE
EN --> VEVT{{valuation_update}}
subgraph Competition
CE[Competition Engine]
LEAD{{leaderboard_delta}}
end
T --> CE
VEVT --> CE
CE --> LEAD
subgraph ETF
NAV[ETF NAV Service]
FEES{{fee/flow events}}
end
DS --> NAV
VE --> NAV
NAV --> FEES
NAV --> APY[(NAV/APY History)]
subgraph Incentives
EM[Emission Scheduler]
RW[Rewards]
end
CE --> EM
FEES --> EM
EM --> RW --> A
subgraph Integrity
AE[Audit Events]
MS[Merkle Snapshots]
end
T --> AE
CE --> AE
FEES --> AE
VEVT --> AE
AE --> MS
subgraph Risk
RG[Risk Heuristics]
RF{{risk_flag}}
end
T --> RG --> RF
RF --> CE
classDef ws fill=#e3f2fd,stroke=#2196f3,color=#0d47a1
class VEVT,LEAD,FEES,RF ws
- Wallet Authentication: EIP-191 signature-based auth
- Competition Management: Create, join, and track competitions
- Portfolio Tracking: Real-time portfolio valuation
- Leaderboard System: Rank participants by performance
- Real-Time Trading Feed: WebSocket sequencing with gap detection + incremental backfill (
since_seq) - Listings & Offers Lifecycle: Create / buy / cancel listings, create / accept / cancel offers (SDK-first)
- Optimistic UI Updates: Temp entries reconciled via contract+token mapping
- Event Store & Activity Feed: In-memory circular buffer (capture + export/import replay)
- Replay Controls: Capture toggle, export/import JSON, timed playback with speed control
- Demo Dataset & Full Replay Manifest: Deterministic seed script + comprehensive 20s manifest (listings/offers/fills/cancels/valuations/NAV/flows/fees)
- Valuation Panel: Live
valuation_updateevent digestion with delta % computation - Leaderboard Panel: Session-scope live score aggregation from
leaderboard_delta - Offer Multi-Currency Support: Dynamic supported currencies enumeration + correct decimals handling
- Cross-Chain Ready: Architecture supports multiple blockchains
- Database Schema: Complete PostgreSQL schema
- API Endpoints: RESTful APIs for all features
- Smart Contracts: Competition, portfolio, and oracle contracts
- Frontend UI: Modern React components with Tailwind CSS
- Advanced Trading Enhancements: Extended order types, batch actions
- Prize Distribution: Automated winner payouts
- Cross-Chain Integration: Doma bridge integration
- Playback UX Improvements: Timeline scrubber & label overlay for replay mode
- Auth Hardening: WebSocket auth tokens for private event scopes
- On-Chain Event Backfill: Historical sync & reorg safety
- Valuation Ensemble (Phase 10): Optional multi-source blend (heuristic + external oracle stub + ML placeholder) with confidence multiplier β toggle via
VALUATION_USE_ENSEMBLE=1(seedocs/samples/ensemble-sample.json).
Competitive domain trading drives order flow; ETF abstraction & valuation fairness mechanisms create repeatable reasons to transact (rebalancing, arbitrage of mispriced domains, fee & APY capture). The platform surfaces:
- Real-time leaderboards (incentivizes frequent domain trades)
- Transparent valuations (reduces information asymmetry; boosts confident bidding/listing)
- ETF issuance/redemption & fee events (secondary transaction vector)
- Replay / synthetic dataset (accelerates user onboarding & judge verification)
- Risk & execution quality metrics (surface trading performance insights -> retention)
| Component | Description |
|---|---|
| WebSocket Sequencing | Every event assigned a monotonically increasing seq; clients persist last applied seq in localStorage (rt_seq). |
| Gap Detection | If incoming seq > last_seq + 1, client triggers incremental backfill via REST using ?since_seq=<last_seq>. |
| Differential Backfill | /api/v1/listings & /api/v1/offers accept since_seq returning only newly created active entries. |
| Optimistic Entries | Temporary IDs (temp-*) inserted immediately; replaced when authoritative listing_created / offer_created arrives (match by contract+token). |
| Event Store | Lightweight in-memory buffer (max 300) with capture toggle; supports replay export/import JSON (versioned). |
| Replay Controls | UI allows capture enable/disable, export, import, and timed playback dispatching events as custom doma-replay-event. |
| Panels | Valuation panel consumes valuation_update; leaderboard panel aggregates leaderboard_delta. |
listing_created, listing_filled, listing_cancelled, offer_created, offer_accepted, offer_cancelled, valuation_update, leaderboard_delta
Listings & offers initially rendered with temp-* IDs; when the real event shares contract + tokenId, temp entry is replaced preserving insertion order.
- Ensure activity is generating events (listings/offers or valuation batch calls).
- In Dashboard -> Recent Activity card, toggle Capture (green = on).
- Perform actions, then Export to download
events_capture.json. - Import the same (or modified) file and click Replay. Panels listening to
doma-replay-eventupdate without touching live seq state. - Adjust speed (200ms, 500ms, 1000ms) for slower/faster playback.
A deterministic demo dataset + expanded replay manifest enables instant showcase without manual actions.
Seed the dataset:
cd apps/api
python -m app.cli.seed_demo_datasetStart services then open the dashboard with ?demo=1 to enable Demo Mode controls:
http://localhost:3000/dashboard?demo=1
Manifests:
demo/demo-manifest.sample.jsonl(minimal quick run)demo/demo-manifest.full.jsonl(~20s sequence: listings / offers / fills / cancels / valuations across 10 domains + ETF NAV, flows, fee accruals, leaderboard deltas)
Switch manifests via the Sample / Full buttons in the Demo Replay section of LiveOpsPanel.
Offer form fetches supported currencies via SDK (getSupportedCurrencies). Selected currency's decimals determine unit conversion (parseUnits equivalent via viem). Last chosen currency persists in localStorage (offer_currency).
POST /valuation/batch triggers server-side valuation computations. Backend emits valuation_update with optional previous_value & change_pct. Frontend panel computes delta fallback if not provided and lists most recent per domain.
leaderboard_delta events accumulate session scores per address. Client aggregates in-memory (no persistence yet) and renders top 25. Future work: merge with server authoritative rankings & add paging.
- WebSocket authentication (token / signature) for private scopes.
- Replay isolation guardrails (currently separate custom event channel; maintain).
- Rate-limited backfill on repeated gap triggers.
- Cleanup of stale optimistic entries if authoritative event never arrives (time-based eviction).
cd contracts
npx hardhat testcd apps/api
# Run with pytest or manual testing
pytest -qWe provide a JSONL audit export with cursor-based resumption:
Endpoint: GET /api/v1/settlement/audit-export?limit=5000&after_id=<last_id> (admin only)
| Control | Description | Trigger / Window | Persistence |
|---|---|---|---|
| Rate Limiting | Per-wallet & per-IP token bucket | N trades/min (configurable burst) | In-memory + Redis ZSET (timestamps) |
| Circuit Breaker | Halts trading on extreme NAV move | Absolute NAV move >= threshold bps over rolling window | In-memory + Redis key with TTL |
| Wash Trade Detection | Opposite side trade by same participant on domain | 120s window | DB trade_risk_flags + websocket risk_flag event |
| Rapid Flip Detection | >=3 flips (side changes) then new trade flags | 10m window | DB + websocket |
| Self-Cross | Opposite side within 30s (tighter wash) | 30s window | DB + websocket |
| Circular Pattern | Domain traded among β₯3 participants and returns to origin | 10m sequence scan | DB + websocket |
| Idempotent Redemption Intent | Prevent duplicate redemption creation | Idempotency-Key header | idempotency_keys table |
| Idempotent Competition Settlement Submit | Prevent duplicate settlement submissions | Idempotency-Key header | idempotency_keys table |
If REDIS_URL is set:
- Rate limiting buckets stored as sorted sets:
abuse:bucket:<wallet_or_ip> - Circuit breaker flag stored as
abuse:circuit_breakerwith TTL = breaker window. Fallback gracefully degrades to in-memory structures if Redis unreachable.
Clients subscribe using: GET /ws?events=risk_flag.
Payload shape:
{ "type": "risk_flag", "trade_id": <int>, "flag_type": "WASH_LIKELY|RAPID_FLIP|SELF_CROSS|CIRCULAR_PATTERN" }Events are emitted synchronously after trade processing; tests assert contract.
- Expand idempotency to issuance / other settlement intents.
- Add anomaly scoring (z-score on trade frequency) feeding a
ANOMALYflag. - Persistence of rolling participant metrics for ML-based flagging.
| Component | Endpoint(s) | Description |
|---|---|---|
| Domain Whitelist | GET/POST/DELETE /api/v1/policy/whitelist |
Admin CRUD for allowed domains (if any active entries exist all listings/offers/buys restricted to set) |
| Governance Config | GET /api/v1/policy/config, POST /api/v1/policy/config/{key} |
Key/value config store for tunable governance parameters (JSON values) |
| KYC Requests | POST /api/v1/policy/kyc/request |
User submits optional document hash for verification |
| KYC Review | GET /api/v1/policy/kyc/requests + `POST .../approve |
reject` |
| Admin Action Audit | GET /api/v1/policy/audit |
Immutable log of admin policy actions (whitelist, KYC, config) |
| Reward KYC Gating | (server internal) | Epoch reward distribution zeroes reward_amount for nonβKYC users (raw amount preserved for later claim) |
| Reward Claim | POST /api/v1/competitions/{competition_id}/epochs/{epoch_index}/claim |
User reclaims previously gated reward once KYC passes (retroactive) |
KYC Flow:
- User calls submit endpoint (status=PENDING).
- Admin reviews pending queue, approves (sets
kyc_verified=true) or rejects (status=REJECTED with notes). - Distribution logic writes both
raw_reward_amountand gatedreward_amount. Nonβverified users getreward_amount=0but retainraw_reward_amountfor later claim. - After approval, user calls claim endpoint to set
reward_amount = raw_reward_amountand markclaimed_at(idempotent).
Admin Authentication: wallets listed in ADMIN_WALLETS_ENV (comma or JSON list) are treated as admins on startup; plus perβuser is_admin boolean allows manual elevation.
Whitelist Enforcement Logic: Listing / offer / buy endpoints query active whitelist rows. If any exist, domain must be present or a 400 error (domain not whitelisted) is returned. ETF creation already enforced previously.
Audit Coverage: Every policy change inserts admin_action_audit row: action types include WHITELIST_ADD, WHITELIST_DEACTIVATE, GOV_CONFIG_CREATE, GOV_CONFIG_UPDATE, KYC_APPROVE, KYC_REJECT, WHITELIST_REACTIVATE.
Realtime Events (emitted over /ws when subscribed):
policy_change(subtype: whitelist_add|whitelist_reactivate|whitelist_deactivate|config_upsert)kyc_status(status transitions: PENDING, APPROVED, REJECTED)reward_claim(user successfully claims retroactive reward)
Roadmap Additions (remaining / future hardening):
- On-chain settlement verification for claimed rewards.
- Admin UI live refresh via websocket (already receiving events; add optimistic update patterns).
- KYC document storage off-chain with signed hash anchoring.
Headers returned:
X-Next-Cursor: last event id in the batch (use asafter_idto resume)X-Integrity-OK:true|falseif integrity chain verification passed whenverify_integrity=true
Example pagination loop (pseudo):
cursor = None
while True:
params = {'limit': 2000}
if cursor:
params['after_id'] = cursor
r = GET('/settlement/audit-export', params)
lines = r.text.strip().split('\n') if r.text else []
if not lines: break
process(lines)
cursor = r.headers.get('X-Next-Cursor')
if not cursor: breakStreaming variant: GET /api/v1/settlement/audit-export/stream (server-sent JSONL until exhaustion) supports large range pulls without manual batching.
Integrity check: pass verify_integrity=true to recompute the rolling integrity_hash chain serverβside and expose X-Integrity-OK (non-stream) or per-line integrity_ok (stream).
Events schema (GET /events/schema) now includes:
dispute_quorum: { domain, dispute_id, votes, threshold }dispute_resolved: { domain, dispute_id, final_status }
Subscribe via websocket:
ws = new WebSocket('ws://localhost:8000/ws');
ws.onopen = () => ws.send('SUB dispute_quorum,dispute_resolved');
Frontend component DisputeBanner listens and displays live dispute status for a domain.
See ADR for governance rationale: docs/adr/adr-valuation-disputes.md.
Current implementation:
- Periodic Merkle incremental snapshot every 120s (
merkle_loop). - On-chain event ingestion: stubbed (blockchain receipt verification exists; continuous on-chain scan not yet implemented).
- Orderbook + reconciliation loops run only when external base URL provided.
Deferred / Not Yet Implemented:
- Full historical on-chain event backfill & gap reorg handling.
- Persistent external queue / dead-letter for failed snapshot operations.
- Parallel shard aggregation for very large audit logs (> millions events).
Mitigations / Next Steps:
- Introduce block range cursor table and lightweight chain scanner task.
- Add periodic integrity self-audit endpoint to compare DB chain vs recomputed digest offline.
- Provide CLI utility to backfill snapshots for archival export.
Warnings: Pydantic v1-style config deprecation warnings are filtered in tests (see pytest.ini). Migration to Pydantic v2 style is a backlog item.
The settlement admin panel (competition payout submission & verification) is gated client-side by the environment variable:
NEXT_PUBLIC_ADMIN_WALLETS=0xAdmin1,0xAdmin2;0xAdmin3
Accepted delimiters: comma, semicolon, or whitespace. Wallet addresses are matched case-insensitively. Only listed addresses will see the Settlement (Admin Demo) section on a competition detail page. Backend endpoints performing sensitive actions also enforce server-side checks using settings.admin_wallets loaded from API env (ADMIN_WALLETS).
To configure locally:
# apps/web/.env.local
NEXT_PUBLIC_ADMIN_WALLETS=0xB47269260Ae1bD614FDc37ADA0eB04Cdb93c5E95,0x364d11a2c51F235063b7DB5b60957aE2ea91ACEE
# apps/api/.env (or parent .env consumed by backend)
ADMIN_WALLETS=0xB47269260Ae1bD614FDc37ADA0eB04Cdb93c5E95,0x364d11a2c51F235063b7DB5b60957aE2ea91ACEE
If a user is not in the list, the admin UI does not render and protected endpoints return 403.
cd apps/web
npm run build # Check for build errorsWhile certain marketplace / orderbook ingestion paths are stubbed for hackathon pacing, the abstraction points are in place:
orderbook_snapshot_service& valuation factororderbook_midalready integrated.- Ingestion toggles (
enable_raw_chain_ingest,enable_chain_marketplace_events) gate heavier sync when real RPC endpoints configured. - Policy & whitelist endpoints mimic governance / permission channels for curated competitions.
- Merkle snapshot & settlement proof flows pave path to verifiable rewards distribution.
- Seed dataset:
python -m app.cli.seed_demo_dataset. - Start API & Web; open
?demo=1dashboard. - Toggle Full manifest; start replay β observe listings/offers/fills/valuations.
- Open Valuation Transparency panel for a domain; note factors & chosen_source.
- View ETF NAV / Flow charts; show fee accrual & (optionally) trigger distribution endpoint.
- (Optional) Trigger a valuation batch; watch live
valuation_updatedelta. - (Optional) Show dispute open & vote endpoints β observe clamp behavior.
Full scripted narration: docs/demo-playbook.md (includes recommended timestamps & talking points).
- Configure production environment variables
- Deploy smart contracts to Doma testnet/mainnet
- Build and deploy API to cloud (Railway, Heroku, etc.)
- Build and deploy frontend to Vercel/Netlify
- Set up monitoring and logging
# Build all services
docker-compose build
# Start production stack
docker-compose up -d- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
MIT License - see LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: See
/docsfolder (coming soon)
Built with β€οΈ for the Doma ecosystem Monorepo
Local-first dev on your VM with an AWS Terraform skeleton for later migration.
- Web: Next.js (apps/web)
- API: FastAPI (apps/api)
- Contracts: Hardhat (contracts)
- Docker: infra/docker/* and docker-compose.yml
- Terraform: infra/terraform/* (AWS skeleton)
- Copy envs cp .env.example .env
- Start stack docker compose up --build
- Web: http://localhost:3000
- API: http://localhost:8000/health
- Postgres: localhost:5432 (in container)
- Redis: localhost:6379 (in container)
- See infra/terraform/ for skeleton modules (ECS/RDS/Redis/ALB/WAF/Secrets).
- Provide variables via tfvars and AWS credentials.
React Query hooks implemented (apps/web/lib/hooks):
- useDomain(name): consolidated domain + top listings/offers + latest valuation
- useListings(name), useOffers(name), useValuation(name): focused slices
- useValuationBatch(domains[]): batch valuation POST /api/v1/valuation/batch
- useCurrencies(): static currency metadata (extensible)
- useOrderbook(name): pulls live orderbook (SDK if available) every 15β20s
- useBuyDomain(), useMakeOffer(): trading mutations (SDK-first, API fallback placeholders)
Component: DomainMarketPanel (apps/web/components) demonstrates integration; navigate to /market/{domainName}.
Next steps: backend trading endpoints, real fee preview integration, websocket push for deltas.
Added external_order_id columns to listings and offers for SDK order ID mapping. Create a new Alembic migration:
- alembic revision -m "add external order ids" --autogenerate
- alembic upgrade head
Listings now include an expires_at timestamp (auto-set using LISTING_TTL_DAYS, default 30).
Admin-only endpoint to deactivate expired listings:
DELETE /api/v1/market/expired/listings
Accept an existing (active) offer via:
POST /api/v1/market/accept-offer with offer_id or external_order_id.
Frontend hook: useAcceptOffer() (gracefully falls back if SDK acceptOffer not yet available).
Trades recorded from buys and accepted offers now only attribute to participants active within competitions whose time window currently includes the trade timestamp. This avoids polluting historical or future competitions with out-of-window trades.
Environment variable:
LISTING_TTL_DAYS=30 # adjust to shorten or lengthen default listing lifetime.
Run new migration adding expires_at to listings:
- alembic revision -m "add listing expires_at" --autogenerate
- alembic upgrade head
The platform implements cryptographic provenance for settlement and fee events:
- Every significant action records an
AuditEventwith an integrity hash chain (integrity_hashlinks to the previous canonical JSON). - Periodic
MerkleSnapshotrows are created from all audit event leaves; each snapshot root is RSA-signed (ephemeral or configured keys) and optionally anchorable on-chain (stubbed). - Clients fetch proofs via
/api/v1/settlement/audit-events/{id}/merkle-proofor batched/api/v1/settlement/snapshot-with-proofs. - Public key exposed at
/api/v1/settlement/public-keywith strong caching + ETag for local verification of signatures. - Streaming export endpoints (
/api/v1/settlement/audit-exportand/api/v1/settlement/audit-export/stream) support JSONL export and optional integrity re-verification (setsX-Integrity-OKheader or inlineintegrity_okflags).
Redemption lifecycle:
- Create intent:
POST /api/v1/etfs/{id}/redeem/intent - Execute:
POST /api/v1/etfs/{id}/redeem/execute/{intent_id}?tx_hash=...(records execution + audit event). - Submit proof (optional source of tx hash if not provided earlier):
POST /api/v1/settlement/etfs/{id}/redemption-proof/{intent_id}. - On-chain semantic verification:
POST /api/v1/settlement/etfs/{id}/redemption-verify/{intent_id}(auto-discovers tx hash from latest proof if not passed). - After success,
verified_onchainflag gates finalization logic (execute endpoints require prior verification for subsequent settlement-sensitive actions).
Semantic checks (centralized in app/services/redemption_validation.py):
- Transaction status == 1
- Block number present
gasUsed >= REDEMPTION_MIN_GAS_USED- Log count >=
REDEMPTION_MIN_LOGS - Optional
toaddress match (REDEMPTION_CONTRACT_ADDRESS) - Optional event topic0 presence (
REDEMPTION_EXPECTED_EVENT_TOPIC0) - Optional minimum native value (
REDEMPTION_MIN_VALUE_WEI)
Response contains: verified, block, gas_used, log_count, and audit_event_id when newly verified (plus already on idempotent re-checks).
When ENABLE_RAW_CHAIN_INGEST=true and DOMAIN_MARKETPLACE_CONTRACT_ADDRESS are provided, the background chain scanner decodes DomainMarketplace events directly from logs:
Parsed events:
OrderCreated(orderId, seller, domainContract, tokenId, price)β emitsCHAIN_ORDER_CREATEDaudit event.TradeExecuted(tradeId, buyer, seller, price)β emitsCHAIN_TRADE_EXECUTEDaudit event and records a placeholderTraderow (domain attribution TBD once full ABI indexing added).
Config flags (env vars):
ENABLE_CHAIN_MARKETPLACE_EVENTS=true(defaults on; gated by raw ingest flag)DOMAIN_MARKETPLACE_CONTRACT_ADDRESS=0x...(lowercased match)
Safety & Reorg Handling: shallow reorgs up to 6 blocks trigger rewind of the cursor preserving idempotency of audit chain (later events simply recompute integrity linkage). Deep reorgs are out-of-scope for hackathon context.
Future improvements:
- Full ABI decoding for all parameters (domain contract + tokenId) and domain name resolution.
- Backfill historical ranges beyond current head-window.
- Persistent reorg journal for deterministic reconciliation.
Persistent Order Attribution Cache (Completed):
Added marketplace_order_cache table + in-memory mirror. Each OrderCreated persists order metadata; TradeExecuted first attempts direct orderId match (assumes interim tradeId==orderId semantics) then heuristics (seller+price). Fulfillment updates the cache with tx hash and block time enabling restart-safe attribution and future settlement provenance queries.
Test coverage ensures:
- Cursor-based resume (
test_audit_export_resume_cursor). - Merkle snapshot generation and single-event proof reconstruction (
test_merkle_snapshot_and_proof). - Streaming export integrity flags.
Add new tests for on-chain marketplace decoding as ABI details stabilize (placeholder events currently logged). A future test_chain_marketplace_ingest.py will assert:
- Given synthetic logs for
OrderCreated/TradeExecuted, corresponding audit events persist. - Integrity hash chain remains continuous across decoded and polled events.
- Trade placeholder row creation (until enriched attribution implemented).
| Variable | Description | Example |
|---|---|---|
REDEMPTION_CONTRACT_ADDRESS |
(Optional) Expected contract address for redemption tx to field. |
0xabc... |
REDEMPTION_EXPECTED_EVENT_TOPIC0 |
(Optional) Keccak hash of expected Redemption event (topic0). | 0x1234... |
REDEMPTION_MIN_LOGS |
Minimum number of logs required. | 1 |
REDEMPTION_MIN_GAS_USED |
Minimum gasUsed threshold for semantic validity. | 60000 |
REDEMPTION_MIN_VALUE_WEI |
(Optional) Minimum native value (wei) required in tx. | 1000000000000000 |
REDEMPTION_WETH_CONTRACT_ADDRESS |
(Optional) WETH token address to allow heuristic ERC20 value inference. | 0xC02a... |
- Fetch snapshot + proof(s).
- Reconstruct leaf inclusion β derive root by hashing proof path.
- Fetch public key (cache ETag).
- Verify RSA signature (PKCS#1 v1.5 / SHA-256) over the hex root string.
- Optionally verify audit integrity chain separately (stream export with
verify_integrity=true).
Run focused tests:
cd apps/api
pytest -k redemption_validation_helper -qThe test suite covers success and each semantic failure reason (status, missing block, gas, logs, contract, topic, min value).