ENERGY DePIN and COLLECTIVE SELF-CONSUMPTION SOLANA SPL and TOKEN-2022 ED25519 VERIFIED TELEMETRY

Solana Solar and EV Grid: Localized DePIN Micro-Energy Grid

Decentralized energy sharing network implementing virtual Collective Self-Consumption for Local Energy Communities (LEC). Matches rooftop solar surplus to nearby EV charging load over the public DSO distribution feeder every ~5 seconds, pricing trades at a community mid-rate with micro-cent protocol fees, high-speed time-series integration in QuestDB, and cryptographically verified on-chain settlements.

~5 sec
Settlement Cadence
0.1¢ / kWh
Protocol Fee (~$0.001)
100% Ed25519
Hardware Signed Wire
SHA-256
Interval Proof Hash

Closing the 23¢ Street-Level Spread

Rooftop solar and electric vehicle chargers already sit on the exact same low-voltage public feeder. Physics mixes their electrons instantly. Billing, however, is structurally broken:

  • Feed-in Tariff (FiT): The utility purchases rooftop solar surplus for a paltry ~5¢/kWh.
  • Retail Grid Import: Three doors down, an EV owner charges at the standard retail utility rate of ~28¢/kWh.
  • The 23¢ Middleman Gap: The retail utility captures the full spread while the distribution wires did no extra work.
  • The DePIN Solution: Software acts as a virtual billing overlay. Neighbors trade coincident kWh at a 15¢ community mid-rate. The producer earns 3x more; the EV driver pays nearly half. The network takes a tiny 0.1¢/kWh protocol fee.
Commercial Settlement Rule:
// Neighbors clear mid-rate; protocol never skims the spread
Producer Credit = Quantity × $0.150
Consumer Debit = Quantity × ($0.150 + $0.001)
Residual Export = Surplus × $0.050 (Utility FiT)
Residual Import = Deficit × $0.280 (Utility Retail)

Regulatory and Physical Realities

Unlike theoretical microgrid science-fiction, this platform does not dig private trenches or string rogue wires between rooftops. It operates directly under established Collective Self-Consumption frameworks (EU Renewable Energy Directive RED II, UK Local Energy Markets, Australian Virtual Energy Networks, Swiss LEGs):

Public Grid Stays in Place: The Distribution System Operator (DSO) remains responsible for physical power delivery, frequency stability, and wire maintenance.
Pure Roles, No Invented Energy: Solar meters are strictly registered as PRODUCER (injection only). EV chargers are strictly registered as CONSUMER (load only). The matcher never allows a device to synthesize opposite flows.
Utility Residual is First-Class: Any energy not matched in the 5-second interval automatically settles against existing utility tariffs. Leftover export is credited at FiT; leftover import is billed at retail.

Event-Driven Architecture and Data Pipeline

The system separates high-frequency physical telemetry from financial settlement. Watts stream into a persistent time-series engine, while 5-second window settlements and cryptographic proofs anchor onto the Solana ledger.

+----------------------------------------------------------------------------------------------------+
|                     PHYSICAL ASSETS and EDGE TELEMETRY LAYER                                       |
|  [Rooftop PV Meter]          [EV Charger Load Meter]          [Lab Modbus TCP Meter HR0-3]         |
|  (Ed25519 Private Key)       (Ed25519 Private Key)            (Multi-Meter Python Bridge / ESP32)  |
+----------------------------------------------------------------------------------------------------+
                                       │
                   Ed25519 Signed Canonical Envelopes
                   telemetry.energy.{region_id}.{meter_id}
                                       │
+----------------------------------------------------------------------------------------------------+
|                     EVENT BUS and INGESTION PIPELINE (NATS JetStream)                              |
|  Stream: telemetry_stream | Subject: telemetry.energy.*.* | Durable Consumer: questdb_ingestors    |
|  - Drops unverified serials and role mismatches (PRODUCER cannot draw, CONSUMER cannot inject)     |
+----------------------------------------------------------------------------------------------------+
                 │                                                      │
     ILP Stream  │                                        EventSource   │  Auth Ticket Check
     Port 9009   │                                       Port 8001      │
+-----------------------------------+             +--------------------------------------------------+
| TIME-SERIES ENGINE (QuestDB)      |             | SSE GATEWAY (services/sse_gateway)               |
| - High-freq sample ingestion      |             | - Live push of real-time watts to browser        |
| - Symbols: meter_id, region, role |             | - Zero credentials exposed in frontend           |
| - Columns: kw_generated, kw_cons  |             +--------------------------------------------------+
+-----------------------------------+                                    │
                 │                                                       │
     Window Integral Queries                                             │
     (kWh += kW * dt / 3600)                              +------------------------------------------+
                 │                                        | WEB CLIENT and OPERATOR NOC              |
                 │                                        | - Leaflet/MapLibre Neighborhood Map      |
+----------------------------------------------------+    | - Real-time generation / consumption SVG |
| SETTLEMENT DAEMON (Every ~5s per Region)           |    | - Meter provisioning and staff verify    |
| 1. Reads unpaid energy past settlement cursor      |    | - Payout audit log and interval proofs   |
| 2. Greedy matching: Hungry EV loads first          |    +------------------------------------------+
| 3. Haversine distance ranking (within 8km radius)  |                             │
| 4. Canonical SHA-256 Interval Energy Proof         |                             │ Django ORM
| 5. Dual Ledger Execution:                          |                             │
|    - Emulator: Redis balances and split payout     |                             │
|    - Live Solana: SPL transfer_checked + Anchor    |      +------------------------------------------+
| 6. Residual clearing: FiT export and Retail import |──-───| RELATIONAL STORE (PostgreSQL)            |
+----------------------------------------------------+      | - SmartMeter registry and credentials    |
                                                            | - Regions, Currencies and Tariffs        |
                                                            | - EnergyTrades and OnChainPayouts        |
                                                            +------------------------------------------+

Microservices and Infrastructure Matrix

Service / Container Protocol / Port Core Responsibility Scaling and Reliability Strategy
web HTTP 8000 (ASGI) Django 5 ASGI + Uvicorn: admin, authentication, hardware provisioning, Leaflet NOC, payouts log. Horizontal stateless replicas behind Nginx load balancer; PostgreSQL connection pooling.
sse_gateway HTTP 8001 (SSE) Standalone ASGI EventSource server streaming live meter readings directly to the browser. Subscribes to NATS; validates short-lived Django auth tickets; zero NATS credentials in client.
nats TCP 4222 / 8222 NATS JetStream 2.10 message bus buffering encrypted telemetry subjects (telemetry.energy.*.*). File-backed persistent stream telemetry_stream; handles broker reboots with zero lost samples.
telemetry_ingestion Internal Worker Asyncio JetStream subscriber verifying Ed25519 signatures and pushing Influx Line Protocol (ILP) rows. Durable consumer questdb_ingestors; auto-scaled via KEDA based on JetStream queue lag.
questdb TCP 9009 (ILP), 9000 (SQL) Columnar time-series store ingesting sub-second watts and calculating rectangle window integrals. High-throughput memory-mapped append log; native SQL window queries partitioned by day.
settlement_worker Internal Daemon 5-second matching daemon: pulls new kWh, runs greedy nearest-neighbor matching, signs payouts. Redis distributed locks (settle_lock:region:{slug}) preventing duplicate payout execution.
redis TCP 6379 Low-latency cache for meter metadata, settlement cursors, locks, and lab token ledger emulator. In-memory key-value store with AOF persistence; sub-millisecond cursor updates.
modbus_bridge TCP 1502 / Host Multi-meter Python gateway polling Modbus TCP holding registers (HR0-3) and publishing signed envelopes. Translates industrial physical meter registers into JSON Ed25519 envelopes on field gateways.

Core Implementation Deep Dive

Explore the primary algorithms powering the platform: Ed25519 signature enforcement, strict role physical sanitization, time-weighted rectangle energy integration, greedy nearest-neighbor matching, and canonical SHA-256 proofs.

1. Ed25519 Signature and Role Check
Python
def canonical_payload_bytes(payload: dict) -> bytes:
    # Deterministic sorting ensures signature matches across devices
    return json.dumps(payload, sort_keys=True).encode("utf-8")

def verify_envelope(payload: dict, sig_str: str, pubkey_str: str) -> bool:
    try:
        signature = Signature.from_string(str(sig_str or ""))
        pubkey = Pubkey.from_string(str(pubkey_str or ""))
        return signature.verify(pubkey, canonical_payload_bytes(payload))
    except Exception:
        return False

def power_columns_for_role(role: str, payload: dict) -> tuple[float, float]:
    """Persist only the physical flow matching verified hardware role."""
    gen = max(0.0, float(payload.get("kw_generated") or 0))
    con = max(0.0, float(payload.get("kw_consumed") or 0))
    if role == "CONSUMER":
        return 0.0, con  # Consumer cannot inject watts
    return gen, 0.0      # Producer cannot consume watts
2. Rectangle Energy Integration
Python
def calculate_unpaid_kwh(samples: list[tuple], max_gap_sec: float = 30.0) -> Decimal:
    """Integrate power over time (rectangle rule).
    Caps sample gaps to prevent offline meters from claiming false energy.
    """
    total_kwh = Decimal("0.0")
    if len(samples) < 2:
        return total_kwh

    for i in range(1, len(samples)):
        ts_prev, kw_prev = samples[i - 1]
        ts_curr, kw_curr = samples[i]

        dt = (ts_curr - ts_prev).total_seconds()
        if 0 < dt <= max_gap_sec:
            # Energy = Average Power (kW) * Time (hours)
            avg_kw = Decimal(str((kw_prev + kw_curr) / 2.0))
            kwh = avg_kw * (Decimal(str(dt)) / Decimal("3600.0"))
            total_kwh += kwh

    return total_kwh
3. Greedy Haversine Matcher
Python
def match_local_energy(offers: list[EnergyOffer], radius_m: float = 8000.0) -> list[EnergyFill]:
    producers = [o for o in offers if o.role == "PRODUCER" and o.remaining > 0]
    consumers = [o for o in offers if o.role == "CONSUMER" and o.remaining > 0]
    consumers.sort(key=lambda c: c.remaining, reverse=True)  # Hungry chargers first
    fills = []

    for consumer in consumers:
        if consumer.remaining <= 0:
            continue
        # Rank producers by Haversine distance if coordinates exist
        eligible = []
        for prod in producers:
            if prod.remaining <= 0:
                continue
            dist = haversine_m(consumer.lat, consumer.lng, prod.lat, prod.lng) if consumer.lat and prod.lat else 0.0
            if radius_m is None or dist <= radius_m:
                eligible.append((dist, prod))
        eligible.sort(key=lambda x: x[0])

        for dist, prod in eligible:
            fill_kwh = min(consumer.remaining, prod.remaining)
            consumer.remaining -= fill_kwh
            prod.remaining -= fill_kwh
            fills.append(build_fill(prod, consumer, fill_kwh, dist))
    return fills
4. SHA-256 Proof and Token Split
Python
def energy_proof_hash(prod_id: str, cons_id: str, kwh: Decimal, start: str, end: str) -> str:
    """Canonical SHA-256 of matched interval bound to on-chain payment."""
    canonical_json = json.dumps({
        "consumer": str(cons_id),
        "interval_end": str(end),
        "interval_start": str(start),
        "kwh": format(kwh, "f"),
        "producer": str(prod_id),
    }, separators=(",", ":"), sort_keys=True)
    return hashlib.sha256(canonical_json.encode("utf-8")).hexdigest()

def execute_split_payout(consumer_wallet: str, producer_wallet: str, mid_rate_amount: Decimal, fee: Decimal):
    # Consumer wallet executes transfer split: producer receives mid-rate, treasury receives 0.1¢ fee
    return transfer_token_split(
        source=consumer_wallet,
        dest_producer=producer_wallet,
        amount_producer=mid_rate_amount,
        dest_treasury=TREASURY_PUBKEY,
        amount_treasury=fee
    )