Building an Energy Market on the Blockchain: Evaluation, Wireframing, and Implementation

Author profile picture

@albertocuestacanadaAlberto Cuesta Cañada

Hello. I design and build blockchain solutions. I like to make the complex simple.

Including Solidity smart contracts to get you started.

People always fear change. People feared electricity when it was invented, didn’t they? People feared coal, they feared gas-powered engines… There will always be ignorance, and ignorance leads to fear. But with time, people will come to accept their silicon masters. — Bill Gates

Introduction

The energy industry contains some of the most valuable use cases for blockchain technology. Blockchain works best when dealing with decentralized markets, and with the advent of renewable microgeneration the energy markets are rapidly becoming just that. It certainly looks like an industry that could be massively disrupted by technology.
In this article I’m going to describe a simple implementation of an electricity market in the ethereum blockchain. I will also include some ideas for further development towards a more mature solution. I struggled myself to unpack how electricity markets work and how to relate energy load with payments. I think this article will be very useful if you are starting on this same path.

How do electricity networks work?

In a nutshell, electricity networks match production with consumption. If my laptop draws 200 watts of electricity during the two hours that I’m writing this article, someone will have to pump 200 watts into the same electricity network in the same timeframe. 
If 10,000 of us log on to a massive Counterstrike LAN party, that would mean that something would need to pump 2 megawatts while we are at it. There are electricity losses due to distance between producers and consumers, and most networks will have several circuits directing the power to the right places, but basically that’s how it works.
There are usually four actors in this scenario: Producers, distributors, retailers and consumers.
  1. Producers produce electricity which is pumped into the network, and they are paid for it.
  2. Distributors maintain the network that takes the electricity from the producers to the consumers.
  3. Retailers buy electricity from producers and sell it to the consumers.
  4. Consumers buy electricity from the retailers, which was bought wholesale from producers.
This buying and selling of electricity don’t mean that the retailers buy electricity from a given wind farm and manage to get those electrons into a specific consumer. What is bought and sold is some kind of certificates for the production of electricity.
Each producer gets these certificates as they pump electricity into the network. For a consumer to take electricity from the network he needs to have enough certificates for the amount of electricity taken. It is obviously not allowed to sell or use the same certificate twice so that exactly the same amount of electricity that is produced is paid for.
At least, that’s how it’s worked for the last 100 years. 
Centralized generation has meant massive power plants produced the electricity for large numbers of consumers. 
The energy flow has traditionally been from producers to the consumers through the distribution network. The money flow has been from the consumers to the producers through the retailers, assisted by meters that ensure the money flow matching the energy flow.
More recently, the picture has started to change towards a prosumer scenario. In several countries now you have large numbers of individuals that produce electricity with solar panels from their homes. These prosumers sometimes take energy from the network, and sometimes pump energy into the network. 
This has made the energy market a lot more complex. How can those prosumers emit their own certificates? Who decides on the price? Who buys them and how? Not only the distributor now has a headache in balancing the network, but now there is a complex decentralized market.
Those of you that have been in the blockchain space for a while will have already connected the dots. I’m sure there is some way of building an efficient decentralized market for all these prosumers.

Business Case

Our business case will be a prosumer scenario for renewable energy trading. We will assume that the distributor runs the energy market and uses monetary incentives to balance the production and consumption of electricity.
This is similar but not identical to the real world energy markets out there. I’ve made the use case more generic because a blockchain based energy market has some computational constraints.
In a real world market the producers bet the price at which they want to produce energy for a given timeframe. The retailers buy or not specific bets from producers, usually just choosing by the lowest price available. This is exactly how a security trading market works, but that happens to be computationally too intensive for current blockchain platforms.

Design

For the simplest implementation of this energy market we will use some ERC20 token as currency, and two variables to represent the production and consumption loads in the network. We will split time into arbitrary units and aim for the production and consumption load to be as balanced as possible for each time unit.
I’m going to take some inspiration on the uniswap market and use a simple price formula that reduces the electricity price when there are more producers than consumers for a given time unit. This way, cheaper electricity will incentivize consumers to consume more and producers to produce less, balancing the network. Conversely, the price rises as the number of consumers will decrease and the number of producers will increase due to the higher prices.
In a nutshell, electricity networks match production with consumption.
In all transactions the distribution network will be one of the counterparts. The distribution network will set the price. Producers will sell electricity to the distribution network. Consumers will buy electricity from the distribution network.
Before you think that I’m centralizing the distribution network, I’m not. The physical distribution network that routes energy remains unchanged, but the financial distribution network that routes money between prosumers becomes a decentralized smart contract.
I’m removing many complex features to focus on the market mechanism. I believe it is possible to implement a national energy market on the blockchain, but for the purposes of this article we must remain with a simple scenario. I’ll discuss some of the missing parts later in the article.
Within these limits, let’s move on to see how does it work in code.

Implementation

The main benefit of a uniswap-style market is that it is very simple. In our case the whole energy trading market fits in less than 100 lines with comments. I’ll explain here the key features and then paste the whole contract. Apologies if you have to switch back and forth a few times.
For its implementation I’m going to make the market inherit from both ERC20 and Whitelist. ERC20 gives us the tools to have a currency for payments. Whitelist allows us to restrict the market only to identified consumers and producers.
As for uniswap, the market needs to be seeded with an amount of currency. This is because there might be more producers than consumers, and the market pays to producers and charges consumers. There needs to be a bit of a margin there.
The prices are calculated by two simple formulas based on the difference between the production and consumption loads. When the consumption and production loads are exactly matched the price is a chosen base level. Please ignore all the casting between types, it’s just to protect against overflow and negative prices.
This mechanism is very simple, which suits the limited computational power of blockchain. At the same time it encourages production and consumption to be balanced. Destabilizing the network in either direction has a monetary cost.
The energy flow has traditionally been from producers to the consumers through the distribution network. The money flow has been from the consumers to the producers through the retailers.
It’s important to realize that the smart contract controls the money flow, and that production and consumption orders will usually be filled for future time slots. The physical distribution network will have some knowledge of proposed consumption and production loads and can take actions to curtail them if required to balance the network.
The production of energy is allowed only to identified producers, and they just need to state their intention to produce and will immediately receive the money. Obviously this is a gross simplification and in real life the money would be held into escrow until it is certified that the power was produced.
The consumption of energy works in the same way. The consumers state their intentions and pay the price determined by the network. In real life there might be some refund if the power is not actually consumed.
pragma solidity ^0.5.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@hq20/contracts/contracts/access/Whitelist.sol";


/**
 * @title Energy Market
 * @notice Implements a simple energy market, using ERC20 and 
 * Whitelist. ERC20 is used to enable payments from the consumers to
 * the distribution network, represented by this contract, and from
 * the distribution network to the producers. Whitelist is used to
 * keep a list of compliant smart meters that communicate the
 * production and consumption of energy.
 */
contract EnergyMarket is ERC20, Whitelist {
  event EnergyProduced(address producer, uint256 time);
  event EnergyConsumed(address consumer, uint256 time);
  // uint128 is used here to facilitate the price formula
  // Casting between uint128 and int256 never overflows
  // int256(uint128) - int256(uint128) never overflows
  mapping(uint256 => uint128) public consumption;
  mapping(uint256 => uint128) public production;
  uint128 public basePrice;

  /**
   * @dev The constructor initializes the underlying currency token
   * and the smart meter whitelist. The constructor also mints the
   * requested amount of the underlying currency token to fund the
   * network load. Also sets the base energy price, used for 
   * calculating prices.
   */
  constructor (uint256 _initialSupply, uint128 _basePrice)
    public
    ERC20()
    Whitelist()
  {
    _mint(address(this), _initialSupply);
    basePrice = _basePrice;
  }

  /**
   * @dev The production price for each time slot.
   */
  function getProductionPrice(uint256 _time)
    public
    view
    returns(uint256)
  {
    return uint256(
      max(
        0,
        int256(basePrice) *
          (3 + safeSub(production[_time], consumption[_time]))
      )
    );
  }

  /**
   * @dev The consumption price for each time slot
   */
  function getConsumptionPrice(uint256 _time)
    public
    view
    returns(uint256)
  {
    return uint256(
      max(
        0,
        int256(basePrice) *
          (3 + safeSub(consumption[_time], production[_time]))
      )
    );
  }

  /**
   * @dev Add one energy unit to the distribution network at the
   * specified time and be paid the production price. Only
   * whitelisted smart meters can call this function.
   */
  function produce(uint256 _time)
    public
  {
    require(isMember(msg.sender), "Unknown meter.");
    this.transfer(
      msg.sender,
      getProductionPrice(_time)
    );
    production[_time] = production[_time] + 1;
    emit EnergyProduced(msg.sender, _time);
  }

  /**
   * @dev Take one energy unit from the distribution network at the
   * specified time by paying the consumption price. Only
   * whitelisted smart meters can call this function.
   */
  function consume(uint256 _time)
    public
  {
    require(isMember(msg.sender), "Unknown meter.");
    this.transferFrom(
      msg.sender,
      address(this),
      getConsumptionPrice(_time)
    );
    consumption[_time] = consumption[_time] + 1;
    emit EnergyConsumed(msg.sender, _time);
  }

  /**
   * @dev Returns the largest of two numbers.
   */
  function max(int256 a, int256 b)
    internal
    pure
    returns(int256)
  {
    return a >= b ? a : b;
  }

  /**
   * @dev Substracts b from a using types safely casting from
   * uint128 to int256.
   */
  function safeSub(uint128 a, uint128 b)
    internal
    pure
    returns(int256)
  {
    return int256(a) - int256(b);
  }
}

Further work

There are some features that haven’t been implemented for the sake of brevity. The most important of them are as follows.
  1. There isn’t an escrow mechanism to ensure that producers only get paid for energy they produce, as opposed to promised to produce.
  2. There isn’t a guard against putting orders for production or consumption in the past.
  3. Neither production nor consumption orders can be cancelled. This would be needed for example for unplanned maintenance.
  4. The pricing formula has been simplified and would need mathematical modelling.
  5. There is no mechanism for minting tokens except for the constructor, so the contract supply can’t be modified and customers can’t actually get funds.
  6. The currency contract should be passed on as an address in the constructor, instead of using inheritance.
  7. The production and consumption orders should be allowed to be for an energy amount which is in a range proportional to the current load.
  8. The current implementation would have poor performance on a national scale.
These are only some examples. Please don’t use this contract as-is except for learning purposes or to build your more advanced version out of it.

Conclusion

Energy markets are a natural fit for blockchain technology. With the advent of microgeneration the energy networks are being disrupted into a mesh of customers that are both consumers and producers at a micro scale.
The current networks were built for unidirectional power flow, with money flowing in reverse. Producers were expected to be thousands or millions of times larger than consumers. Reengineering the physical network is a challenge, but reenginering the payments network is a different challenge.
An energy market can be built in the blockchain using uniswap-style smart contracts. This introduces a radical change over the current order book implementations. At the same time successfully decentralizes the market, allowing small producers direct access.
Where current markets rely on retailers to dictate the production price of small producers, a blockchain market sets prices by supply and demand. This is nothing short of revolutionary.
Thanks for reading this far. This was a challenging project and extremely fun to get to this point. I hope you will find it useful as well. If you are interested in exploring energy markets in the blockchain please drop me a line, I’ll be more than happy to help.

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!