A comprehensive Clarity smart contract for decentralized energy grid management, enabling peer-to-peer energy trading, real-time grid monitoring, and efficient energy distribution.
This smart contract provides a complete infrastructure for managing a decentralized smart grid, allowing energy producers, consumers, and storage facilities to interact transparently on the blockchain. The system includes dynamic pricing, emergency protocols, and comprehensive metrics tracking.
- Energy Producer Registration: Register as an energy producer with specified capacity and energy type (solar, wind, hydro, nuclear, geothermal, biomass, natural-gas)
- Consumer Management: Register consumers with consumption limits and balance tracking
- Energy Storage: Support for battery/storage systems with configurable charge/discharge rates
- Production Reporting: Real-time tracking of energy production from registered producers
- Consumption Management: Controlled energy consumption with dynamic pricing
- Grid Load Monitoring: Real-time monitoring of total grid capacity and current load
- Peer-to-Peer Trading: Direct energy trading between producers and consumers
- Trade Creation: Producers can create trade offers with specified amount and price
- Trade Completion: Consumers can accept and complete trades with balance verification
- Trade History: Complete audit trail of all energy transactions
- Load-Based Pricing: Prices adjust automatically based on grid utilization
- Emergency Mode: 3x price multiplier during grid emergencies
- Base Price Management: Grid operator can adjust base energy prices
- Transparent Calculations: All pricing logic is on-chain and auditable
- Capacity Management: Track total grid capacity vs. current load
- Utilization Metrics: Calculate grid utilization percentage in real-time
- Performance Tracking: Historical metrics including production, consumption, peak load, and efficiency
- Reputation System: Track producer reliability with reputation scores (0-100)
- Role-Based Access: Grid operator role with administrative privileges
- Active Status Checks: Ensure only active participants can transact
- Balance Verification: Prevent overdraft with comprehensive balance checks
- Capacity Limits: Enforce production and consumption limits
- Input Validation: All external inputs are validated before processing
{
capacity: uint, // Maximum production capacity
current-production: uint, // Current production level
total-produced: uint, // Lifetime production total
energy-type: string, // Type of energy (solar, wind, etc.)
active: bool, // Active status
reputation-score: uint // Reliability score (0-100)
}{
consumption-limit: uint, // Maximum consumption allowed
total-consumed: uint, // Lifetime consumption total
current-usage: uint, // Current consumption level
balance: uint, // Available balance for purchases
active: bool // Active status
}{
capacity: uint, // Storage capacity
stored-amount: uint, // Current stored energy
charge-rate: uint, // Maximum charge rate
discharge-rate: uint // Maximum discharge rate
}{
seller: principal, // Producer address
buyer: principal, // Consumer address
amount: uint, // Energy amount
price: uint, // Trade price
timestamp: uint, // Block height of creation
completed: bool // Completion status
}register-producer (capacity: uint, energy-type: string) -> (response bool uint)
- Register as an energy producer
- Specify production capacity and energy source type
- Initial reputation score set to 100
register-consumer (consumption-limit: uint) -> (response bool uint)
- Register as an energy consumer
- Set maximum consumption limit
- Initialize with zero balance
register-storage (capacity: uint, charge-rate: uint, discharge-rate: uint) -> (response bool uint)
- Register energy storage facility
- Configure capacity and charge/discharge rates
report-production (amount: uint) -> (response bool uint)
- Report current energy production level
- Updates grid load automatically
- Must not exceed registered capacity
consume-energy (amount: uint) -> (response bool uint)
- Consume energy from the grid
- Automatically calculates cost using dynamic pricing
- Deducts balance and updates grid load
charge-storage (amount: uint) -> (response bool uint)
- Charge storage facility from grid
- Respects charge rate limits
- Reduces grid load
discharge-storage (amount: uint) -> (response bool uint)
- Discharge stored energy to grid
- Respects discharge rate limits
- Increases grid load
create-trade (buyer: principal, amount: uint, price: uint) -> (response uint uint)
- Create energy trade offer
- Returns trade ID for tracking
- Validates buyer exists and is active
complete-trade (trade-id: uint) -> (response bool uint)
- Complete pending trade
- Verifies buyer authorization and balance
- Transfers energy and updates balances
add-consumer-balance (target-consumer: principal, amount: uint) -> (response bool uint)
- Add balance to consumer account
- Amount must be between 1 and 1,000,000
- Anyone can add balance (payment gateway integration)
set-base-price (new-price: uint) -> (response bool uint)
- Update base energy price
- Grid operator only
- Must be greater than zero
toggle-emergency-mode () -> (response bool uint)
- Activate/deactivate emergency pricing
- Grid operator only
- Triggers 3x price multiplier
record-metrics (prod: uint, cons: uint, peak-load: uint, eff: uint) -> (response uint uint)
- Record grid performance metrics
- Grid operator only
- Returns metrics ID for reference
update-producer-reputation (target-producer: principal, new-score: uint) -> (response bool uint)
- Update producer reputation score
- Grid operator only
- Score must be 0-100
deactivate-participant (target: principal, is-producer: bool) -> (response bool uint)
- Deactivate producer or consumer
- Grid operator only
- Prevents further transactions
get-producer-info (producer: principal) - Retrieve producer details
get-consumer-info (consumer: principal) - Retrieve consumer details
get-storage-info (storage: principal) - Retrieve storage facility details
get-trade-info (trade-id: uint) - Retrieve trade information
get-grid-status () - Get current grid status including capacity, load, and utilization
get-dynamic-price () - Calculate current energy price based on grid conditions
get-metrics (metrics-id: uint) - Retrieve historical performance metrics
| Code | Constant | Description |
|---|---|---|
| u100 | err-owner-only | Unauthorized: admin function called by non-operator |
| u101 | err-not-found | Entity not found in registry |
| u102 | err-unauthorized | Caller not authorized for this action |
| u103 | err-insufficient-energy | Insufficient energy available |
| u104 | err-invalid-amount | Amount outside valid range |
| u105 | err-already-exists | Entity already registered |
| u106 | err-inactive | Participant is deactivated |
| u107 | err-insufficient-balance | Insufficient balance for transaction |
| u108 | err-invalid-input | Invalid input parameter |
(contract-call? .smart-grid register-producer u50000 "solar")(contract-call? .smart-grid register-consumer u10000)(contract-call? .smart-grid report-production u5000)(contract-call? .smart-grid consume-energy u100)(contract-call? .smart-grid create-trade 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM u1000 u150)(contract-call? .smart-grid get-grid-status)The contract implements a sophisticated pricing model:
- Normal Mode: Price = Base Price + (Base Price Γ Current Load / (2 Γ Total Capacity))
- Emergency Mode: Price = Base Price Γ 3
This ensures fair pricing based on supply/demand while incentivizing production during high-demand periods.
- β All external inputs are validated before processing
- β Role-based access control for administrative functions
- β Balance and capacity checks prevent overdraft
- β Active status verification prevents inactive participant transactions
- β Zero compiler warnings - all code paths are validated
- β No use of potentially unchecked data