Build a Confidential Energy Flexibility Settlement Network with Oasis Sapphire and ROFL
Introduction
Electricity demand is not constant. During periods of extreme heat, cold weather, or unexpected grid congestion, energy providers may need businesses and large consumers to temporarily reduce their electricity usage. This is known as demand response.
An energy provider might offer a commercial building a financial incentive to reduce its consumption by 200 kWh during a specified peak-demand window.
The idea sounds simple:
A building agrees to reduce electricity consumption. Its smart meter records actual consumption. A verification service checks whether the reduction happened. The building receives a payment.
But there is a significant data problem. Electricity consumption can reveal information about a business that it would rather not publish:
- Operating hours and production schedules.
- Periods of unusually high or low activity.
- Equipment utilization.
- Occupancy patterns.
- Seasonal business activity.
- Operational capacity.
Putting all this information into a public blockchain application would be a poor design. At the same time, an energy provider needs to know that the reduction was genuine. Participants should not be able to invent meter readings, reuse old measurements, or claim the same flexibility reward multiple times.
This is where confidential computation becomes useful.
In this tutorial, we'll design GridFlex, a confidential demand-response settlement application using:
- Oasis Sapphire for confidential participant records, settlement rules, and private contract state.
- Oasis ROFL for off-chain meter-data processing and verification inside a Trusted Execution Environment.
- Solidity for campaign management, authorization, and settlement accounting.
- TypeScript for the processing service and application integration.
- Signed meter readings as the input evidence.
The objective is to create a system where participants can prove that they fulfilled an energy-reduction commitment without publishing their detailed consumption history.
This is an educational reference architecture. Actual electricity-market participation requires integration with approved meter-data providers, market operators, settlement systems, and applicable regulatory frameworks.
The Real-World Use Case: Rewarding Businesses for Reducing Electricity Demand
Imagine a regional energy provider running a peak-demand campaign. It invites 50 commercial buildings to participate. Each building agrees to reduce its electricity consumption during a specific time window. For example:
Participant Agreed reduction Reward rate Building A 200 kWh $0.18/kWh Building B 150 kWh $0.18/kWh Building C 300 kWh $0.18/kWh
The provider needs to calculate the actual reduction achieved by each participant. However, it does not need every participant's detailed electricity profile to be publicly accessible.
GridFlex separates the information into two categories.
Confidential information Participant identity. Baseline consumption. Meter readings. Agreed reduction targets. Individual reward calculations. Commercial settlement information.
Publicly verifiable information Campaign identifier. Campaign status. Authorized settlement commitment. Aggregate settlement amount, if the campaign chooses to disclose it. Settlement completion status.
The blockchain becomes the coordination and accounting layer, rather than a public database of electricity consumption.
Architecture: Separating Private Data from Public Settlement
The most important design decision is separating the confidential computation from the public settlement record. Sapphire manages confidential application state and contract execution. ROFL processes the meter data and evaluates whether a participant fulfilled the campaign conditions. The energy provider's existing payment infrastructure can then handle the actual payment.
System architecture flowchart TB A["Smart Meter / Meter Data Provider"] B["Signed Meter Readings"] C["ROFL Verification Worker"] D["Oasis Sapphire"] E["Campaign and Settlement Contract"] F["Energy Provider Payment System"] G["Participant Dashboard"] A --> B B --> C C -->|"Authenticated result"| D D --> E E -->|"Authorized settlement instruction"| F G <-->|"Encrypted interactions"| D
Each component has a specific responsibility.
Smart meter or data provider Produces signed electricity-consumption readings. The system must establish which meter identities and signing keys are trusted.
ROFL verification worker Validates signatures, checks timestamps, detects duplicate readings, calculates consumption reductions, and prepares settlement results.
Sapphire contract Stores confidential campaign state, manages participant permissions, and enforces settlement rules.
Payment system Executes the actual payment through the provider's chosen financial infrastructure. The payment rail is deliberately separate. A confidential settlement record does not automatically make an external bank transfer private or guarantee that payment was completed.
Understanding the Demand-Response Calculation
Before writing contracts, we need to define what counts as successful performance. A demand-response campaign generally compares actual electricity consumption against an agreed baseline. For this tutorial, we'll use a simplified baseline model.
Suppose a building has: Baseline consumption: 1,000 kWh. Actual consumption during the campaign: 760 kWh. Agreed reduction: 200 kWh.
The achieved reduction is: Achieved Reduction = Baseline - Actual Consumption Achieved Reduction = 1,000 - 760 Achieved Reduction = 240 kWh
The participant achieved 240 kWh of reduction against a 200 kWh commitment.
The reward is: Reward = Eligible Reduction × Reward Rate Reward = 200 × $0.18 Reward = $36
Why use the eligible reduction rather than automatically rewarding all 240 kWh? Because the campaign has a maximum agreed commitment. A production system could introduce overperformance bonuses, minimum thresholds, penalties, or other market-specific rules, but these must be explicitly defined.
Our simplified implementation caps the eligible reduction at the participant's commitment.
The baseline calculation is also simplified. Real demand-response programs may require weather adjustments, historical comparison days, operational adjustments, independent baseline methodologies, and dispute resolution.
Repository Structure
We'll organize the project as a monorepo.
gridflex/ │
├── contracts/ │ ├── src/ │ │ ├── GridFlex.sol │ │ └── interfaces/ │ │ └── ISettlementVerifier.sol │ │ │ ├── test/ │ │ ├── GridFlex.test.ts │ │ └── SettlementInvariants.test.ts │ │ │ ├── ignition/ │ │ └── modules/ │ │ └── GridFlex.ts │ │ │ └── hardhat.config.ts │ ├── rofl/ │ ├── app/ │ │ ├── src/ │ │ │ ├── index.ts │ │ │ ├── meterVerifier.ts │ │ │ ├── baseline.ts │ │ │ ├── settlement.ts │ │ │ └── sapphireClient.ts │ │ │ │ │ ├── Dockerfile │ └── package.json │ │ │ ├── compose.yaml │ └── rofl.yaml │ ├── frontend/ │ ├── src/ │ │ ├── components/ │ │ ├── services/ │ │ └── pages/ │ │ │ └── package.json │ ├── scripts/ │ ├── createCampaign.ts │ └── registerParticipant.ts │ ├── diagrams/ │ ├── architecture.mmd │ └── settlement-flow.mmd │ ├── test-data/ │ ├── sample-readings.json │ └── sample-campaign.json │ ├── .env.example ├── package.json └── README.md
The separation matters. The contract should not become a large data-processing engine. The ROFL application handles computational work, while the contract enforces the rules that determine whether a settlement can be accepted.
Never commit meter-provider credentials, private signing keys, or real customer consumption data to this repository.
Designing the Campaign Lifecycle
A campaign needs a predictable lifecycle.
stateDiagram-v2 [*] --> Draft Draft --> Active Active --> MeasurementPending MeasurementPending --> VerificationPending VerificationPending --> Approved VerificationPending --> Disputed Disputed --> VerificationPending Approved --> Settled Draft --> Cancelled Active --> Cancelled
The important transitions are:
Draft to Active The energy provider defines the campaign period, reward rate, and participant commitments.
Active to MeasurementPending The measurement window has ended. New readings for that campaign are no longer accepted unless an explicitly authorized correction process exists.
MeasurementPending to VerificationPending The ROFL worker processes the submitted meter data and prepares a result.
VerificationPending to Approved The authorized verifier submits a valid result that satisfies the campaign rules.
Approved to Settled The settlement system records that the payment process has completed.
A critical detail: approving a reward and actually paying it are different events. The application must not mark a participant as paid merely because a reward calculation succeeded.
Implementing the Sapphire Contract
Let's begin with the core Solidity contract. The contract manages campaign commitments and participant settlement records. It does not store raw meter readings. Those remain within the confidential processing workflow.
The following is an illustrative contract skeleton. It demonstrates the state machine and settlement invariants, but production deployment requires complete ROFL authentication, role management, dispute handling, and payment integration.
GridFlex.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; contract GridFlex { enum CampaignStatus { Draft, Active, MeasurementPending, VerificationPending, Approved, Settled, Cancelled } struct Campaign { address operator; uint256 startTime; uint256 endTime; uint256 rewardRate; CampaignStatus status; uint256 participantCount; } struct Participant { bytes32 commitment; uint256 committedReduction; uint256 eligibleReduction; uint256 reward; bool registered; bool verified; bool settled; } mapping(bytes32 => Campaign) public campaigns; mapping( bytes32 => mapping(address => Participant) ) private participants; address public verifier; event CampaignCreated(bytes32 indexed campaignId); event CampaignActivated(bytes32 indexed campaignId); event ParticipantRegistered(bytes32 indexed campaignId); event SettlementApproved(bytes32 indexed campaignId); event ParticipantSettled(bytes32 indexed campaignId); modifier onlyVerifier() { require(msg.sender == verifier, "Not verifier"); _; } constructor(address initialVerifier) { require(initialVerifier != address(0), "Invalid verifier"); verifier = initialVerifier; } function createCampaign( bytes32 campaignId, uint256 startTime, uint256 endTime, uint256 rewardRate ) external { require( campaigns[campaignId].operator == address(0), "Campaign exists" ); require(endTime > startTime, "Invalid period"); require(rewardRate > 0, "Invalid reward rate"); campaigns[campaignId] = Campaign({ operator: msg.sender, startTime: startTime, endTime: endTime, rewardRate: rewardRate, status: CampaignStatus.Draft, participantCount: 0 }); emit CampaignCreated(campaignId); } function activateCampaign( bytes32 campaignId ) external { Campaign storage campaign = campaigns[campaignId]; require(msg.sender == campaign.operator, "Not operator"); require( campaign.status == CampaignStatus.Draft, "Invalid status" ); campaign.status = CampaignStatus.Active; emit CampaignActivated(campaignId); } function registerParticipant( bytes32 campaignId, bytes32 commitment, uint256 committedReduction ) external { Campaign storage campaign = campaigns[campaignId]; require( campaign.status == CampaignStatus.Active, "Campaign inactive" ); require(commitment != bytes32(0), "Empty commitment"); require(committedReduction > 0, "Invalid commitment"); Participant storage participant = participants[campaignId][msg.sender]; require(!participant.registered, "Already registered"); participant.commitment = commitment; participant.committedReduction = committedReduction; participant.registered = true; campaign.participantCount++; emit ParticipantRegistered(campaignId); } function closeMeasurement( bytes32 campaignId ) external { Campaign storage campaign = campaigns[campaignId]; require(msg.sender == campaign.operator, "Not operator"); require( campaign.status == CampaignStatus.Active, "Invalid status" ); require(block.timestamp >= campaign.endTime, "Too early"); campaign.status = CampaignStatus.MeasurementPending; } function submitVerifiedResult( bytes32 campaignId, address participantAddress, uint256 eligibleReduction, uint256 reward ) external onlyVerifier { Campaign storage campaign = campaigns[campaignId]; require( campaign.status == CampaignStatus.MeasurementPending || campaign.status == CampaignStatus.VerificationPending, "Invalid status" ); Participant storage participant = participants[campaignId][participantAddress]; require(participant.registered, "Unknown participant"); require(!participant.verified, "Already verified"); require( eligibleReduction <= participant.committedReduction, "Exceeds commitment" ); require( reward == eligibleReduction * campaign.rewardRate, "Invalid reward" ); participant.eligibleReduction = eligibleReduction; participant.reward = reward; participant.verified = true; campaign.status = CampaignStatus.VerificationPending; } function approveSettlement( bytes32 campaignId ) external { Campaign storage campaign = campaigns[campaignId]; require(msg.sender == campaign.operator, "Not operator"); require( campaign.status == CampaignStatus.VerificationPending, "Invalid status" ); campaign.status = CampaignStatus.Approved; emit SettlementApproved(campaignId); } function markSettled( bytes32 campaignId, address participantAddress ) external onlyVerifier { Campaign storage campaign = campaigns[campaignId]; require( campaign.status == CampaignStatus.Approved, "Not approved" ); Participant storage participant = participants[campaignId][participantAddress]; require(participant.verified, "Not verified"); require(!participant.settled, "Already settled"); participant.settled = true; emit P
Comments
No comments yet. Start the discussion.