myco-bonding-curve/docs/13-crdt-primitives.md

20 KiB

13: CRDT-Native Primitives

How Balancer, Gyroscope, and CoW Swap Apply to CRDT Tokens

The existing MYCO system uses Automerge CRDTs for off-chain payment state with BFT consensus (2f+1) and Braid-HTTP peer sync. This document maps DeFi primitives to that architecture, identifying which work natively in CRDT contexts, which activate at the chain boundary, and which enable entirely new hybrid patterns.


The Two Token Domains

┌─────────────────────────────────────┐     ┌──────────────────────────────┐
│         CRDT Domain                 │     │      Blockchain Domain       │
│                                     │     │                              │
│  Automerge documents                │     │  EVM state                   │
│  BFT 2f+1 consensus                │     │  Global ordering             │
│  Braid-HTTP sync                    │     │  Atomic settlement           │
│  Ed25519 signatures                 │     │  ECDSA signatures            │
│  Eventual consistency               │     │  Immediate finality          │
│                                     │     │                              │
│  Properties:                        │     │  Properties:                 │
│  - Commutative operations           │     │  - Sequential execution      │
│  - Merge-convergent state           │     │  - Single canonical state    │
│  - Partition-tolerant               │     │  - Atomic transactions       │
│  - Fast (~1-3s BFT finality)        │     │  - Slow (~12s+ finality)     │
└──────────────────┬──────────────────┘     └──────────────┬───────────────┘
                   │                                       │
                   └───────────┬───────────────────────────┘
                               │
                    ┌──────────▼──────────┐
                    │   Bridge Layer       │
                    │                      │
                    │  StateCommitment.sol  │
                    │  USDCEscrow          │
                    │  RollupAggregator    │
                    │  EscrowWatcher       │
                    └─────────────────────┘

The key insight: most DeFi primitives assume blockchain properties (global ordering, atomic state). But several can be decomposed into CRDT-compatible operations that work natively in the off-chain domain.


Tier 1: CRDT-Native (No Blockchain Required)

These primitives work entirely within the Automerge/BFT layer. Each node computes them locally from its own state — no coordination beyond normal CRDT sync.

1.1 Flow Dampening (Gyroscope)

Why it works as a CRDT: EWMA (exponential weighted moving average) is a pure function of timestamps and amounts. Each node independently tracks outflow per peer.

CRDT implementation:

Per-peer state (stored in Automerge document):
  flow_tracker: {
    current_flow: float       // EWMA of recent outflows
    last_update: timestamp
    memory: 0.999             // decay constant
    threshold: 0.1            // fraction of balance triggering penalty
  }

On each transfer/redeem from peer P:
  dt = now - last_update
  current_flow = current_flow * memory^dt + amount
  penalty = max(1.0, (current_flow / (threshold * total_balance))^2)

Use cases in CRDT domain:

  • Rate-limit aggressive withdrawals from the CRDT balance layer before they hit the rollup
  • Penalize peers drawing down mutual credit lines too fast
  • Anti-drain protection: if a compromised key starts mass-transferring, flow dampening buys time for BFT nodes to detect and halt

Merge semantics: Each BFT node independently tracks flow. On Automerge merge, take the maximum flow value (conservative — more protection). This is a valid CRDT join operation (max is commutative, associative, idempotent).

1.2 Commitment Issuance — Labor Attestations as CRDTs

Why it works: Labor attestations are append-only. The set of "Alice contributed 5 hours of code review on day 7" entries is a G-Set (grow-only set). Merge = union. No conflicts possible.

CRDT implementation:

Automerge document extension:
  labor_attestations: Map<contributor_address, {
    entries: [{ type, units, timestamp, attester, signature }],
    claimed_up_to: index,    // LWW-Register — last claimed index
    total_minted: float,     // monotonically increasing counter
  }>

Properties:

  • Attestations are immutable signed entries — adding one never conflicts with adding another
  • claimed_up_to uses last-writer-wins (Automerge default for scalar fields)
  • total_minted is a monotone counter — can only increase
  • Rate limits and cooldowns are enforced by BFT validation before committing to the document

Token flow:

Attestation created (off-chain, signed by attester)
    → Submitted to BFT consensus
    → Validated: rate limit, cooldown, contribution type
    → Appended to Automerge document
    → Tokens minted in CRDT balance (supply increases)
    → Eventually committed on-chain via RollupAggregator

This is the cleanest CRDT-native primitive: the entire lifecycle from attestation to minting happens off-chain with no blockchain dependency.

1.3 Dynamic Weights / LBP Schedules (Balancer)

Why it works: Time-parameterized pricing is a pure function. Given a shared start time and schedule, every node computes the same weight at the same moment.

CRDT implementation:

weight_schedule: {
  start_weights: [0.9, 0.1],     // immutable at creation
  end_weights: [0.5, 0.5],       // immutable at creation
  start_time: timestamp,          // immutable at creation
  end_time: timestamp,            // immutable at creation
}

// Any node computes current weight:
function current_weight(schedule, t, asset_index):
  progress = clamp((t - start_time) / (end_time - start_time), 0, 1)
  return start_weights[i] + progress * (end_weights[i] - start_weights[i])

Use cases:

  • CRDT token launch pricing: New token available via CRDT transfers at LBP-style declining prices. Early buyers pay more, discouraging bots. No AMM pool needed.
  • Subscription tier transitions: Gradually shift the token/commitment ratio over a governance period
  • Trust bootstrapping: New BFT node enters with high-collateral weights that decay toward symmetric as it proves reliability

No merge conflicts: The schedule is immutable once created. Only the creation requires consensus (BFT 2f+1). Evaluation is local.

1.4 QuantAMM-Style Oracle Weights (Balancer)

Why it works: Each node has local observations about peer behavior. Weight adjustments based on these observations need no coordination.

CRDT implementation:

Per-peer metrics (local to each BFT node):
  peer_metrics: Map<node_id, {
    uptime_ewma: float,           // exponential moving average of availability
    latency_ewma: float,          // response time
    delivery_ratio: float,        // fulfilled / promised
    last_observed: timestamp,
  }>

Weight adjustment rule:
  // Momentum: shift weight toward peers with improving metrics
  peer_weight[i] *= (1 + momentum_factor * (current_metric - ewma_metric))
  normalize(peer_weights)

Use cases:

  • Automatically route CRDT sync through more reliable peers
  • Adjust credit limits based on observed peer solvency
  • Shift resource allocation weights toward better-performing validators

Tier 2: CoW-for-CRDTs (The Major Opportunity)

CoW Protocol's architecture is remarkably CRDT-compatible. The core concepts — intents, batch auctions, coincidence of wants — decompose into append-only sets and commutative matching operations.

2.1 Intents as CRDT Documents

The insight: A signed intent ("I want to sell 100 CRDT-USDC for at least 95 MYCO") is an immutable, self-contained document. It can be replicated, forwarded, and stored across any number of nodes without coordination. It is naturally a member of a G-Set.

CRDT implementation:

Automerge document extension:
  pending_intents: Map<intent_id, {
    maker: address,
    sell_token: token_address,
    sell_amount: float,
    buy_token: token_address,
    min_buy_amount: float,       // limit price
    valid_until: timestamp,      // natural tombstone
    signature: bytes,            // Ed25519 sig over canonical fields
    status: "open" | "filled" | "expired",  // LWW-Register
  }>

Properties:

  • Adding an intent is conflict-free (G-Set append)
  • Intents expire via valid_until — natural garbage collection
  • Status transitions are monotone: open → filled or open → expired (never backwards)
  • The maker's Ed25519 signature proves authorization — no on-chain tx needed
  • Double-fill prevention: the BFT layer validates that maker.balance >= sell_amount before accepting the intent, and status is set to filled atomically at fill time via BFT consensus

2.2 Coincidence of Wants in the CRDT Layer

The insight: CoW matching is a commutative, associative operation on a set of intents. Finding that intent A and intent B are complementary produces the same match regardless of which is processed first. This is structurally CRDT.

Implementation:

// CoW matching runs on each BFT node independently
function find_cows(intents: Intent[]) -> Match[]:
  matches = []
  for each pair (A, B) where A.sell_token == B.buy_token
                          and B.sell_token == A.buy_token:
    // Check price compatibility
    if A.sell_amount / A.min_buy_amount <= B.min_buy_amount / B.sell_amount:
      // Prices overlap — CoW possible
      // Clearing price = geometric mean of limits (fair midpoint)
      matches.append(Match(A, B, clearing_price))
  return matches

Why this matters for MYCO: Currently, curve_buy and curve_sell operations go through the bonding curve one-at-a-time. With CoW matching:

  1. A buyer wanting MYCO and a seller wanting USDC can match directly in the CRDT layer
  2. No bonding curve invocation needed — zero price impact for matched pairs
  3. Only unmatched remainder hits the curve (on-chain settlement via rollup)
  4. This is exactly what BondingCurveAdapter.sol + MycoConditionalOrder.sol do on-chain — but moved off-chain into the CRDT domain

2.3 Batch Settlement at Commitment Time

The insight: The RollupAggregator already batches CRDT transactions every 30 seconds. This is structurally identical to CoW Protocol's batch auction window.

Proposed architecture:

Current flow:
  CRDT ops → BFT consensus → Automerge doc → RollupAggregator → StateCommitment.sol

Enhanced flow:
  CRDT ops → BFT consensus → Automerge doc
       ↓
  [Intent Collector — G-Set of open intents]
       ↓
  [CoW Matcher — find peer-to-peer matches]
       ↓
  [Solver — route unmatched orders through curve]
       ↓
  [Batch Settlement — single rollup tx]
       ↓
  StateCommitment.sol + MycoBondingCurve.sol

Benefits:

  • Matched CoW pairs settle entirely in the CRDT layer — no gas cost
  • Only net curve interactions (unmatched orders) go on-chain
  • Uniform clearing prices within each batch — MEV-resistant by construction
  • The BFT consensus nodes can act as competing solvers

2.4 BFT Nodes as Solvers

The insight: The existing BFT validator set (4 nodes, 2f+1 threshold) can double as CoW solvers. Each node independently proposes a settlement for the current batch, and the BFT consensus selects the best one.

Solver competition within BFT:
  1. Each node collects open intents from Automerge document
  2. Each node independently runs CoW matching + surplus optimization
  3. Each node proposes a settlement (which intents to fill, at what prices)
  4. BFT consensus selects the proposal with maximum total surplus
  5. Winning settlement is committed to Automerge document
  6. Net on-chain operations batched by RollupAggregator

This eliminates the need for a separate solver infrastructure — the BFT layer already has the coordination primitives.


Tier 3: Bridge Primitives (Activate at CRDT→Chain Boundary)

These primitives require blockchain state but can be parameterized by CRDT-layer data.

3.1 P-AMM Redemption at Withdrawal Time

When a user calls USDCEscrow.withdraw(), the redemption rate should reflect the system's health. The P-AMM curve activates here:

CRDT-layer data (computed off-chain):
  - backing_ratio: total_reserve / total_supply (known from Automerge state)
  - flow_pressure: EWMA outflow (from flow dampening)

On-chain enforcement:
  - StateCommitment.sol stores the state root
  - Withdrawal processing checks:
    effective_rate = pamm_rate(backing_ratio) * flow_penalty(flow_pressure)
    usdc_out = myco_burned * effective_rate

Hybrid: The backing ratio is computed off-chain (CRDT state is the most current view), but enforced on-chain (StateCommitment verifies the state root covers the claimed ratio).

3.2 Reserve Tranching at Deposit/Withdrawal

The multi-vault reserve structure activates when CRDT tokens bridge to/from on-chain assets:

CRDT-layer: tracks which vaults hold which assets, target weights, deviations
On-chain: USDCEscrow holds actual USDC; future vaults hold ETH, DAI

At bridge time:
  - Deposit: optimal_deposit_split routes funds to underweight vaults
  - Withdrawal: optimal_withdrawal_split draws from overweight vaults
  - Safety checks: reject if any vault would exceed max deviation

3.3 Bonding Surface at Net Settlement

The N-dimensional ellipsoid surface activates only for net unmatched curve operations after CoW matching:

Batch settlement:
  1. CoW matcher fills 70% of orders peer-to-peer (no curve needed)
  2. Net remaining: +500 USDC buy, -200 MYCO sell
  3. These net amounts hit MycoBondingCurve.sol on-chain
  4. Curve price reflects full reserve state (from StateCommitment)

This dramatically reduces on-chain curve interactions — most trades settle at peer-determined prices.


Tier 4: New Hybrid Patterns

Combining CRDT primitives with DeFi concepts enables patterns that don't exist in either domain alone.

4.1 Trust-Ratio-Driven P-AMM

Concept: Each peer has a local "backing ratio" computed from observed reliability. This ratio parameterizes a P-AMM-style curve for bilateral exchange terms.

peer_trust_ratio(P) = {
  delivered_value / promised_value          // resource delivery
  * uptime_fraction                         // availability
  * (1 - flow_penalty(recent_drawdown))     // not draining credit
}

exchange_rate(P) = pamm_curve(peer_trust_ratio(P))
  // trust ≥ 1.0 → par rate
  // trust < 1.0 → parabolic discount
  // trust ≪ 1.0 → floor rate (minimum viable exchange)

Properties: Graceful degradation (not binary trust/block), locally computed, no central credit bureau, automatic recovery as behavior improves.

4.2 CRDT Mutual Credit with Weighted Invariant Bounds

Concept: Bilateral credit lines between BFT nodes, constrained by a weighted-product-style invariant that prevents any single credit relationship from dominating.

For node N with credit lines to peers [P1, P2, P3]:
  credit_balances = [500, 300, 200]  // how much each peer owes N
  weights = [0.5, 0.3, 0.2]         // diversification targets

  invariant = prod(max(credit_i, epsilon) ^ weight_i)

  Constraint: invariant must stay above a floor value
  → prevents N from extending 90% of credit to one peer
  → automatically diversifies counterparty risk

No blockchain needed: Each node enforces its own invariant locally. The weighted product math from Balancer becomes a credit risk management tool rather than a swap pricing tool.

4.3 CRDT-Native Imbalance Fees

Concept: When CRDT token transfers skew the balance distribution across BFT nodes, apply surge fees to discourage further imbalance.

Per-node balance tracking:
  node_balances = {node_1: 5000, node_2: 3000, node_3: 8000, node_4: 4000}
  median = 4500
  imbalance = sum(|b_i - median|) / sum(b_i) = 0.30

If imbalance > threshold (0.2):
  surge_fee = base_fee + surge_rate * (imbalance - threshold)^2
  Apply to transfers that would increase imbalance
  Discount transfers that would decrease imbalance

Use case: Prevents liquidity concentration on a single BFT node, which would create a single point of failure.

4.4 Intent-Based Commitment Issuance

Concept: Combine CoW-style intents with commitment channels. A contributor publishes an intent: "I will deliver 10 hours of code review in exchange for 100 MYCO." This intent sits in the G-Set until an attester (DAO, oracle, or peer review) confirms delivery, triggering the mint.

commitment_intent: {
  contributor: address,
  contribution_type: "code",
  promised_units: 10.0,
  requested_tokens: 100.0,
  valid_until: timestamp,
  signature: bytes,
}

// Lifecycle:
open → attested (attester confirms delivery) → minted (tokens issued)
     → expired (if valid_until passes without attestation)

This makes labor markets CRDT-native: Offers and attestations propagate through the BFT network as CRDT documents. No blockchain interaction until the contributor wants to withdraw USDC.


Summary: What Goes Where

Primitive CRDT Domain Bridge Chain Domain
Flow dampening Primary Parameters Enforcement
Labor attestations Full lifecycle Rollup
Subscription tracking Full lifecycle Revenue to vault
Dynamic weights / LBP Full lifecycle
QuantAMM peer metrics Full lifecycle
CoW intent matching Primary Net settlement Unmatched orders
Batch auctions Primary Rollup batch Atomic settlement
Imbalance fees Primary
Trust-ratio P-AMM Primary
Weighted credit bounds Primary
P-AMM redemption Parameters Primary Enforcement
Reserve tranching Tracking Primary Vault management
Bonding surface Net orders Primary
Staking lockups Tracking Primary

Key takeaway: The majority of useful primitives can operate primarily in the CRDT domain. The blockchain becomes a settlement layer for net positions rather than the execution layer for every operation.


Implementation Priority

  1. Flow dampening in Automerge — immediate value, protects against drain attacks
  2. Intent G-Set + CoW matching — biggest efficiency gain, replaces per-trade curve calls
  3. Labor attestation lifecycle — commitment issuance fully off-chain
  4. LBP-style weight schedules — token launch pricing without on-chain AMM
  5. Trust-ratio P-AMM — graceful peer trust degradation
  6. Batch settlement integration — connect CoW matcher to RollupAggregator
  7. Weighted credit invariants — counterparty risk management

Implementation

  • src/crdt/flow_dampening.py — Per-peer EWMA flow tracking with CRDT merge semantics
  • src/crdt/intent_matching.py — G-Set intent store + CoW matching algorithm
  • src/crdt/labor_crdt.py — Attestation lifecycle as append-only CRDT
  • src/crdt/trust_pamm.py — Trust-ratio-driven exchange rate curve
  • src/crdt/credit_invariant.py — Weighted-product credit bounds
  • src/crdt/batch_settlement.py — Batch solver + net position calculator