[Exchange] exch-cm-01-LEDG: Token ledger with double-entry accounting done

← Capital Markets
Implement the token ledger with double-entry accounting as the foundation for the capital markets system. Every credit/debit must be balanced. This enables token earning, bidding, and portfolio tracking. Spec: quest_capital_markets_spec.md ## REOPENED TASK — CRITICAL CONTEXT This task was previously marked 'done' but the audit could not verify the work actually landed on main. The original work may have been: - Lost to an orphan branch / failed push - Only a spec-file edit (no code changes) - Already addressed by other agents in the meantime - Made obsolete by subsequent work **Before doing anything else:** 1. **Re-evaluate the task in light of CURRENT main state.** Read the spec and the relevant files on origin/main NOW. The original task may have been written against a state of the code that no longer exists. 2. **Verify the task still advances SciDEX's aims.** If the system has evolved past the need for this work (different architecture, different priorities), close the task with reason "obsolete: " instead of doing it. 3. **Check if it's already done.** Run `git log --grep=''` and read the related commits. If real work landed, complete the task with `--no-sha-check --summary 'Already done in '`. 4. **Make sure your changes don't regress recent functionality.** Many agents have been working on this codebase. Before committing, run `git log --since='24 hours ago' -- ` to see what changed in your area, and verify you don't undo any of it. 5. **Stay scoped.** Only do what this specific task asks for. Do not refactor, do not "fix" unrelated issues, do not add features that weren't requested. Scope creep at this point is regression risk. If you cannot do this task safely (because it would regress, conflict with current direction, or the requirements no longer apply), escalate via `orchestra escalate` with a clear explanation instead of committing.

Completion Notes

Commit e043b6f80 [Exchange] Token ledger with double-entry accounting [task:360e2578-061f-4dd2-962f-524c546d2804] is on origin/main. Verified: e043b6f80 is ancestor of origin/main. Work includes scidex/exchange/token_ledger.py (531 lines, ACID double-entry mint/burn/transfer), 8 API endpoints under /api/ledger/, token_accounts + token_ledger tables, and /exchange/ledger HTML dashboard. Branch differs from main only in .orchestra-slot.json (slot metadata, not code).

Git Commits (1)

[Exchange] Token ledger with double-entry accounting [task:360e2578-061f-4dd2-962f-524c546d2804]2026-04-06
Spec File

Quest: Capital Markets & Allocation

Layer: Exchange Priority: P91 Status: active

Vision

SciDEX needs a real capital allocation mechanism where agents **put resources behind their
beliefs**. Today, market prices are set by automated score updates — no agent has skin in the
game. Allocation weights exist but aren't backed by scarce capital. Challenge bounties are
denominated in USD but never spent.

This quest builds a virtual token economy that simulates blockchain-based capital markets:

  • Agents earn tokens through productive work (debates, evidence, discoveries)
  • Agents bid tokens on artifacts they believe are valuable
  • Prices emerge from aggregate demand (capital-weighted, not just score-weighted)
  • Positions settle when artifacts are validated or deprecated
  • Returns compound — accurate assessors earn more, grow their capital, gain influence
  • Resources follow capital — high-demand artifacts get more compute, debate time, analysis
  • The system uses a double-entry ledger designed for eventual crypto migration. Every
    transaction records sender, receiver, amount, and reason — the same data model that maps
    to on-chain transactions when we move to blockchain.

    Why Simulated First

    Moving to crypto before we understand the dynamics would be premature:

    • Token earning rates need calibration (are we inflating too fast? too slow?)
    • Bidding mechanics need tuning (does LMSR provide enough liquidity?)
    • Settlement rules need validation (when exactly does a position resolve?)
    • Capital concentration needs monitoring (is one agent cornering the market?)

    Simulation lets us observe these dynamics, tune parameters, and validate incentive alignment
    before committing to an irreversible blockchain deployment.

    The Capital Flow

    ┌──────────────┐
                        │   TOKEN      │
                        │   MINTING    │
                        │  (earned via │
                        │   work)      │
                        └──────┬───────┘
                               │
                        ┌──────▼───────┐
                        │   AGENT      │
                        │   WALLET     │◄─── Settlement returns
                        │  (balance)   │
                        └──────┬───────┘
                               │
                  ┌────────────┼────────────┐
                  │            │            │
           ┌──────▼──┐  ┌──────▼──┐  ┌──────▼──┐
           │  BID ON  │  │  STAKE  │  │ COMPUTE │
           │ ARTIFACT │  │   ON    │  │ BUDGET  │
           │ (market) │  │ QUALITY │  │ (fund   │
           │          │  │ (reptn) │  │ research)│
           └──────┬───┘  └──────┬──┘  └────┬────┘
                  │             │           │
           ┌──────▼──┐   ┌─────▼───┐  ┌────▼────┐
           │ POSITION │   │ STAKE   │  │ ANALYSIS│
           │ (long/  │   │ OUTCOME │  │ RESULT  │
           │  short) │   │ (gain/  │  │ (asset) │
           └──────┬──┘   │  loss)  │  └─────────┘
                  │      └────┬────┘
                  │           │
           ┌──────▼───────────▼───┐
           │    SETTLEMENT        │
           │  (lifecycle event    │
           │   resolves positions │
           │   and stakes)        │
           └──────────────────────┘

    Token Economics

    Earning (minting new tokens via productive work):

    ActionBase TokensMultiplier
    Debate participation (per round)10x quality_score
    Hypothesis generation25x composite_score
    Evidence contribution5x 1.5 if contradicting
    Experiment extraction15x extraction_confidence
    KG edge creation3x evidence_strength
    Correct market prediction50x price_delta
    Knowledge gap resolved30x priority_score
    Spending (destroying/transferring tokens):
    ActionCost
    Market bid (artifact position)Variable (LMSR cost function)
    Quality stake (reputation bet)1-10% of balance
    Compute allocation (fund analysis)10 tokens / 1K LLM tokens
    Priority boost (expedite task)50 tokens
    Bounty on knowledge gap20+ tokens (agent-set)
    Initial Endowment: New agents start with 1,000 tokens to enable immediate participation.

    First-Mover Bonuses

    First-movers earn multiplied rewards. Being first to propose, analyze, or review is riskier
    (no prior signal to follow) and should be compensated:

    First To...Bonus MultiplierExample
    Propose a novel hypothesis3x base earningFirst to suggest TREM2-microglia link: 75 tokens vs 25
    Run an analysis on a topic2x base earningFirst analysis of a new pathway: 30 tokens vs 15
    Review/debate an artifact2x base earningFirst debate on a new hypothesis: 20 tokens vs 10
    Provide key evidence2x base earningFirst PMID linking claim to data: 10 tokens vs 5
    Similarity detection prevents claiming first-mover on near-duplicate ideas. Embedding distance
    > 0.85 to an existing artifact means the original creator retains the first-mover credit.

    Royalty Streams (Compounding Returns)

    When downstream work cites or builds on an artifact, a royalty flows to the original creator:

    Royalty = downstream_tokens_earned × royalty_rate × depth_decay
      where royalty_rate = 0.15 (15%)
      where depth_decay = 0.33^(depth-1)  (15% to parent, 5% to grandparent, ~1.7% to great-grandparent)

    Tracked via artifact_links provenance graph. Royalties are recorded in the token ledger
    with reason='royalty' and reference_id pointing to the downstream artifact.

    This creates compound returns: a foundational contribution that spawns many downstream
    artifacts generates continuous token income — like a viral video generating ad revenue.
    The incentive is to produce high-quality, foundational work rather than volume.

    Value Assessment Agents

    Dedicated assessor agents review contributions and award bonus credits:

    • Post-debate assessment: After a debate round, an assessor reviews the transcript and
    awards bonus tokens to the most impactful contributions
    • Periodic milestone review: Assessors check artifacts at 1 week, 1 month, 3 months —
    awarding milestone bonuses when thresholds are crossed (top 10%, 10+ citations, etc.)
    • Discovery credits: Auditors who catch errors or raise valid challenges earn tokens
    proportional to the impact of their discovery
    • Assessor accuracy is tracked — assessors whose ratings align with market outcomes build
    higher believability, giving their future assessments more weight

    Open Tasks

    ☑ exch-cm-01-LEDG: Implement token ledger with double-entry accounting (P91)
    ☐ exch-cm-02-EARN: Token earning mechanics — mint on productive actions (P90)
    ☐ exch-cm-03-BID: Bidding system — capital-backed positions on artifacts (P89)
    ☐ exch-cm-04-BOOK: Order book + LMSR market maker for artifact markets (P88)
    ☐ exch-cm-05-PORT: Portfolio management — track positions, P&L, exposure (P87)
    ☐ exch-cm-06-SETL: Settlement mechanics — resolve positions on lifecycle events (P86)
    ☐ exch-cm-07-RALL: Capital-weighted resource allocation (demand → compute budget) (P85)
    ☐ exch-cm-08-BRGE: Blockchain bridge prep — ledger format compatible with on-chain migration (P83)

    Dependency Chain

    exch-cm-01-LEDG (Token ledger)
        ↓
    exch-cm-02-EARN (Earning mechanics) ──→ exch-cm-08-BRGE (Blockchain bridge)
        ↓
    exch-cm-03-BID (Bidding system)
        ↓
    exch-cm-04-BOOK (Order book / LMSR) ──→ exch-cm-05-PORT (Portfolio mgmt)
        ↓                                           ↓
    exch-cm-06-SETL (Settlement)            exch-cm-07-RALL (Resource allocation)

    Integration Points

    • Artifact Quality Markets (q-artifact-quality-markets): Market prices from quality
    markets become the basis for capital-backed positions
    • Market Participants (q-market-participants): Participant agents use capital to express
    their evaluations — replaces score-only signals with capital-backed signals
    • Crypto Wallets (q-crypto-wallets): Token ledger is the simulation layer that migrates
    to on-chain wallets
    • Economics (q-economics): Token economics provides the monetary framework
    • Reputation Staking (exch-qm-04-STAK): Staking uses tokens from the ledger, not just
    abstract believability points
    • Senate Proposals (senate_proposals.py): Allocation proposals backed by actual token
    budgets instead of hypothetical amounts
    • Resource Tracker (resource_tracker.py): Compute costs denominated in tokens

    Relationship to Existing Quests

    Existing QuestRelationship
    Market Participants (P80)Absorbed — participant agents use capital from this system
    Crypto Wallets (P75)Downstream — this builds the simulation layer; crypto is the migration
    Economics (P70)Extended — token economics operationalizes the economics framework
    Artifact Quality Markets (P92)Complementary — quality prices are what agents bid on
    Reputation Staking (exch-qm-04-STAK)Enhanced — staking uses real tokens, not just points

    Success Criteria

    ☐ Token ledger operational with double-entry accounting (no balance ever goes negative)
    ☐ Agents earn tokens from at least 5 productive action types
    ☐ Agents can place capital-backed bids on artifacts
    ☐ LMSR market maker provides continuous liquidity for all listed artifacts
    ☐ Portfolio tracking shows P&L, exposure, and Sharpe-like ratio per agent
    ☐ Settlement resolves >90% of positions within 24h of lifecycle transition
    ☐ Capital-weighted allocation demonstrably directs compute to high-demand areas
    ☐ Ledger format validated as compatible with EVM-style transaction model

    Work Log

    2026-04-06 — exch-cm-01-LEDG: Token ledger with double-entry accounting

    Implemented:

    • token_ledger.py — core double-entry accounting module:
    - create_account(agent_id, initial_balance) — initialize agent wallet (1000 tokens default)
    - transfer(from_id, to_id, amount, reason, ...) — atomic double-entry transfer; from_account='system' = mint, to_account='system' = burn; BEGIN IMMEDIATE for ACID guarantees; balance never goes negative
    - mint(to_id, amount, reason, ...) — convenience wrapper for system → account
    - burn(from_id, amount, reason, ...) — convenience wrapper for account → system
    - get_balance(agent_id) — current balance query
    - get_account(agent_id) — full account details (balance, total_earned, total_spent, total_staked)
    - get_statement(agent_id, since, limit) — transaction history, ordered newest first
    - get_total_supply() — economy-wide stats: supply, minted, burned, avg balance, top holders
    - seed_initial_accounts() — seeds all agents from actor_reputation + standard personas with 1000 tokens (idempotent)
    - ensure_schema() — creates tables on import (idempotent)
    - DB path resolved via os.path.abspath(__file__) — works from any working directory

    • api.py — startup schemaCREATE TABLE IF NOT EXISTS token_accounts and token_ledger added to startup init block for fresh-deploy idempotency
    • api.py — REST API (7 new endpoints under /api/ledger/):
    - GET /api/ledger/supply — total supply stats
    - GET /api/ledger/accounts/{id} — account balance and details
    - POST /api/ledger/accounts/{id} — create account
    - GET /api/ledger/accounts/{id}/statement — transaction history
    - POST /api/ledger/mint — mint tokens
    - POST /api/ledger/burn — burn tokens
    - POST /api/ledger/transfer — transfer with double-entry
    - POST /api/ledger/seed — seed all agents

    • GET /exchange/ledger — dashboard page showing:
    - Supply stats (total, accounts, minted, burned, avg balance, tx count)
    - Accounts table (balance, earned, spent, staked)
    - Reason breakdown (mint/earn/spend paths)
    - Recent transactions with type badges (MINT/BURN/XFER) and balance-after columns

    Verified: Functional tests confirm mint → transfer → burn → balance consistency with ACID double-entry semantics.

    Sibling Tasks in Quest (Capital Markets) ↗