Smart contracts in energy systems: A systematic review of fundamental approaches and implementations

Given the ongoing transition towards a more decentralised and adaptive energy system, the potential of blockchain-enabled smart contracts for the energy sector is being increasingly recognised. Due to their selfexecuting, customisable and tamper-proof nature, they are seen as a key technology for enabling the transition to a more efficient, transparent and transactive energy market. The applications of smart contracts include coordination of smart electric vehicle charging, automated demand-side response, peer-to-peer energy trading and allocation of the control duties amongst the network operators. Nevertheless, their use in the energy sector is still in its early stages as there are many open challenges related to security, privacy, scalability and billing. In this paper, we systematically review 178 peer-reviewed publications and 13 innovation projects, providing a thorough analysis of the strengths and weaknesses of smart contracts used in the energy sector. This work offers a broad perspective on the opportunities and challenges that stakeholders using this technology face, in both current and emergent markets, such as peer-to-peer energy trading platforms. To provide a roadmap for researchers and practitioners interested in the technology, we propose a systematic model of the smart contracting process, by developing a novel 6-layer architecture, as well as presenting a sample energy contract in pseudocode form and as open-source code. Our analysis focuses on the two mainstream application areas we identify for smart contract use in this area: energy and flexibility trading, and distributed control. The paper concludes with a comprehensive, critical discussion of the advantages and challenges that must be addressed in the area of smart contracts and blockchains in energy, and a set of recommendations that researchers and developers should consider when applying smart contracts to energy system settings.


Introduction
Energy systems are undergoing major changes to accommodate the increasing amount of renewable energy sources (RES), as well as new types of loads, such as those from decarbonised transport systems.Wind and solar energy technologies have rapidly advanced in recent years as a result of supportive energy policies, economic incentives and changes in the sector, such as the establishment of energy communities Furthermore, small-scale decentralised generation assets are currently not coordinated by the system operator for balancing the grid and are often too small to participate in energy or ancillary services markets -unless their participation is enabled by an aggregator.Therefore, the system requires new local-level management and distribution techniques.The current trend of decentralisation and digitalisation is driving the pursuit for innovative solutions that enable reliable and tamper-proof data and energy exchange to increase selfconsumption in local energy communities, and support the deployment of more distributed control solutions.Similarly, the foreseen increase in new types of decentralised load (e.g. the adoption of electric vehicles) could offer the grid the flexibility it needs, such as load shifting, peak shaving and demand-side response.However, the problem is that the current system operation paradigm is unable to coordinate and take advantage of the vast amount of small decentralised assets.
Smart contracting, along with distributed ledger technologies (DLTs) may offer a solution to these challenges, as highlighted by the systematic review of Andoni et al. [7].Blockchain technology or distributed ledgers represent a base layer technology that provides a secure and immutable ledger of digital transactions and value transfers in a network.Smart contracts are codified using an underlying blockchain architecture and therefore intrinsically inherit many of its desired properties, such as automation, decentralisation, immutability and security.In fact, it can be argued that smart contracts are the aspect of blockchains that is the most relevant for the energy application layer.While blockchain architectures are concerned with data storage, involving aspects such as cryptographic security or reaching consensus on the information to be written on the blockchain, the contractual operations and transactions to be executed on the blockchain (whether they concern money, energy or flexibility commitments) is a concern of the smart contracting layer.
Smart contracts are self-executable programs that are able to monitor and change the ledger according to user-defined rules.They can be triggered when certain conditions are met and can automatically execute and control energy trading events.They use computer hardware to process data, verify conditions, deal with negotiations and validate a contract.The records are append-only (i.e.irreversible) and transparent.Hence, the requirement for an intermediary or a system operator is eliminated.As a result, this holds the potential to automate and accelerate automated negotiations and contracting between the parties [8].Smart contracts offer a virtual means of reaching and enforcing a credible agreement and/or transaction [9].In turn, this can enable the development of new forms of social organisations, such as Decentralised Social Organisations (DAOs), in the energy space, selforganising energy communities or microgrids.On the regulatory side, a report on distributed ledger technologies published by the United Kingdom government chief scientific advisor [10] identifies smart contracts as a crucial factor that can unlock the full potential of blockchain technology.
Despite the rapid increase in the number of reviews that cover the use of blockchain in energy [7,[11][12][13], to the best of our knowledge, there has never been a systematic review of smart contracts used for energy applications specifically and our review attempts to fill this very important knowledge gap.As the number of research papers using smart contracts has considerably increased in the last three years, with more than 150 publications since 2018, it is timely and relevant to understand how this novel technology has been adopted by energy researchers.Indeed, this is a fast-moving field that requires a good overview of the capabilities and limitations of smart contracts in order to use them adequately.This review aims to help researchers and practitioners form an informed opinion on the possibilities of smart contracts adoption in the energy domain, and understand how they can integrate this new technology into their projects.Moreover, as published research sources do not always reflect the full potential and drawbacks of applications of smart contracts in the real world, our review also briefly surveys some relevant demonstration and industrial projects.
Finally, we note that, despite its significant potential, smart contracting is still a developing technology and has several open challenges associated with its implementation, such as privacy concerns, risk of cyber-attacks (such as hacking) and the energy required for computation and blockchain deployment of the contracts.So far, smart contract applications in energy systems have been mostly focused on research, proof-of-concept and demonstration projects (such as P2P demonstration projects run in a local community or microgrid).However, as the technology scales up, security vulnerabilities and threats, implementation and communication issues, as well as financial and environmental costs of deploying smart contracts will become increasingly important to consider.This is already the case in areas where smart contracts are already deployed on a large commercial scale such as Decentralised Finance (DeFi) and non-fungible tokens (NFTs).Hence, one of the goals of this review is to leverage the knowledge from both the existing body of published literature of smart contracts in energy, as well as experience from their large-scale use in other areas in order to provide a critical discussion of the potential risks and challenges that need to be addressed to scale up their adoption in digital energy systems.
To conduct our study, a systematic search and review method was employed to evaluate how smart contracts are used in the field of energy systems.To obtain the literature of interest, the phrase ''smart contract'' was queried along with ''energy'' or ''electricity''.Following the methodology shown in Fig. 1, we filtered the literature that feature the aforementioned keywords in their title, abstract and list of keywords, using Scopus which is one of the most comprehensive indexes of peer-reviewed scientific publications, comprising of both journals and conference proceedings.After filtering for relevance, this resulted in a corpus of 178 peer-reviewed publications, on which this study is based (full data is provided in Table 1 in the Appendix).
Overall, the contributions of this work can be summarised as follows.
First, we perform a comprehensive review of smart contracts research in energy, including the benefits and limits of smart contracts for energy applications.To this end, we propose a 6-layer architecture, that provides a systematic model of the different levels involved in the smart contracting process, ranging from the communication and implementation layers to the blockchain layer and then to the higher layers consisting of agent-mediated markets and management of bids and offers.Additionally, we propose a sample energy smart contract1 in order to provide readers with a potential starting point for smart contract implementations within their energy-related projects.
Second, we provide a systematic presentation of the strengths and weaknesses of smart contracting for different use cases related to the energy domain described in the literature (such as P2P trading, demand-side response, EV charging, battery management, smart homes etc.), and discuss the capabilities of smart contracts that are most relevant for the energy applications (such as asset and user management, automated market clearing functions, management of bids and offers or distributed computation).Additionally, we perform an evaluation of various use cases of smart contracts from industry and pilot demonstration projects.Finally, we provide a comprehensive critical discussion of both the benefits, but also the potential drawbacks and risks of current smart contract technologies, including security vulnerabilities, implementation and communication risks, and well as potential costs, both financial and environmental.The paper concludes with a set of practical recommendations of issues that researchers and developers should take into account when considering smart contract solutions to their energy problems.
The remainder of the paper is structured as follows.Section 2 describes the main principles of smart contracts.Section 3 presents the different types of applications in which smart contracts are used in the energy sector, whereas Section 4 highlights the main functions that are implemented in smart contracts for energy related use cases.Section 5 reviews innovative industrial and academic projects.Section 6 summarises the trends shown by this review, whereas Section 7 provides an extensive discussion of the benefits, but also the challenges and limitations of the use of smart contracts in the energy sector.Finally, Section 8 concludes the paper with a summary, but also with a set of recommendations of points that readers should follow when applying smart contracts in their energy project.

Background and fundamental principles of smart contracts for energy
This section presents the background information and fundamental principles regarding the definition of a smart contract, including an example of a generic energy smart contract.

Blockchain technology overview
Before we discuss key capabilities and applications of smart contracts in the energy section, we briefly review blockchains -the key underpinning technology for smart contracts.Note that this paper is meant specifically as a focused, in-depth review of smart contracts in energy, for a broader discussion of blockchain technology in the energy sector, readers can consult Andoni et al. [7].
Intuitively defined, a blockchain is a chain of information blocks (usually, containing information about crypto-currency transactions or smart contract specifications), linked together through cryptographic methods.It has alternatively been described as an append-only log, or a distributed ledger of transactions [14].Unlike a centralised database, this ledger is distributed, meaning no single party has control over writing information to the blockchain.In fact, a number of nodes or peers all have a copy of the whole blockchain (or the key information of the chain), and mutually agree on how the information can be written/added through a consensus protocol.
A key feature of blockchains is that it is tamper proof : information written in previously accepted blocks cannot be changed, a property assured through cryptographic hashing.In more detail, all the transaction information contained in each block is efficiently hashed through a so-called Merkle tree in the header, while each block contains a hash of the header information of the preceding block.In practical terms, these cryptographic links created through hashing means that any unauthorised change (i.e.tamper) with the information in a previous block is immediately detectable by all nodes.Typically, in blockchain systems, if a transaction in a previously accepted (or ''mined'') block needs to be changed or reversed, this can only be achieved by recording the reverse transaction in a future block, accepted by all parties.
A key issue in blockchain systems is the method of reaching consensus among the nodes on each information block to be stored, i.e. the consensus protocol.There are many variants of consensus protocols deployed or proposed (see [7,14]), but the main ones are: 1. Proof of Work (POW): This is the form of consensus in most open blockchain systems, supporting their own cryptocurrency, such as bitcoin [15].In POW consensus, the node that has the right to add the next block to the chain is determined by solving a cryptographic puzzle (technically, through a so-called ''zero-knowledge proof''), i.e. a puzzle that is hard to solve, but easy to verify.Adding a new block is often referred to as ''mining", and the nodes that perform this activity as miners, which are rewarded a certain amount of native cryptocurrency (or sub-unit of it) for each new block they successfully mine.In the Bitcoin system, the puzzle consists of computing a number of leading zeros, with the difficulty of the puzzle can be adjusted by increasing/decreasing the number of zeros required to be computed.In practice, the puzzle has become exponentially harder to solve over time, currently requiring specialised hardware (called ASICs, application-specific integrated circuits), pooling computation resources into so-called ''mining pools", and especially, a large amount of energy consumption.This large energy required to undertake POW computations is, popularly, one of the most well-known and striking features of POW blockchains, as it currently exceeds the energy consumption of several countries (with Ireland, Denmark or Argentina alternatively mentioned 2 ).The sustainability of the high energy use has been questioned, with most mining pools being established in places with very cheap energy.While this often happens in areas with excess generation from renewables, in many cases it utilises questionable sourcing of cheap energy in some countries/regions (which are often based on coal or other fossil fuels).

Proof of Stake (PoS):
This alternative consensus mechanism relies on giving more weight (and hence a greater chance to mine the next block) to nodes that have a greater ''stake" in the system" (e.g.own more of the cryptocurrency).This eliminates the need for energy-consuming PoW-style mining to establish trustworthiness, and can also make generating blocks much faster.Currently, the Ethereum network is actively exploring transitioning to a PoS-type model, partially due to much lower energy costs to assure consensus.

Proof-of-Authority (POA):
This consensus mechanism can be seen as a variant of Proof-of-Stake, where the stake is the identity of the validator.POA relies on a (relatively small) number of pre-approved validator accounts or ''authorities'', that have the right to validate transactions and add new blocks.Authority nodes are required to go through a pre-selection process, disclose their identity and register with a public notary database and comply with a series of rules to remain trustworthy.Since they are rewarded for doing this and receive energy in the network, they have an incentive to remain trustworthy, and avoid being compromised by attacks.POA protocols have proved especially popular in private (enterprise) blockchains, including energy applications (e.g. the Energy Web Foundation blockchain system).This is due to the high transaction rate that is achievable in 2 Readers can consult https://cbeci.org/ for the latest figures.
POA-based systems, and much lower overheads and energy costs than, e.g.PoW systems.However, having a small number of authority nodes can be seen as going against the decentralisation principles underlying blockchains, hence this is a less suitable alternative for public, permissionless blockchains.4. Other protocols: A number of other protocols have been proposed, including: proof of elapsed time, proof of activity, consensus mechanisms relying on Byzantine Fault Tolerance etc.The reader can consult Andoni et al. [7] or the NIST overview [14] for detailed discussions.
We note that different types of consensus protocols are appropriate for different types of blockchain systems.The main types of blockchain systems are: A. Permissionless blockchain systems.This includes most of the blockchain systems supporting known cryptocurrencies, such as Bitcoin, Ethereum etc.In this type of blockchain there is no central authority granting access to the blockchain.In fact, in many cryptocurrency systems (e.g.Bitcoin), the users or holders of cryptocurrency wallets remain completely anonymous, identified only by their public key and cryptographic signature.Some wallets may be suspected of belonging to criminal activity or hacking, but until the users behind them attempt to exchange their cryptocurrency in ''fiat" (regular) currency, it is extremely hard to establish their real identity.B. Permissioned blockchains (also known as ''private" or ''enterprise" blockchains).In this type of blockchain, not any party can join, there is a central authority granting access according to preagreed rules.Such blockchains often refer to a specific system of application (e.g.prosumers in a microgrid P2P energy trading scheme, parties trading energy given a specified protocol etc.).Permissioned blockchains can (and have) sometimes come under criticism for not following what some authors see as the ''truly decentralised" ethos at the core of blockchain technology.Yet, it is worth pointing out that permissioned blockchains are still very different in implementation to centralised databases: while there is a process of verification and granting access, information is still stored and written in a decentralised fashion among nodes, on a distributed ledger.
There are, of course, advantages and disadvantages that can be highlighted to each type.Permissionless blockchains are described in some sources as the only ones that are ''truly" open or decentralised: it is impossible for any party to change the stored information or rules, unless they gain control of 51% of the computing power, which is unlikely in a large system like Bitcoin (although some authors have raised concerns about the increasing concentration of mining pools).
Most energy applications reported in the literature fall (implicitly or explicitly) in the ''permissioned blockchain" category.This is because in energy trading, the identity of the parties trading will be generally known at least to some actors in the system (unlike cryptocurrency transactions, where wallet owners can remain completely anonymous).For example, smart metres points, where energy is imported or exported, have a physical, identifiable location on the power grid.On the flip side, however, this may also hold the promise of using forms of consensus that are quicker and much less energy-intensive than Proof-of-Work mining, which would not an environmentally sustainable proposition, from an energy use perspective.

Relation between blockchains and smart contracts
Most well-known blockchain systems (e.g.Bitcoin, Ethereum) were set up around a so-called ''native" cryptocurrency, and the main aim of the blockchain is to record the transaction in that crypto-currency, between users who store such currency in a digital wallet.This digital wallet is protected and accessed by users through a system of public-key (or asymmetric) cryptography, and allows transactions to be digitally signed.
In addition to cryptocurrency transactions, a blockchain can also store software code, called smart contracts, that is executed when the pre-defined conditions are met.A smart contract is embedded on the blockchain, in a similar way to a cryptocurrency transaction (which is the most common use case of blockchain).Specifically, the compiled code and specific pieces of information, such as the list of functions to be executed are sent from a wallet to the blockchain.This code and information must then be included in a block that is added to the ledger (though the consensus mechanism), at which point the smart contract code will execute to establish the initial state of the smart contract.Similar to currency transactions, cryptographic hashing secures the smart contract in a decentralised way from attempts to change or tamper with it.Once its code is stored on the blockchain, a smart contract can be compared to a software process that will be run when specific conditions arise (e.g. a certain amount of energy consumption or production).Practically, the execution of the code embedded in a smart contract is deployed in a virtual environment that is physically hosted by all the nodes that constitute the blockchain, as if they were a single computer.
As a result, once a smart contract is deployed, it cannot be updated -if an attack occurs due to some fault or vulnerability in the contract code, it is not easy to fix, due to the decentralised nature of blockchains.This is true in open, permissionless blockchains, for example, the DAO attack on the Ethereum blockchain in June 2016 -in which the Ethereum community decided to hard fork the blockchain, resulting in a different cryptocurrency.It is possible that in a permissioned (enterprise) blockchain which most energy applications are likely to use, fixing attacks by restoring the blockchain could, arguably, be easier to do, as a central party controls the access to the system.
In summary, the blockchain architecture -while no doubt crucial for understanding what a smart contract is and its capabilities -can be seen as being at a different implementation level than the smart contract specification itself.For example, to take an energy P2P exchange application, it is the smart contract that specifies the rules for how/when energy or flexibility is to be traded, and the price to be paid, rather than the blockchain architecture.It is fair to state that the overwhelming majority of papers reviewed for this study concern themselves with this ''application layer" of the smart contract, rather than implementation and fundamental choices in the blockchain layer.In fact, most papers rely on an existing blockchain architecture, which pre-specifies choices such as, e.g. the consensus protocol and type of cryptography used.The Solidity smart contract language for programming smart contracts based on the Ethereum blockchain is proving to be especially popular, due to its flexibility, but it is clearly not the only choice.

Definition and lifecycle of a smart contract
Smart contracts were first introduced by computer scientist Nick Szabo in 1996, with the vision of using computer code in order to automate legal contracts while using cryptography to make them secure and tamper-proof [11].Szabo defines smart contracts as ''a set of promises, specified in digital form, including protocols within which the parties perform on these promises" [16].
Another research line in the community [17] has focused on defining ''smart legal contracts'' (or ''Ricardian contracts''), that aim to capture the defining elements of a legal agreement in a format that can be expressed and executed in software code.Many smart contracts presented in the literature do not place the same weight on the formal legal aspects as the Ricardian approach.
Their ''smart'' nature is related to their ability to self-enforce using a specified set of rules once the pre-defined criteria are met.When deployed on a blockchain, smart contracts can automatically reach and enforce agreements which result in a faster process and reduced costs.This is especially beneficial for recurring trust-free agreements/transactions with a low financial value such as half-hourly peerto-peer energy trading.The core principle of a smart contract is based on the ''if-then'' logic which requires to program the desired outcome/action and the condition(s).For instance, the outcome of a smart contract can be an action such as the discharge of a battery whereas the condition for this action to be triggered can be the electricity export price going over a threshold value or the successful transfer of the required funds from a buyer.
Since they are secure and tamper-proof, smart contracts are used in other sectors with confidence.One example is the financial smart contract template developed by the British multinational investment bank and financial services company Barclays [18].One of the key advantages of smart contracts over regular contracts is the cryptography techniques used.This is highly valued by utility businesses as it creates an encrypted and secure ledger of contracting actions.In addition to the recognition of this in academic literature, Makmur et al. [19] presents the case study of Persero, an Indonesian state-owned utility company with a reach of over 72 million customers, highlighting the role of smart contracting in billing due to its tamper-proof and secure nature.
To summarise, a smart contract is a sort of agreement between parties that is automated, enforceable and self-executing.Even though it is mostly computed digitally, some parts of the smart contract can be programmed to have human input and control.Fig. 2 concisely depicts the lifecycle of a smart contract in four fundamental steps which are (1) agreement amongst the parties, (2) establishment of smart contract, (3) verification that the criteria are fulfilled and (4) execution of value transfer (e.g. money and energy exchange).Step (3), namely verification of criteria reached, provides a novel advantage for the energy systems and especially local electricity markets.Indeed, smart contracts can enable automated peer-to-peer energy trading: Smart metre data can be used to verify energy transactions and trigger the billing process of a smart contract.This would result in a fairer and faster settlement, increasing the benefit to both the consumer and producer.The main goal of smart contracts is to provide more secure transactions in comparison to the traditional contracting methods and to decrease processing and verification costs and time.
Although these characteristics make smart contracts very suitable for financial transactions using cryptocurrencies [20], the use of smart contracts energy sector is still in its development phase as there are multiple concerns related to security, privacy, scalability and billing [21,22].

Key characteristics of smart contracts
The main characteristics of smart contracts are the following: 1. Self-enforcement and automation: Smart contracts are made of code that takes decisions based on specific inputs.This code is executed automatically in a virtual environment that is shared among the nodes of the blockchain when specified conditions arise.Therefore, smart contracts are self-enforced and will execute the dedicated code automatically.2. Tamper-proof nature: Smart contracts are software components that are stored on a blockchain.Therefore, they inherit distributed ledger properties, among which the tamper-proof characteristics.Indeed, being stored on a blockchain makes the smart contract code immutable and unalterable, as this would require changing the whole blockchain.3. Trustworthiness: Being tamper-proof, a smart contract cannot be changed by any other node of the blockchain.Therefore, it is ensured that the smart contract code is original and corresponds to its designer's code.4. Transparency and accessibility: Being part of a blockchain, the smart contract is transparent and accessible to all the members of a blockchain.Therefore, in the case of permissionless ledgers, everyone can have access to the content of a smart contract, whereas it might be restricted to some users in the case of permissioned blockchain. 5. Security: Given the high level of cryptography and the characteristics of blockchain (e.g.tamper-proof), smart contracts inherit a high level of security, as their content cannot be changed by anyone, and their execution is automatic.6. Speed and reliability: This is a key aspect of smart contracts: as they are executed in a virtual environment shared among the blockchain nodes, their code is run at the moment this virtual environment identifies a specific condition.This ensures a high speed of response that will be maintained as long as there are nodes in the blockchain.Furthermore, this ensures high reliability in the execution, as the code execution does not depend on a single server as would be the case in a centralised architecture scheme.7. Self-verification: Although formal verification is still an ongoing research field, most smart contract languages and blockchains verify the code embedded in a smart contract, in order to ensure the viability of the contract.For example, the self-verification steps to deploy a smart contract on a blockchain can include the fact that the smart contract does not lead to an infinite loop.8. Computational performance and expense: As smart contracts imply the execution of code in a virtual environment shared among the blockchain nodes, each node dedicates part of its computational power to the smart contract execution.The execution cost is covered by the smart contract owner (i.e. the node that deploys the smart contract on the blockchain).In Ethereum, Gas is the measurement unit for executing operations in the virtual environment, that is called Ethereum Virtual Machine (EVM).Wood et al. [23] present a table with the gas requirements per operation.The amount of gas increases as the complexity of operations in a smart contract increases.For example, an ethereum (ETH) transaction to another agent costs 21000 gas, whereas the deployment of a new contract costs at least 32000 gas to create a contract account.The current cost for bytecode execution is 200 gas, and 68 gas per each byte used to start a transaction.Also, the contract's first execution embeds an additional cost.The total deployment cost of a smart contract can be higher than 200,000 gas, with an execution cost near to 50,000, as presented in [24], where 3 types of contracts were evaluated.In public networks the gas cost is determined by demand and supply, where a limited number of miners can offer their computational power to a big number of agents, generating gas price fluctuations between 10 Gwei (i.e.nanoether, 10 −9 ETH) to 100 Gwei in a year and peaks over 400 Gwei in high congestion events, according to ETHGasStation data. 3In private networks, costs are usually neglected as the blockchain nodes do not need a specific financial incentive to take part in the virtual environment.Indeed, nodes of private blockchain usually join the blockchain environment to take advantage of other benefits, such as local green and cheap energy supply.To calculate the required gas for a transaction or a contract deployment the function web3.eth.estimateGas4can be used on a testnet before the deployment of the contract.In order to reduce the future transaction cost of smart contracts, different gas-wasteful patterns are identified in [25,26], where the use of loops as for and while, non 256-bit and unnecessary public variables in the code increases the contracts deployment and execution cost.9. Reliance on a particular language: A smart contract is a software that will execute in a virtual environment distributed among the nodes of a blockchain.This software is written in a particular language that has some characteristics.All languages are not identical and do not allow the same computation.As an example, for deployment in a blockchain, it might be preferred to restrict the type or size of numbers so the computations are not too computationally expensive.Also, some languages used for smart contracts development are close to Turing Completeness, whereas others are not.In more detail, Turing completeness (named after Alan Turing, a pioneer in the field of modern computer science) is defined as the ability of a language to compute any Turing-computable function, i.e. to execute any recursive function, as while, if or for loop, among others.This property is problematic in smart contracts, as a Turing-complete language could run a while loop forever, depending on the memory usage, and thus overload the corresponding blockchain.
To overcome this possibility, most smart contracts languages are not Turing-complete (TC).However, Solidity language along with the Ethereum Virtual Machine (EVM) can be defined as a pseudo-Turing complete system, where Solidity can be considered as a deterministic TC language [23] but the gas cost limits artificially the EVM computational power, where the defined budget determines the maximum computational power and operations available for the smart contract.This prevents a smart contract from running indefinitely on the Ethereum blockchain, although Solidity language does not impose such a limit.Therefore, the flexibility of TC languages can be their biggest threat in smart contract applications due to security issues as highlighted by the DAO attack [27] and halting problems [28].This showed that a TC language could affect the expected contract solution, duplicate the amounts of money spent or create fraudulent withdrawal of funds from a contract.Unlike Solidity language, non-TC languages as Vyper [29] reduce possible attacks and facilitate the estimation of the required computational power per contract.The use of non-TC languages is discussed in [28] through the evaluation of computational requirements from 53757 smart contracts, where only 6.9% of them require a TC programming language to be implemented.Finally, it is also necessary for a smart contract enabled language to be a deterministic language, so the execution of a contract is the same everywhere, in every node.This ensures the consistency between the network nodes is maintained.

A sample energy smart contract
A sample smart contracting logic is shown in Fig. 3, using P2P energy trading as an example.The flowchart starts with the initialisation of the contract which prompts the command to read the capacity and price offered by the generators.It is assumed that the forecast, estimation and price selection is performed at the generator's end.The offer is then communicated to the buyers (consumers) and the bidding procedure starts.There is a variety of possible techniques for clearing the price.The most commonly used one is the Double Auction which ranks the bids and offers in ascending and descending order and evaluates a clearing price.The next step is to assess the physical feasibility of the allocations by inspecting the grid power flows.Then, the smart contract is updated with the outcome and the energy transaction is verified using the smart metre recording of the generator.Once verified, the total units and duration of generation are checked and any scaling and penalties are applied if necessary.Following this, the payment to the generators is authorised and the transaction is stored.This means that it is irreversible [11].
Algorithm 1 shows a brief pseudocode of a simplified smart contract for P2P energy balance update and transfer of funds.Separate data structures are created for consumers and prosumers as the information required from these agents are different.While the prosumer declares its hexadecimal identifier (i.e.address),    D. Kirli et al. in KWh and e-wallet details, the consumer needs to input its address,  in kWh, the per-unit bid price and also their e-wallet details.The matched pairs for P2P trading would be input in the    which compares the requested and offered energy.If there is excess energy, the energy balances are updated accordingly and the total price is set as the product of the per-unit bid price and the energy requested by the consumer.On the other hand, if there is not enough local energy offered, the price is equal to the per-unit price multiplied by the energy offered by the prosumer.
Finally, an example of Solidity implementation of a Peer-to-Peer energy exchange platform is proposed in Github [30] as a reference.It can run on a local Ethereum DLT such as Ganache.The deployment and interactions between peers and the smart contract are done through Python library web3.py(with corresponding code also uploaded to Github), which makes it convenient for energy researchers who may need to also interact with computational software such as MatLab.

Tools for implementing smart contracts
This section focuses on the software tools that are the most widely used to implement smart contracts in energy-related research projects.One of the most popular implementations of smart contracts consists of setting up a local private distributed ledger such as an Ethereum based blockchain, using tools as Ganache, that will create a blockchain with ten accounts already configured, with 100 ethers each.Then, running a smart contract on this blockchain requires uploading it to the Ethereum Virtual Machine through one account.Therefore, the steps to set up, and deploy a smart contract are the following: 1. Configuration of a local blockchain with nodes (virtual machines) and accounts, using Ganache 2. Develop a smart contract in a given language (e.g.Solidity or Vyper) 3. Compile the Smart contract code using the language compiler 4. Deploy the compiled code (byte code) in the blockchain using either Python or Javascript Web3 libraries 5. Interact with the contract (and the blockchain) through python or javascript commands that are sent to the address of the smart contract via a node of the local blockchain.
In terms of development and deployment of smart contracts or distributed applications (Dapp), researchers mainly used one of the three distributed ledger technologies that are: Ethereum (most used DLT that is mainly permissionless), Hyperledger (permissioned DLT) and IOTA (more scalable DLT as it does not require mining process to store data).
For Ethereum DLT, researchers can use the following implementation tools: • Similarly, hyperledger has associated tools that can ease the development and deployment of smart contracts as Hyperledger Cello which is an application that is used to manage, supervise and deploy multiple blockchains and associated smart contracts.

Six layers of energy smart contracts
Synthesising the information published in a variety of areas that range from settlement mechanisms for the agents to cybersecurity, a multi-layer architecture is proposed to describe the flow of information that starts with the input from agents.As shown in Fig. 4, from user input to the response of the physical assets, smart contract processes involve six different layers that the information travels through.The identified 6 layers are namely (1) Input from agents, devices and the grid, (2) Energy management algorithms such as consensus and control algorithms, (3) Native smart contracting functions that take care of the financial and gas transactions, (4) Blockchain functions of verification, encryption, etc., (5) Computational processes, i.e the different threads run by the virtual environment (EVM) and lastly (6) Communication layer that involves physical transfer of the information between nodes.
Layer 1 requires data from an agent, device and/or the grid.Some of the examples include bids and offer from agents engaged in P2P trading, availability signal from a smart charging EV and voltage levels from the grid to trigger an automated demand-side action.
On the second layer, this information is passed to the energy management algorithms which are designed by energy researchers.In the literature, this layer usually is novel and involves optimisation techniques.For instance, this may be an advanced efficient settlement algorithm to resolve the mismatch between contracted and delivered energy.Any sophisticated form of decision-making such as control algorithms, negotiations, etc. would be performed on this layer.Such computations can be deployed off the smart contract to avoid unnecessary computational costs.
The third layer involves programming of the contract which is often in a standalone smart contract language (e.g.Solidity).There are many examples where Layer 2 and Layer 3 are coded in different languages.Hence, they are expressed as separate layers.Registration of agents and devices, any form of financial transaction, etc. take place on this layer, as well as the calculation of gas usage.The output is a digital contract composed of code (and prose).
Layer 4 involves the integration of the smart contract on a block in the blockchain.This brings the aspects of verification, encryption, etc.A popular example is the Proof of Work used for Bitcoin.Implementation and computation take place on Layer 5 which involves interaction with virtual machines such as the previously discussed EVM.
Lastly, the information is transferred via communication protocols.This may involve machine-to-machine (M2M) communication via wired and/or wireless means.For instance, as a result, the smart contract could trigger the smart metre to send information to a software.

Application areas of smart contracts in the energy sector
After summarising the main features and advantages of smart contracts, and introducing some key techniques and steps required in their implementation, in this section we provide a systematic review of reported applications in the energy area.Smart contracts have been proposed and used in many applications, ranging from energy trading to the coordination of distributed assets -as shown in Fig. 5.The type of applications of smart contracts can be categorised into two main categories: energy and flexibility trading on the left-hand side, and distributed control on the right-hand side.We follow these two main themes in this section and present all the different areas of energy applications illustrated in the figure.

Energy and flexibility trading
As smart contracts run on a blockchain that has been initially designed to store financial transactions, the most intuitive application of smart contracts corresponds to trading and payment between two entities.As a result, in research, smart contracts are mostly used in the context of energy or flexibility trading applications.In these applications, the main objective of the smart contract is to facilitate the matching between consumers and prosumers (providing microgeneration and/or storage), but also to propose a secured and trusted payment or settlement mechanism.Smart contracts have been used for the following specific applications:

Peer-to-peer trading
Smart contracts are often employed for P2P trading applications.The smart contracts first receive the bids and offers from the different stakeholders (producers, prosumers and consumers), which usually also requires a deposit from the buyers.Different approaches are then used by smart contracts to match the buyers (consumers) with the sellers (producers).Approaches range from heuristic methods to more complex approaches that include double auctions and power flow validations [31], as shown in Fig. 3, that will be detailed in the market design category.In terms of heuristic methods, the smart contract usually matches buyers and sellers and validates a trade as the bids come.This matching can be performed by comparing the amount of energy and the price of incoming bids and offers [20].Once the smart contract has validated a trade, which consists of a price, an amount of energy and a time of delivery, the smart contract for P2P trading can then be used to analyse the monitoring of actual consumption and production coming from the smart metring infrastructure [32].This analysis can then automatically trigger the settlement within the smart contract in order to distribute rewards and penalties according to the contract condition.When P2P trades do not cover all the needs of consumers or the generation from producers, smart contracts can then facilitate transactions between the peers and the grid.[33] uses a smart contract-based ancillary service peer-to-peer energy exchange platform which acts as a ''virtual decentralised market authority'', negating the need for the presence of a physical central operator.This is tested with 50 nodes and prove the potential application in local ancillary services.In order to minimise the computation costs of their Ethereum platform, the proposed smart contract uses a continuous double auction (CDA) model.[34] uses the flexibility of EVs for P2P trading using a novel Proof-of-Benefit (PoB) consensus to remove the need for an intermediary.They also achieve demand response and lower power fluctuations by providing the right incentives.Finally, smart contracts can also be used as a support for P2P trading, i.e. the trading process is not implemented in the smart contract, but a smart contract can be called to process a specific function.For example, [35] uses a smart contract to allow consumers to request energy, but also to validate eligibility, and process the financial transaction.However, the trading process that consists in matching consumers energy requests with available energy in the microgrid, is done outside the blockchain, at run time.

Peer-to-grid
Although the P2P area corresponds to the vast majority of smart contracts applications reported in published research, some works also use smart contracts for P2G transactions, as it is explained by Khalid et al. [36].Indeed, after local P2P trades have been validated by a smart contract, remaining energy needs (or extra energy) can be traded between the consumers and the grid.In this case, the smart contract is used for billing purposes, but also to store and sign energy transactions between the prosumers and the grid [20,37], similar to the situation in the retail market category.When Peer-to-Grid transactions are required to compensate for energy shortage or surplus, the smart contract uses the grid electricity prices at the current hour in order to determine the amount of money required for the financial transaction.The P2G also considers vehicle-to-grid (V2G) examples such as [38][39][40].
For example, in [38] proof of authority is used to validate transactions and synchronise the data which are authenticated by authorised aggregators.Moreover, the recent work of [41] studies a setting where residential batteries are aggregated through a smart contract to provide forward bids on the wholesale energy market.

Retail market
Smart contracts can also be used for retail market applications, to allow consumers to choose a supplier, to sign a contract with the supplier, but also to securely store time series from the energy monitoring infrastructure and provide associated billing services [42][43][44][45][46].This is achieved by first allowing the DSO to register every smart metre to the smart contract.Then, suppliers can broadcast their offers for energy through the smart contract, which will authenticate interested customers by using the smart metre address and by requiring a money deposit.Payment is then executed by the smart contract after the monitoring and settlement period are validated [44].[47] uses a trading mechanism embedded in smart contracts which uses the market prices in China as a case study.A method called encourage-real-quotation (ERQ) is employed for determining the clearing price.The proposed method allows the generator to enter their offer after the consumers bid on their required energy amount.On the other hand, [45] uses smart contracts to create a contract between households and suppliers (once households have declared energy quantities and prices they accept to pay), to monitor the energy consumption and production of the household, and to process the settlement.
Similarly, smart contracts can be used jointly with smart metres to measure in real-time the amount of energy generated or consumed and automatically adjust demand and supply.Smart contracts can also help to implement automated activities such as defining electricity costs for a period, payment policies, times for buying and selling electricity.Indeed, by leveraging the features of smart contracts, we can increase the speed, reliability, scalability, and security of the energy market [48,49].

Demand-side response
In the current wholesale market settings, balance responsible parties and aggregators can contract ancillary services, in the form of flexibility from end-users to achieve equilibrium between energy supply and demand.For a demand reduction or increase, the aggregator requires the registered end-users to meet a given load profile.This process is called Demand Response (DR).Smart contracts can be used at different stages of this process.First, in the case of DR events, smart contracts can compute and store the forecasted baseline profile and the required profile for buildings that are registered to the DR event [50], or they can periodically define the available flexibility, prosumer energy profile and calculate the grid energy balance [51].Then, similar to the use of smart contracts in P2P transactions, smart contracts can be used to set up a specific contract between interested consumers and the aggregator, in which case the smart contract specifies the acceptance of the DR request, with the required load profile [52].Then, smart contracts can analyse the demand reduction provided by the buildings, by comparing the measured load profile with the forecasted profile.Smart contract design, from a game-theoretic perspective, has also been proposed for incentivising participation in demand-side response schemes [53,54].Moreover, appropriate billing and payment can also be automatically generated by a smart contract in order to reward or penalise consumers who met the targeted load profile or not respectively [2,55].

Market design
Finally, in the energy trading area, smart contracts can be used to clear a market in order to determine the prices of energy trades.Unlike the peer-to-peer category that corresponds to full peer-to-peer trades, in which a buyer buys energy from a specific seller, in this category, the application corresponds to hybrid peer-to-peer, as defined in [56], in which a buyer does not know which producer provides the energy procured.Hence, this category regroups applications such as double auctions [36,[57][58][59][60][61][62][63][64], but also more complex market design approaches that directly includes a validation of the trade from power flow computations, as it can be carried out using Distributed Locational Marginal Pricing (DLMP) and AC Optimal Power Flow (AC OPF) [31, 60,65,66].Also, [67] uses smart contracts to implement a modified Vickrey auction.In this application, the available energy from prosumers is computed by a specific smart contract and sent to a trading smart contract.The trading smart contract also receives consumers' valid bids, and determines the winning consumer bid as the highest bid, whereas the price is the second highest price.The smart contract iterates until all bids have been satisfied or no energy is left.P2P energy trading was also proposed in [68] for electric vehicles.Indeed, [68] implements a contrary auction mechanism in which discharging electric vehicles offering the lowest price are chosen to supply a local set of charging EVs.
Unlike auctions that can efficiently be implemented within smart contracts [69], optimisations such as AC OPF are too complex algorithms to be implemented in current smart contracts languages.Indeed, as an example, Solidity language does not support complex numbers computation.However, researchers proposed different ways to use smart contracts for these applications, as an offline optimisation from which the solution is stored in a smart contract [60], or by using the alternating direction method of multipliers (ADMM) algorithm, which allows a smart contract to coordinate other nodes that will process offline more complex computations as required by the optimisation problem [31,66].
Also, hybrid peer-to-peer trading through smart contracts has been implemented in [70] by using mathematical formulas for the matching of consumers and producers and dynamic pricing.Therefore, in [70], all consumers pay electricity at the same price, which varies in time depending on the ratio and difference between the total demand and the total supply of the community.
Finally, [71] uses a smart contract design to determine the right level of subsidies for solar panel electricity production in a community.Indeed, in [71], smart contracts are used as an instrument to compute automatically the linear Bayesian-Nash equilibrium that aims to compute the right level of subsidy a government should allow to solar PV production.In this case, smart contracts are used to gather the monitoring of solar PV production, to determine the subsidy level using Cournot quantity models, to automatically contractualise the agreement between households and the government, and finally to transfer money from the government to households that produced electricity from their solar panels.

Electric vehicle management
In the field of electric vehicle (EV) charging systems, smart contracts can be used for different purposes.First, smart contracts can implement lighter optimisation algorithms such as limited neighbourhood search with memory to balance the distribution of EV users among parking spaces while achieving fair profits distribution among the owners of EV charging places [40,46,72].
One of the most popular application areas of smart contracting is smart charging for EVs [73].Smart contracts are also used for peak load shifting and shaving by leveraging the flexibility of EV loads [74].Similar to [75,76] which deal with smart energy communities, [77] implements an energy trading platform amongst EVs in smart campus parking lots using local controllers.In [68], a smart contract was designed to allow P2P energy trading between Vehicle-to-grid-capable electric vehicles (producers) and all EVs (consumers).Finally, [78,79] focus their research on autonomous vehicles where they both use smart contracts for smart charging purposes.

Battery management
Smart contracts are also a powerful tool that can be used to securely coordinate assets that are distributed [80].In the case of batteries control, a smart contract can be used to store the information of distributed batteries, such as the state of charge or state of health, and automatically send control recommendations to all batteries in order to synchronise or prioritise the charge or discharge of the distributed instances, as it is shown in [80,81].Decentralised control of batteries has also been proposed in [41] where a smart contract facilitates the control of residential batteries to participate in wholesale markets.

Grid management
The development of the Internet of Things allows grid operators to have better monitoring, understanding, and control of their network and the power systems as a whole.In this context, smart contracts can be used to securely and synchronously store data from Phasor Measurement Units when a fault happens on the grid [82].Smart contracts can also be used to automatically coordinate actuators or take control decisions between contradictory set point requests from different assets of the grid [83,84].Finally, due to the security characteristics inherent to smart contracts, they can also be used to grant access to grid data, such as market data for example in [85].

Virtual power plants
The concept of Virtual Power Plants (VPP) involves the operator that monitors the production or consumption of different assets in order to better coordinate and optimise the aggregated production [41,86,87] or reduce curtailment [88,89].In this context, some authors [90] have proposed smart contracts to store and read data from distributed assets, in order to help for better synchronisation of the production.

Audit and certification of supply-chain
Smart contracts can also be used to establish a transparent supply chain.Both [91,92] take advantage of the self-executing and tamperproof nature of smart contracts.The former, employ the chain of custody method in order to calculate and assign renewable energy and carbon credits.Ashley and Johnson [91] observed significant reductions in time and cost as smart contracts eliminate the need for external auditing.This also immediately allowed the energy producers to monetise the credits.The latter uses a similar approach.However, the focus is more on issuing guarantees of origin and green certification.Pajic et al. [93] also acknowledge the auditable quality of smart contracts in the scheduling services of EV charging.

Internet of things (IoT)
Another suggested application for smart contracts in energy is IoT applications.In more detail, as Internet-of-Things concepts (IoT) become more widely used in the energy sector for smart cities and remote assets monitoring and control, there is more concern about the control and security of the data gathered by IoT devices, especially when it is managed centrally by a single system.To address this issue, ''PrivySharing'' provides a secure alternative with an encrypted private blockchain-based framework for smart cities [8,94].''PrivySharing'' enables data sharing with external parties via the use of a digital token called ''PrivyCoin''.As the authors show, in an IoT context, privacy is a key concern for smart contracts, as data can be transferred and shared between different parties for monitoring, bidding or other purposes.These data can include the geographical location of a prosumer, or other personal information, that should be protected.Therefore, it is essential to provide anonymisation through encryption, hash function or other means of anonymising so that other parties do not access the data transmitted between the owner and the receiver of a communication [8,94].In a similar approach to ''PrivySharing'', Tan et al. [95] performs privacy-preserving energy scheduling for energy services companies.Unterweger et al. [96] summarises lessons learned regarding privacy-preserving Ethereum-based smart contracts.

Smart homes and energy management systems
Lately, smart contracts have also been employed for home energy management systems (HEMS) in order to coordinate flexible loads and assets such as scheduling home heating and cooling.The secure nature of smart contracts plays an important role in the coordination of home appliances in order to minimise bills or decrease the user's carbon footprint.For Smart Home applications, smart contracts are used to coordinate assets, to automatically take control decisions (switch appliances on or off) depending on the state of some variables because they ensure the communication channel is secure [97][98][99][100].For instance, [101] proposes a ''smart-home-based IoT-Blockchain'' that employs three different sorts of smart contracts which allow access control, judging misbehaviour of the assets and registration of new policies to the access control.They demonstrate the application of the three contracts using Ganache, Remix, and web3.js.Rather than smart contract design, other publications focus on increasing the reliability of existing IoT services using the tamper-proof nature of the smart contracts [102].The scale within this application may vary from a single household to an energy community.Afzal et al. [3,103] manage the scheduling of appliances within the community to offer DR services and [2] coordinates a group of smart buildings using a network of smart contracts on the blockchain.

Capability of energy smart contracts
This section presents the capability of smart contracts.Smart contracts can be programmed to reach an agreement and verify the transfer of value between parties as shown in the example from Fig. 3. Here, we analyse the range of functions embedded in energy smart contracts in the literature.These functions can be triggered by external events or by the contract itself.The main functions categories implemented in energy smart contracts were classified as functions aiming to manage a portfolio of participants or contracts, market clearing, storing data, optimising a problem or running complex computations.The main characteristics of each of these functions' implementation are detailed below.

User and asset management
As most of the smart contracts in the energy sector are used to facilitate energy trades, an important set of functions implemented within smart contracts focus on the management of the users and the assets.Hence, one basic function of smart contracts corresponds to the registration of the different users (prosumers, consumers, producers) [104,105] or assets [44].The registration allows the users or assets to define their profile (e.g.prosumer, consumer, etc.), but also to link a monitoring device to their profile [43].This allows end-users to then authenticate themselves, using their smart metre address [36,44].Furthermore, the registration functions can also require a money deposit in order to validate the participation of an end-user in a smart contract.Smart contracts can also be used to grant access to data streams, as it is proposed in a function implemented in [85].Then, the management of end-users involves functions that update the list of end-users [36], but also that record statistics related to each agent, such as the quality of the electricity provided by prosumers in [42].Han et al. [20] proposes to store the type of producers (e.g.renewable energy generator) in order to allow buyers to access energy that follows their preference.
Similar to user management, some smart contracts implement functions for asset management, in order to sort and categorise assets, such as charging or discharging energy storage systems as proposed in [9,38].

Contracting operations
Smart contracts can be used to set up an agreement between two entities (e.g.agents, equipment, etc.) [42].Indeed, in smart contracts such as those described in [42], a smart contract broadcasts the list of available suppliers to every end-users, in order to help them find an adequate supplier.After the matching is completed between a producer and a consumer, the smart contract automatically sets up a signed contract between them, either for the retail market application [42] or for Demand Response events.This contract between two entities can include the amount of energy reduction/increase required, along with the time window within which the effort must be provided by the consumer [52].Finally, billing functions have also been implemented in smart contracts in order to automatically determine the daily or monthly bill between end-users or buildings and the energy provider [2,36,106].For example, in the context of a cooperative energy community, the smart contract in [2] provides a function embedded within the smart contract to compute the bill of individuals based on the total electricity price of the community.

Management of energy bids and offers
One of the main interactions of end-users with smart contracts is the submission of energy offers.Hence, most of the smart contracts for P2P energy trading implement a function that receives and saves the bids or requirements of end-users, as it was implemented in [3,20,31,59,67,104,105,107 -110].Bids can include the amount of energy, the time at which the energy is needed or available, the price that is desired to buy or sell the proposed quantity of energy, and finally, also the power [109].The bids can be specific and limited to particular assets, such as distributed batteries, as it is proposed in [110].Finally, smart contracts are also often used to validate a bid or to determine the eligibility of an agent given his/her deposit for example [67,105].Once bids and offers are received, some studies implement a broadcast function that aims to communicate the received offers to the registered end-users [44,109], or to specific trading partners [31].Other smart contracts allow agents to get access to a ledger so they can read offers, as proposed in [109].
Therefore, smart contracts can update the bids and offers that are received and stored.A function updates the remaining quantities of energy [3,109].Finally, when receiving a bid or offer, the smart contract can also ensure the feasibility of the bid, by making sure the end-user has made a deposit that is high enough to afford the requested energy quantity [109], or by ensuring that the offer from a prosumer can be honoured given the remaining energy in a battery [108].
In the context of smart contracts for demand response, a smart contract can also implement a function to allow an aggregator or an end-user to automatically accept or reject a flexibility offer [52].

Monitoring
As they provide inherent security in the communication between an end-point and the blockchain, smart contracts have also been used for monitoring purposes in the energy domain.Indeed, smart contracts can be used to gather measurement data from pre-registered monitoring assets, such as smart metres, by ensuring that the data is generated by a trusted asset.In the energy domain, smart contracts can implement functions to gather the monitoring of actual production and demand which are callable by the system operator only [2,37,42,43,52,55,90,107]. These measurements can then be used in the settlement and billing processes [111].Hence, it is necessary that prior to the measurement, the system operator registers the monitoring devices such as smart metres, as explained in Section 4.1 and in [44].Furthermore, system operators can also use smart contracts to synchronise monitoring systems such as Phasor Measurement Units (PMU) in order to store and facilitate access to the state of the network when a fault arises [82].

Market mechanism and market clearing
In energy trading applications, smart contracts are often used to clear a market, which consists of determining a single price for all trades by matching demand and production.In the context of smart contracts used in market mechanisms, they are initialised by a constructor function, called by the system operator, to set up the marketplace and start the state machine [59,112].
Following this, a function is implemented that automatically determines the trading price.There are different methods to achieve this.First, it can be determined through a double auction that maximises social welfare.In this case, the function ranks the offers in ascending order and the bids in decreasing order, selecting the intersection point as the global clearing price [20,59,107].Other methods used to determine the trading price can vary.In [3,36], the trading price for the whole community is the lowest price proposed by the sellers, whereas in [43] the trading price is based on a planned grid price, which is increased or decreased afterwards in the settlement phase through compensation formulas based on the quantity of energy that was produced or consumed.In [104], the price is determined as a mathematical function that depends on the total amount of energy surplus and demand, whereas [67] implements a Vickrey auction in which the buying price is the second highest price among consumers bids.A distinct approach is taken by Son et al. [112], who propose a privacy-preserving algorithm to determine the price of energy between two peers.The price is calculated as the average of the proposed prices from the seller and the buyer.This raises the concern that the market operator could take advantage of his position to be an intermediary who buys electricity at a cheaper price than the seller and sells it at a higher price to the buyer.To resolve this issue, an encryption of the bids is proposed to maintain privacy.
Along with the computation of the trading price, smart contracts include a matching function that allocates generation to meet demand, especially in the case of P2P contracts.Meng et al. [107] and Han et al. [20] propose to first categorise the energy offers between renewable-based and non-renewable-based in order to match the buyers' preferences [20] or to give advantage to the sellers providing renewable energy [107].Then, energy matching can be based on the output from the double auction where the bids and offers are ordered in opposite price evolution [20,59,107].In [104], the matching of buyers and sellers is completed by awarding the same percentage of energy to each energy request.If there is enough energy available, all the energy requests are awarded.If not, only a percentage of each request is awarded.
In [112], the buyer with the highest price bid is matched with the seller with the lowest price offer, which is made possible by managing two arrays-based data structures.A similar principle is used in [9], where the smart contract ranges the assets (energy storage systems) by priority.Hence, the assets that require energy with the highest priority are matched with the assets that need to discharge (produce) with the highest priority.In [3], the smart contract implements immutable predefined negotiation rules in order to match buyers and sellers.After the matching of P2P buyers was completed, most smart contracts implement a balancing function that ensures that energy requirements that were not awarded will be met by the grid at the grid price [20,107], as explained in 3.1.There is also work done investigating the interaction of different nodes, a margin of error and impact of competition and/or cooperation [62,63].
In the current centralised energy markets, smart contracts implement a settlement function in order to adjust the financial transaction to the actual energy transaction that occurred, as it is verified by monitors such as smart metres.The interest of using smart contracts for settlement resides in the potential reduction in the time for the settlement, as a smart contract could potentially automatise the monitoring of actual demand and production, and thus could quickly compute the balancing costs used in the classic settlement process.In smart contracts, the settlement phase also includes a redistribution of the remaining deposit money that users transferred to the smart contract.
In [107], the smart contract rewards prosumers if they meet the energy bid they submitted in the first place, and it penalises them if they produced less or more than what was agreed in the contract.In [113], the settlement includes additional grid prices fees to include the cost of balancing services.For demand response applications, the settlement function includes a verification that the realised demand reduction corresponds to the requested effort (with respect to a baseline estimation corresponding to the hourly average load over one month of data) [50,52].In [20], the settlement function uses the system imbalance prices from the transmission system operator in order to settle the difference between the actual and the agreed energy consumption/production, and provides rewards if the forecast used for the bids was accurate.[114] proposes an energy internet market in which electricity charges are automatically collected by the settlement function of a smart contract, and are then distributed to beneficiaries.For Electric Vehicle (EV) charging applications, settlement functions consist of updating the agreed price of the energy trade if the energy quantity overpasses what was agreed in the contract between the EV and the owner of the charging station [115].In control applications, the settlement function can require payment from control assets when the actual operation differs from the agreed contractual setpoint [83].[116] propose two novel settlement mechanisms embedded into smart contracts which are namely splitting and global balancing settlement.The former splits the sellers and buyers into two categories with a coefficient that denotes their contribution to the imbalance.The latter performs settlement actions for each responsible party individually.Other examples of advanced settlement methods used with smart contracts include P2P multi-settlement markets by Nakayama et al. [49] and multi-layered imbalance settlement by Danzi et al. [117].

Financial transactions
One of the most popular applications of blockchain is cryptocurrencies.Hence, most of the smart contracts used in the energy sector implement a function to process financial transactions between two entities.When smart contracts involve financial transactions between two peers or assets, it is good practice to add a payable function that requires money deposit when users or assets register or submit bids and offers to the smart contract [44,83].Then, the payment function can be triggered after the settlement phase in order to proceed for payment between a buyer and a seller [9,20,43,44,105,109,[113][114][115]118].Payment functions for energy applications are functions that are usually called by the operator only, that use the two parties account addresses (the buyer and seller, whose address must be payable) and the amount of money required from the settlement function, and that involves the pre-defined transfer function to transfer actual money from the buyer's account address to the seller's account address, as stored in the corresponding blockchain.Then, operators can call a close function to proceed with the transfer of remaining money from the deposit to each entity [52,83].

Data storage
As they are based on blockchains, smart contracts can be used to store specific data that are accessible only within the smart contract.In the energy sector, smart contracts are used to store the record of energy transactions or agreed-to contractual commitments, such as the energy quantities to be traded, price, parties involved in the case of P2P transactions, the amount of power and the time of delivery [36,60,108,115].
Smart contracts store the actual production and consumption [107] even though it is good practice to limit the quantity of information stored in the smart contracts.As mentioned previously, most contracts store information about buyers, sellers that submit bids and offers or assets that participate to control applications [36,43,44].This is usually achieved using hash tables such as mapping in the Solidity language.That is generated when the smart contract of a marketplace is created through the construct function.
For control applications, smart contracts store information about the current asset state, such as batteries state of charge (SoC) and state of health (SoH) [80] or the grid state from PMU measurements when a fault occurs [82], but also achieved operating points [83].In demand response applications, historic and baseline profiles are used in the settlement phase to assess the quality of the response which may be load increase or decrease [50,55].

Complex computations
Although contracting languages and the associated computational cost inhibit complex computations within the implemented functions, some studies prove the feasibility of consequent calculations within the smart contracts.For example, the demand response contract in [50] computes a baseline load profile for every user, based on the average of hourly load data over one month.For control applications, a simplified automated negotiation is implemented in [83] to allow control assets to decide on the competitive control setpoint.For P2P applications, [70] used a complex formula to determine dynamic pricing for energy transactions within a community, using tangent and exponential functions.
Lastly, optimisation can also be executed in a contract to achieve the optimal operation of power systems.AlSkaif and van Leeuwen [66] propose a contract that coordinates the AC optimal power flow (AC-OPF) computation-based on the general consensus optimisation form of the alternating direction method of multipliers (ADMM).The ADMM is used to solve a relaxed convex formulation of the AC-OPF problem by breaking it into smaller optimisation problems that can be solved locally outside the blockchain by every participating node with limited information.In this application, the smart contract is used to break the optimisation problem into smaller pieces, to keep track of participating nodes, to realise the consensus step from the ADMM algorithm and to distribute the required information to all the other nodes.Another example of optimisation in smart contracts is for battery control, presented by Baza et al. [81], where a Knapsack algorithm is implemented.This is solved in a polynomial time in order to find the charging schedules of the distributed storage units that are the most efficient in terms of energy use.
Additionally, [40] optimises the distribution of EVs among charging stations by solving a bi-objective mixed integer programming problem (MILP) by using a limited neighbourhood search algorithm with memory.[119] implements an open-source automated energy trading algorithm, written in the Solidity language, in their microgrid smart contract which was tested on an Ethereum blockchain platform.

Synchronisation and coordination
In the context of distributed control applications, smart contracts are used to coordinate and manage distributed assets.Hence, they can implement synchronisation functions such as in [80] where the smart contract synchronises different batteries from a close to real-time monitoring of their state of charge (SoC) and state of health (SoH).Then, smart contracts can act as a coordinator and aggregator for decentralised optimisation algorithms such as the ADMM algorithm for AC OPF resolution in [31,66].In [82], the proposed smart contract is used to retrieve the state of the grid from PMU measurements when a fault is detected by one PMU.In this case, the communication security and trust characteristics from smart contracts are highlighted to gather measurements of the monitoring assets.Although synchronisation is difficult to be achieved due to the time required for PMU measurements to be added to the blockchain, synchronisation could be performed afterwards if measurements include a time tag.In demand response applications, smart contracts such as those proposed in [3,59] implement control functions that securely send control signals to end users appliances in a coordinated way.As presented in [101,102], home energy monitors such as sensors and actuators can communicate securely with each other by using the require method from solidity language.Finally, smart contracts can also coordinate the execution of specific tasks by local endpoints by using the emit method, as it is presented in [2] to execute the optimisation of batteries and controllable loads schedules at the building level.Lastly, some smart contract applications adopt a state machine model in order to manage the transition between different tasks, functions or even other smart contracts, as presented in [36,107].

Smart contracts and AI: uses from energy and other sectors
This subsection concentrates on the literature that combines the use of smart contracts and Artificial Intelligence (AI).Some advanced examples from other sectors are presented to describe how smart contracts can interact with AI algorithms.AI techniques such as machine learning include a set of methods that can learn and identify patterns in the data in an automatic way, and then use these patterns to predict, cluster and assist in decision making under uncertain environment [120].Combined with automated smart contracts and decentralised data access, they have been used to design innovative and intelligent systems for various fields.
In terms of applications of AI and smart contracts in communication security, Fang et al. [121] have proposed a solution based on smart contracts and machine learning to enhance the security of 5G communication networks.AI-embedded smart contracts are adopted as a countermeasure against denial-of-service attack (DoS) attacks in a 5G communication network.The proposed solution adopts a flexible transaction fees scheme for smart contracts operations to limit the scale of DoS attacks.In this solution, the AI component is used to identify a DoS attack and increase the cost of transactions when a DoS attack happens.This way, the coordinator of a DoS attack would have a prohibitive cost to pay in order to maintain this attack.The training of the AI component in the smart contract being too costly and computationally inefficient, it was decided to train the AI model with a small portion of blockchain nodes.Then, these nodes broadcast the training results to other nodes that were not involved in the training.
Another application of AI with smart contracts is concerned with the analysis of fraudulent insurance claims.Deebak & Turjman [122] have proposed a solution based on smart contracts and AI-module consisting of an extreme boosting also known as XGBoost to automatically detect and predict fraudulent claims.However, the AI component is not embedded in the smart contracts and the training is executed separately.The outputs of the training are used then by the smart contracts for detection.
AI has also been used along with smart contracts in the health care system.For instance, in the work of Puri et al. [123], a rule-based AI is integrated into a smart contract to enhance the security of the healthcare data management system.Similarly, Kumar et al. [124] have used smart contracts to share computed tomography images of lung cancer patients securely across hospitals, while protecting the privacy of the patients.Then, a shared deep neural network model is used to learn from images of various patients to detect and predict cancer symptoms in the early stage.In this implementation, machine learning models are trained locally by each hospital, then, a smart contract aggregates and shares each model's weights with other locations constituting the blockchain network.Therefore, the AI training phase is not embedded in the smart contract.
AI is also combined with smart contracts for the application in retail marketing.Gupta et al. [125] have proposed AI-enabled smart contract for ice-cream retail marketing.The complete process of ordering, retailing and dispatching the product is automated using smart contracts.AI techniques are used to identify the user preferences to offer seasonal discounts.Furthermore, dimensionality reduction techniques (principal component analysis) is implemented to reduce the required number of computation within the smart contracts.Thereby, including smart contracts in the retail chain enhances the security of the whole retail market.However, here also, the AI module is not embedded within the smart contracts.
For edge computing applications, He et al. [126] have used the state-of-the-art machine learning asynchronous advantage actor-critic (A3C) algorithm to solve the problem of edge computing resources allocation for IoT applications.In this application, IoT devices send a computing request to the blockchain nodes, then, the smart contract assigns a specific edge computing node (ECN) to serve for the IoT device's computation.Here, the AI algorithm is used to help the smart contract select the optimal ECN for computation.However, this A3C algorithm is executed separately to the blockchain and the output is taken as input by the smart contract.
Recently, Miao et al. [127] have proposed a cognitive natural gas micro-ecosystem based on blockchain and AI.A Smart contract is implemented to securely automate financial transactions between gas producers, suppliers and consumers.An LSTM-based deep learning algorithm is used to predict natural gas flow and pressure.The gas supplier uses these predicted values to purchase gas from the producer in advance whenever the current selling price for natural gas is low.Machine learning is performed separately and not included in the smart contract.
Finally, for smart transportation system application, Khan et al. [128] have proposed a secure and intelligent electric vehicle transportation system based on smart contracts and machine learning.a double-layer optimised long short term memory model predicts the EV's motor temperature, which is then transmitted to a smart contract that will make decisions according to predefined rules, and send these decisions to actuators, such as the engine cooling system for example.Therefore, here again, the training and prediction are realised off-line, and predicted values are used as input to the smart contract module to make decisions.
In most of the applications reviewed, AI implementation and Machine Learning training are not embedded in smart contracts, mostly due to the computational costs.Therefore, AI algorithms are executed separately whereas their outputs are used as inputs to smart contracts.As a result, the integration of AI into smart contracts with higher efficiency and low cost is still an open research question and challenge.In particular, in the energy domain, research works that combine smart contracts and AI techniques are still rather rare, so this seems a promising area for further work.

Review of innovative industrial and academic projects
The possibility of automatic processing in a decentralised and secure way using smart contracts has motivated the creation of a large number of projects related to power systems in different areas, such as energy markets, data storage, energy billing and CO 2 traceability.These projects use public and private blockchains with different consensus mechanisms, according to the requirements of each implementation, where the permissioned blockchains are gaining popularity due to the capacity to control access to the chain, even though -unlike open blockchains, perfect anonymity of participants is not always guaranteed.In order to show the trends in the adoption of smart contracts in the energy industry, we compiled a list of implementations and demonstrators.The following is an indicative list of projects that have created an impact in the smart contract industry and academic community and presented innovations or novel implementation of smart contracts in the wider energy industry.An itemised list of 13 companies and consortia working in this space is also provided in Appendix B. Table 2 summarises the aims, consensus mechanisms, location and platforms each project uses for energy smart contracting.The list also provides a spatial insight into the use of smart contracts in various countries such as Australia, Italy, China and the UK with a concentration of projects in Germany and the USA.

Energy web foundation (EWF)
A non-profit organisation founded by Grid Singularity and the Rocky Mountain institute.EWF's mission is to accelerate a customercentric electricity system view using blockchain to facilitate the deployment of decentralised apps and technologies.In 2019 the EWF launched the Energy Web Chain (EWC) [129], based on Ethereum using a public and permissioned Proof-of-Authority (PoA) consensus mechanism, promising an increase in the transaction capacity by 30x and a decrease in energy consumption in 2-3 orders of magnitude in comparison with Ethereum.

Grid singularity (new)
A German Start-up focused on a decentralised energy exchange platform for local communities.In 2018 presents the Decentralised Autonomous Area Agent (D3 A) Market Model [130], an open energy exchange engine to model, simulate and operate energy trading markets in local communities.The energy exchange can be operated by a unique DSO or multiple agents, using smart contracts to define the energy trading and matching between the customers.

Power ledger
Australian company founded in 2016, focused on peer-to-peer energy trading.Power Ledger deploys a dual-token ecosystem [131] with a PoA consensus mechanism to decrease energy consumption, limit double-spend tokens and control the access to the chain.The Power Ledger platform allows the DSO or prosumers to manage a microgrid with a real-time energy market, traceable renewable energy certificates, manage energy peaks using ESS or choose the type and quality of the energy.

LO3 energy
founded in 2012, LO3 Energy wants to improve the communitybased local generation and energy exchange.The Brooklyn Microgrid [132] was developed by LO3 Energy as a proof-of-concept peerto-peer energy trading using existing grid infrastructure.The gained experience in the Brooklyn Microgrid helps to develop an energy exchange platform called Exergy [133] as a permissioned data platform for peer-to-peer tradings, and the Pando platform [134] that can be used by the DSO to pool local resources and establish an energy marketplace, based on bidding auctions between business and prosumers.In December 2019, L03 Energy along with Green Mountain Power deploys a pilot energy marketplace called Vermont Green [135] as the first US authorised marketplace.

Prosume.io
founded in 2016, prosume.io[136] proposes a platform based on smart contracts, IoT devices and the Prosume token with multiple applications, including peer-to-peer energy trading, smart billing, grid balancing and trading processes optimisation for electricity and gas, according to local laws in each country.

IBM
In October 2016, IBM launched Hyperledger Fabric [137], an opensource, modular and permissioned blockchain focused on business.Hyperledger includes modular consensus protocols, whereas Chaincode is the equivalent of Ethereum smart contracts.In association with IBM, Energy Blockchain Lab [138] creates a decentralised carbon credit management platform in China that expect to cut between 20%-50% the average 10-month carbon asset development cycle.Another relevant energy applications based in the Hyperledger are Car eWallet [139], Sunchain [140], and Tennet [141].

Share&charge
A German foundation focused on e-mobility.Share&charge [142] promotes the Open Charging Network (OCN) as a decentralised solution for EV charging services.Different services for charging stations are included, such as Green certificates, instant payment and eRoaming contracts.These services are provided by external companies using the OCN implementation with the Open Charge Point Protocol (OCPP).

Results of the systematic review
In this section, we present the results from our systematic literature review.As shown in Fig. 6, while the research trend for the use of smart contracting for energy applications started in 2011, it remained low key for 6 years.It is worth noting that much of this early, pre-2017 literature concerns smart legal contracts (also called Ricardian contracts), a rather different concept.Ricardian contracts are often very complex to define and crucially they are not implemented on a blockchain and often not even necessarily web-based.While they attracted academic interest, they saw limited practical applicability.The research outputs rapidly increased after 2017, as the use of blockchain and DLT-based smart contracts were introduced and started to grow in popularity.The number of publications per year reached a pre-COVID peak in 2019 with 88 publications.This trend is likely to continue as smart contracting in energy attracts increasing interest as a means of distributed control and also aids the deployment of emerging local energy markets.
Based on our systematic review, we divided the 178 papers into 11 key application areas which are discussed in detail in Section 3. The most prominent research area for the use of smart contracts identified are P2P energy transactions, which are the main topic of almost a quarter of the literature works reviewed.Following this, 17% of the works propose smart contract-based solutions for energy markets such as market clearing and settlement, while 14% employ smart contracts for EV management which includes smart charging and coordination.
We grouped these 11 areas into two main themes which are namely (1) Energy and Flexibility Trading and (2) Distributed Control; these are presented with blue and green shades in Fig. 7. Around 60% of the reviewed literature works feature the theme of energy and/or flexibility trading (which includes P2P, market design, DR, retail market and peerto-grid).On the other hand, the theme of distributed control is dealt with in 35% of the works reviewed.Nevertheless, the applications areas are more diverse including assets such as batteries, EVs, smart homes, VPPs, etc.More than half of the distributed control papers focus on the coordination and scheduling of EV charging, as they are foreseen as a critical challenge for the power systems.The remaining papers address the challenge of grid management, whether this concerns the control of voltage control in the distribution grid or allocating control tasks amongst system operators.Another highlight is that 3% of the reviewed literature uses smart contracts for carbon audits and certification.This is anticipated to be a powerful method of carbon monitoring for meeting the net zero-emission goals.
Similarly, Fig. 8 shows the contribution and explicit use of smart contracts functions (as presented in Section 4) by energy researchers.It is important to note that implicit use of functions (such as financial transactions for example) was not captured in this graph, that only displays functions or capabilities explicitly used and mentioned by researchers.The most used capability of smart contracts has been their ability to clear a market, either using auctions or other custom algorithms.This capability of smart contracts is tightly linked to another functionality embedded in smart contracts that is the management of bids and offers before clearing a market.This management corresponds to all the functions aiming to receive and store the bids and offers from the different buyers and sellers of energy.The high proportion of implementation of these functionalities shows that smart contracts in the energy domain have mostly been used for market applications.Then, other functionalities of smart contracts are equally represented in the literature, including the synchronisation of assets for distributed control, but also storage of energy related data, financial transactions and monitoring.
We also mention that only around 30% of the research work reviewed were peer-reviewed journal research articles, with the rest being published in conference proceedings, chapters of books resulting from physical and online meetings and similar venues -which are more geared towards fast dissemination.This reflects both the surge of recent interest in the topic from the energy community and the fact that this is a fast-moving research field, with many recent developments.
The keywords used in all reviewed publications were analysed and the top 20 keywords were ranked according to their frequency of use.Fig. 9 is a word cloud diagram that shows the most common phrases in large yellow font and the less frequent ones in small dark blue font.As shown, the most frequent phrases apart from smart contracts are ''blockchain'' and ''smart grid''.
In summary, a total of 178 peer-reviewed publications -which resulted from the systematic Scopus search and relevance check, were categorised according to their application area within the field of energy.In Appendix A, Table 1 categorises each publication according to its energy application area.

Discussion
In previous sections, we have provided a systematic review of the fundamentals of smart contracting, and the different smart contracting types and techniques used in the energy sector.Some use cases and commercial initiatives of smart contracts for energy were also presented.Based on this analysis, in this section we discuss the key challenges and opportunities we identified for smart contracts in the energy field.

Scalability of energy smart contracts: Opportunities and threats
First, this subsection discusses the opportunities and threats associated with scaling up the use of smart contracts for energy applications.
Here, we summarise the key issues observed in the literature and suggest solutions that incorporate our outlook on energy systems.We also highlight the main advantages of smart contracts such as automation, and reduction in time and cost of market operations.

Cyber-security and privacy
One of the major challenges in applying smart contracts in any sector revolve around cybersecurity, confidentiality and privacy which involve identity theft and data leakage.For what concerns cybersecurity aspects, the challenges are associated with the fact that some smart contracts decisions can be operational decisions controlling electrical grid assets, which can become a threat to the energy system.To address this issue, encryption with private keys and the addition of a hash ensure that the data received was generated by a trusted entity.The append-only and distributed nature of smart contracts provides an advantage [55,91] when used with cryptography and hash functions to protect the data [143,144].Furthermore, the risk of denial of service of the blockchain that could happen from a smart contract running infinite loops with heavy computation tasks is limited by strategies such as gas limitation.To illustrate this cybersecurity aspect, [145] provides a study on ''cyber-resilient'' systems whereas [146,147] show the robustness of smart contract-enabled control of battery systems against cyber-attacks.
Smart contracts are tamper-proof and immutable, in the sense, their code is self-executing and cannot be stopped by any single party,  once the contract is deployed and written on the blockchain.While often viewed as a strength, their immutability could be a weakness for smart contracts, as the contract code defines each interaction, where errors or bugs can generate unexpected results and consequences if it has not been thoroughly tested and validated [148].The relevance of immutability in smart contracts is best exemplified by the infamous ''DAO attack" [27,149].A malfunction allowed the withdrawal of an amount of ethers much higher than the original deposit.The losses associated with the malicious transactions were estimated to be over US$ 150 million [150].The permanent nature of the blockchain forced the attackers to hard fork in order to ''erase'' the malicious transactions.This sparked a new set of coding regulations and best practices to work with the deterministic nature of smart contracts which elevated the security measures [151,152].
Despite these concerns around cybersecurity, smart contracts are also seen as a solution to increase the reliability of the whole energy chain by removing the single points of failure such as central control by a unique server or the reliance on a trusted third party (TTP).A single point of failure can pose a threat to the scalability of energy systems as it is bounded by the capacity and capability of the TTP.Secure private blockchains offer a reliable solution to this problem, as it was shown in Section 3.2 by works such as [11,153] where smart contracts are shown to be helpful for grid operations.Similarly for market applications, the work from [154] allows the users and producers to negotiate energy directly through smart contracts, without any TTP.
Another potential danger of smart contracts, especially in new projects, is damaging self-executing code inserted in a smart contract without the counter-party being fully aware of its effect.In the worst case, this can lead to a complete loss of funds for investors and goodfaith participants, after the developers (who often stays anonymous) leave the system, executing a so-called ''rug pull".Examples of this have unfortunately become increasingly frequent in the use of smart contracts in decentralised finance (DeFi) and the sale of non-fungible tokens (NFT) applications.For example, in DeFi, the project developer could intentionally write a backdoor in the project's smart contracts, that allow them to drain or manipulate tokens that should be locked or used as a stake in PoS protocols.In recent years, there have been DeFi projects in which developers, using these smart contract backdoors, extracted valuable currencies such as ethers or bitcoins to their own digital wallets and then left the project, leaving other parties holding a worthless cryptocurrency.Another example from the NSF domain could be one in which one party sells a non-fungible token (NSF) to a picture, video or other digital assets through a smart contract.Yet, unknown to the buyer, the project smart contract defining the sale contains selfexecuting code that specifies that for any subsequent re-sale, some percentage (often 1/3 or more) of the sale price is automatically transferred to the account of the initial seller, resulting in a loss for the buyer.
Examples such as the above in the energy domain have been, so far, very rare -to the best of the authors' knowledge.This is both due to the fact that the use of smart contracts in energy is still in their infancy (compared to decentralised finance and NFT tokens), and most projects are research-oriented in nature, using a private blockchain, rather than a public one.Yet, as smart contract adoption in energy settings increases and becomes more commercially oriented (as it has in decentralised finance and NFT), these security challenges are likely to become more acute.
Finally, the ability to authenticate bids and offers is also essential, as fake bids/offers may be sent to sabotage the system using smart contracts, such as a P2P microgrid.For instance, bids and offers can be secured using private keys based encryption, whereas transactions can be authenticated by authorised aggregators [38].

Implementation and communication risks in smart contracts
Although the majority of the papers reviewed only describe projects at a proof-of-concept stage, some researchers deployed energy smart contracts on operational blockchains.These are especially Ethereum based, and rely mostly on a private blockchain.Moreover, some works present the use of single-board computers, such as Raspberry Pis to emulate a physical private blockchain with nodes physically hosted in a laboratory, which allows further experiments to be carried out [155,156].[155] creates a comprehensive testbed using a stacked formation of Raspberry Pis for testing communications characteristics during smart contracts execution on hyperledger.[156] dedicated one Raspberry Pi per agent and used these Raspberry Pis as light nodes of an Ethereum blockchain.Such testbeds could be used to assess the impacts of simulated network latency or communication errors.This will become more significant for smart contracts used in market applications, especially when the settlement periods decrease in length from 30 min to shorter periods, such as 5 min.Indeed, in such a development, the impact of latency and bandwidth would increase.
Communication and synchronisation issues can play a significant role, especially in real-world smart contracts that have a ''live" deployment.For example, a smart contract whose self-executing code states it must be closed once the clearing price in a certain market (called an ''oracle") drops below a certain level.It is possible that in an illiquid market prices are highly volatile, experiencing a lot of fluctuations, even within an hour or number of minutes, hence the price may drop below a critical level for a few minutes, but then be restored some minutes later.Hence, there is a risk the contract will be closed (or not closed) depending on how frequently the price is updated in a particular smart contract implementation or device.Such ''oracle risks" would need to be taken into account in future implementations in energy systems.For example, spot prices in energy markets are known to be highly volatile, especially in those markets that use locational marginal pricing [157].If the spot prices are used as ''oracles" for deciding to execute or liquidate a smart contract, then the contract design must account explicitly for this volatility.

Computational expense of smart contracts
As more assets take an active role in the energy systems, their associated computational expense will increase.The benefit of automation should outweigh the cost of computation and the associated problems such as latency.
Although most of the papers reviewed did not address the subject of the cost (in gas units) of running smart contracts, [158] highlights that this cost will not be a negligible factor, especially when smart contracts are deployed for electricity market applications.
Therefore, [159] proposes a way to predict the approximate performance and data requirements of contract execution for Ethereum-based smart contracts.This would be a valuable addition to smart contract design and a good metric for comparison of the performance of smart contracts proposed in energy related research papers.
Most smart contracts require a certain amount of data from sensors and smart metres.The deployment of smart contracts on the blockchain would be limited by the bandwidth and computational power required to transfer and process the necessary data.Fog computing (also known as edge computing), offers a solution to this problem, by the processing of data at a local level, before transferring the results to cloud-based servers [160][161][162].This would result in reduced bandwidth and cloudbased storage requirements.Gai et al. [163] present an example of a permissioned blockchain system that uses fog or edge computing for a smart grid application.
For what concerns energy market operations, market clearing computations running within smart contracts can be made more efficient by allowing the sharing of more information within the participants which reduce the number of unknowns and the level of discrepancy between bids and offers.For instance, the encourage-real-quotation (ERQ) rule [47] allows the producers to make an offer after the consumers place bids.This decreases the difference between bids and offers and speeds up the clearing process.
Another key concern is the volatility in price in registering and running a smart contract on a blockchain.In more detail, many current and proposed energy smart contracts are currently deployed on the Ethereum blockchain, where the cost is expressed in subunits of ether called gas.However, the price of gas can be highly volatile D. Kirli et al. between subsequent weeks and even days, hence the moment of registering/deploying a smart contract needs to be chosen very carefully, to minimise both financial and environmental costs.
Finally, it should be noted that the cost for a smart contract running is not only financial.Smart contracts also have an environmental cost, since running a smart contract and associated DLTs requires considerable electricity consumption.Hence, the environmental impact of smart contracts depends heavily on the source of electricity generation.As the number of energy transactions is expected to increase due to innovations such as peer-to-peer trading, in order to scale up, the existing blockchain consensus protocols used to deploy and run smart contracts will need to be re-designed to minimise their energy consumption.The Ethereum Foundation aims to transition to a Proof-of-Stake (PoS) protocol (from the current energy-consuming Proof-of-Work) could provide a significant step in this regard, if/when it happens.

Novel market mechanisms
[164] demonstrated that the settlement processes are faster due to the embedded monitoring and verification functions of smart contracts.As the number of peer-to-peer energy trades increases, the market regulation mechanisms need to be adapted, especially to ensure a continuous balance between production and consumption, such that the frequency and voltage are maintained within acceptable limits.Therefore, novel settlement mechanisms dealing with contribution to imbalance on an individual, group and global level could be designed to address the increase of agents participating actively in energy trading.The novel settlement mechanisms could include imbalance contribution coefficients as proposed in [116], could be specific to a particular type of energy traded, such as solar energy trading settlement [113] or lead to the emergence of multi-layer and multi-settlement markets [49,117].
Another concern regarding smart contracts in energy trading is fairness and the formation of oligopolies.Intuitively defined, an oligopoly represents the domination of the market by a small number of large producers.Deval and Norta [165] describe an improvement of the Proof-of-Stake with lifecycle governance of smart contracts that decreases the risk of oligopoly formation.Other work has considered the issue of fairness of market mechanisms in smart contract design.For example, Danzi et al. [166] use proportional-fairness control in a simulated microgrid where all assets contribute to the overall action equally.Finally, market designs should also consider exceptions such as system failures (e.g.fault at a line) that could inhibit the actions prescribed by the smart contract.

Software requirements
Most researchers in energy modelling are not familiar with using smart contracting languages, such as the popular smart contract programming language Solidity.The fact that most smart contract design and modelling takes place on Solidity, rather than in the languages used by the energy systems modelling community, inhibits the research in energy smart contracts.For instance, unlike Python, Simulink does not have the right communication protocol to directly interact with the Ethereum node.There is ongoing work such as [167] which develops a solution to this issue and presents an example smart contract in Simulink.The work by Nothold and Coil-Mayor [156] and the Github code available in [30] use a combination of MatLab/Simulink, Python and Solidity -with Python used to facilitate communication between the other two platforms.Indeed, Python3 is a suitable solution to ensure interoperability between the research application code in which agents are modelled (usually written in Python or MatLab), and smart contract code, implemented in languages such as Solidity.Finally, Solidity's limitations such as the lack of some data types or mathematical functions are an obstacle to the implementation of smart contracts for energy use cases.For example, the fact that Solidity does not allow exponentiation for real numbers makes it unsuitable for power flow computations.
Another trend observed in recent years, due to the increasing complexity of smart contract code, has been to employ specialised companies to verify and certify the code against errors and specially security issues, such as potential backdoor attacks. 5This is important as, once deployed, the smart contract code is self-executing and harder to correct in a decentralised environment.

Legal issues related to smart contracts design
For energy applications, the contract design depends on the applicability of the law and the local legal framework which requires them to be adapted or interpreted, introducing new requirements to the programming of the contract.For peer-to-peer trading, the definition of the interaction between the participants as a Business-to-Consumer or Consumer-to-Consumer can change depending on how the contract was coded.For instance, if a prosumer is considered to be a business, they would need to contribute to grid balancing in Germany (according to the German Energy Industry Act) [168] and add a withdrawal policy according to the consumer rights law in the EU [169].According to the EU Renewable Energy Directive [170], a ''renewables self-consumer'' consumes local energy that is generated behind the metre.This invokes barriers against energy trading within communities.Similarly, the Dutch law requires a supplier certification for selling energy to the grid [171].
To summarise, how an entity is considered in each market defines how the smart contract needs to operate and the local laws need to comply accordingly.On the other hand, new definitions and regulations are required to make smart contracts compatible with new energy markets or services.
Advances in the energy trading process such as the use of automated bids and offers may generate market distortions.Especially, we argue the use of smart contracts in wholesale electricity markets will give rise to a need to review the EU's financial market regulations [172]: • Regulation on Wholesale Energy Market Integrity and Transparency (REMIT) -prohibits insider trading and market manipulation and requires extensive reporting obligations.• Markets in Financial Instruments (MiFiD II) -introduces authorisation requirements for investment services.Regarding peerto-peer energy trading, MiFiD II discusses the use of a virtual currency.• European Market Infrastructure Regulation (EMIR) -aims to increase transparency in Over-the-Counter derivative markets, mitigate credit risk and reduce systemic risk [173], where trading companies must report their contracts to Trade Repositories (TR), which at their turn report to the authorities [174].
Enerchain [175] is an energy trading blockchain for peer-to-peer transactions, specially designed in order to try to resolve these issues.It includes tools that ensure trades are compliant with REMIT.Some efforts are being made in different countries to include and enable the use of smart contracts in energy markets.In Germany, the project BEST (Blockchain-based decentralised energy market design and management structures) aims to develop an open-source electricity market bidding system, supported by the German Federal Ministry for Economic Affairs and Energy [176].One of the research topics in BEST is about the requirement for such a legal energy framework and how it complies with existing frameworks.The ''Blockchain strategy of the Federal Government'' [177] stimulates innovation, testing and application of blockchain technologies in the German industry.
For services that imply data storage issues, the General Data Protection Regulation (GDPR) [178] in Articles 17 and 21 introduce the capacity to delete personal and sensitive data from databases.GDPR introduced 3 principles that are relevant for smart contracts in energy [179]: 1.It considers the existence of a legal person who can fulfil its requirements.The basis of blockchain and smart contracts is decentralisation and operation without third parties, but the GDPR requires the presence of an administrator or manager who can manage sensitive information.2. It assumes that data can be erased or modified to comply with legal requirements.However, the immutability of blockchain does not allow tampering -however, data access can be restricted, and transactions can be reversed by adding the reverse transactions in subsequent blocks of the ledger.3. The GDPR assumes that data can be processed to be kept a minimum number of copies of data.The blockchain stored the data in each node connected using append methods, which is against the data minimisation principle included in the GDPR.
These three principles can affect the operation and decentralisation of smart contracts.Hence, it is necessary to research how the GDPR requirements can be fulfilled as most of the energy data stored may be considered sensitive.One proposal is to introduce a third party such as cloud storage systems (e.g.Interplanetary File System and StorJ or local resource servers) [180] or a data manager.The latter could include functions in the contract to limit internal data access after a time interval, introducing hashing and encrypting techniques to anonymise the stored data [181].

Knowledge gaps and areas of further research for smart contracts for energy systems
In this subsection, based on the above discussion, we summarise some of the knowledge gaps identified from our systematic literature review.Specifically, we identify a number of open questions that researchers in this field need to address, in order to allow smart contracts to become a truly useful tool for future energy systems deployment.
First, an open area requiring further research and attention in smart contracts is cyber-security.Smart contracts are, by definition, selfexecuting and tamper-proof once agreed and deployed on a blockchain -in the sense that it is hard for a single party to stop or change their execution.While this is a clear advantage that has the potential to enable true decentralisation, this also involves considerable security risks and vulnerability to potential attacks, if the smart contract code is not properly checked before deployment.So-called re-entrancy attacks (such as the well-known DAO attack whose only solution was a ''hard fork" in the Ethereum blockchain, splitting it into 2 crypto-currencies -see Section 2.2 for a discussion) is one example.Moreover, it is also possible for the smart contract developer itself to build an intentional ''backdoor" in the smart contract code, of which the party accepting the contract is not fully aware, and which are impossible to change once the contract is deployed on a blockchain.Such a backdoor could, for example, specify that the other party will automatically pay the contract maker a commission on each future sale, or could even enable one of the parties to withdraw valuable digital assets or cryptocurrencies to their own digital wallet, executing a so-called ''rug pull".As the use of smart contracts in energy systems has, so far, been mostly geared to research and demonstration projects (usually run by honest research institutions or foundations), this has not been a significant issue in energy systems yet.But, as smart contracts gain wider adoption in commercial energy projects, the security and verifiability of smart contract code is an aspect that needs to be considered.A possible solution is to employ companies and authorities that verify and certify smart contract code before deployment, as is current practice when deploying smart contracts in decentralised finance (DeFi) applications.
Another key challenge that smart contracts in energy face are scalability and questions of energy use.So far, most smart contract projects in the energy sector have been relatively small scale, and/or implemented on a private blockchain (as opposed to, e.g.deployment on the public Ethereum blockchain, which requires considerable gas payments).However, as smart contracts in energy scale up and applications become more commercial in nature, the constraints and costs of real implementation (both financial and environmental) will need to be considered carefully and mitigated.Currently, the most popular platform for implementing smart contracts, Ethereum (though the Solidity language, also used in the illustrative example for this paper) charges a cost in a sub-unit of Ethereum called gas.Yet the cost of gas can be substantial -especially for a complex contract, and moreover, the value of gas is often highly volatile.Besides the financial aspect, there is an environmental impact to consider, in the energy that is consumed just to run the Proof-of-Work protocol underlying Ethereum.The transition of Ethereum towards a Proof-of-Stake protocol (if/when it happens) should reduce this idle energy consumption very considerably, but still this requires consideration of what computations should be deployed/run on a public blockchain.
Third, a very important issue -also highlighted in Section 4.10 of the paper is that smart contracts are not particularly ''smart" in themselves, in the sense of having embedded Artificial Intelligence/machine learning capabilities.This is both due to the computational cost of executing complex code on a distributed public blockchain, but also because smart contract programming languages are often restricted, due to computational and security reasons (for example Solidity/Ethereum limits recursive calls and exponentiation operations, and some other smart languages are even more restricted).This is clearly a direction where further research and development effort will be needed, as has been achieved in other domains where smart contracts are applied, such as decentralised finance.One potential solution is to have smart contracts as part of larger frameworks where AI-enabled devices perform learning and decentralised control (for example of available generation, or demand-side flexibility [120]), and make transparent, verifiable commitments to other parties in the system using smart contracts.
Finally, more research is needed from the energy and power systems community to develop smart contracts with capabilities to enable intelligent management of power networks.Smart contracts that integrate uncertain generation/loads and perform, e.g.ADMM computations have already been proposed, but augmented by AI-capabilities, smart contracts could play a key role in achieving more decentralised, flexible and ''self-healing" energy networks of the future.

Summary of the contributions of the paper
This paper presented a systematic review of the peer-reviewed literature featuring the use of smart contracts for energy applications.In addition to a corpus of 178 papers, identified based on a systematic search of the published literature, we also analysed 13 different projects that use energy smart contracts.We categorised the energy applications into two main streams: Energy and flexibility trading and Distributed control.The former encompasses 65% of the reviewed literature.In the opinion of the authors, this share is only likely to increase, as energy markets continue to get decentralised, with individual prosumers increasingly taking control of their own energy generation, storage and consumption.The most common areas of smart contract use were identified as P2P trading, market design, EV coordination, grid management and DR control.This is because smart contracts are seen as a solution to the implementation difficulties of these local energy management strategies in terms of automated negotiations, billing, settlement, etc.The most popular features reported in energy smart contracts are market mechanism functions (including market clearing), synchronisation and coordination functions, data storage capabilities and financial transactions.
Based on the solutions presented in the literature, we developed a novel 6-layer architecture (see Fig. 4) that summarises the concept of smart contracting for energy applications in Section 2.7.In addition to the systematic review, which forms the main body of this paper, we also present a sample ''Energy Smart Contract'' in Section 2.5 with example pseudocode for a simple peer-to-peer energy exchange.Alongside this, there is also background information in order to bring the reader up-to-speed with the recent developments in this field.

Recommendations for smart contract adoption in energy applications
Overall, this review concludes that there is clearly considerable potential for the use of smart contracts in the energy sector.The opportunities are wide ranging, from automation of billing and market mechanisms, such as market clearing and settlement functions, to distributed control of energy assets.The ongoing trend towards more transactive, peer-peer and community energy systems [182], in which energy prosumers are increasingly empowered to take control of their own energy supply [183] can be a key driver for smart contract adoption.For instance, future community energy projects could be supported by blockchain-enabled Decentralised Autonomous Organisations (DAOs), which use smart contracts to self-enforce mutual agreements between their members.
Yet, there are also considerable challenges and threats that need to be carefully considered when implementing smart contract solutions in energy.Based on our study, we believe it is constructive to end this review with some best-practice recommendations or attention points for future deployment of smart contracts in energy: 1. First, it is important to ask if smart contracts are the right tool for the specific energy system problem being considered.While smart contracts can be powerful tools in building truly decentralised energy systems, this need for decentralisation must be balanced against potential disadvantages, such as high security risks, high energy consumption and high complexity of implementation.For many applications, a possible solution could involve considering the trade-off between which computations should be done inside the smart contract and executed ''on the blockchain", and which computations (such as complex learning or optimisation) are best performed ''off-chain".2. When agreeing and deploying a smart contract, it is crucial to consider cybersecurity aspects and to have a full understanding of the underlying code.Once deployed, a smart contract is self-executing and tamper-proof, making it very hard to correct by any single party, and hence any exploits in the code that may it vulnerable to cyber-security threats needs to be carefully considered.Moreover, parties also need to consider that the counter-party has not introduced some unknown ''backdoor" into the potentially complex code of a smart contract, that could unilaterally favour them in the future.One way of doing this is to employ a company to verify and certify the code of complex smart contracts before committing to investing in a project, as is standard practice in smart contracts for decentralised finance and NFT applications.3. The costs of the complexity of implementation and cost of deploying the smart contract must be carefully considered.This means both financial costs (in terms of cost of gas on Ethereum) and environmental and energy costs, in running the Proof-of-Work protocol on the underlying blockchain.So far, many smart contract projects in the energy domain have been more proofof-concept or demonstration projects, and run on a private blockchain.But, as projects become more commercial and are run on public blockchains, these deployment costs can become considerable.To give an example, a smart energy project for which the expected overall energy savings are lower/comparable with the additional energy needed for running the PoW protocol itself, the use of public smart contracts would be very questionable.4. Finally, we note that employing a smart contract in an energy project or platform will not, in itself, make the project ''smart".Such systems still need techniques from machine learning, for efficient use of device data and smart control, to power systems/smart grid techniques to consider local imbalances, voltage excursions, power quality issues and managing the network, to techniques from automated negotiation and smart markets for efficient trading and clearing.Often, the innovation comes from these other areas, rather than the smart contract implementation itself.Nevertheless, we conclude that, employed properly and in combination with other techniques, smart contracts are a potentially powerful technology that can play a crucial role in enabling the truly decentralised and transactive energy systems of the future.

Declaration of competing interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.TenneT-Vandebron-Sonnen [141] Grid management, balancing and ancillary services using storage Practical Byzantine Fault Tolerance Hyperledger Germany, Netherlands

Fig. 2 .
Fig. 2. Four fundamental steps for execution of value transfer using smart contracts.

Fig. 4 .
Fig. 4. The 6-layer structure of smart contracting for energy applications.

Fig. 5 .
Fig. 5. Application of smart contracts in the energy sector.Each application is discussed in one of the two main application categories identified which are (1) energy and flexibility trading and (2) distributed control.

Fig. 6 .
Fig. 6.The research trend in energy smart contracts.

Fig. 7 .
Fig. 7. Classification of the literature in different categories of energy applications.

Fig. 8 .
Fig. 8. Classification of research contributions on smart contracts functions.

Fig. 9 .
Fig. 9.A word cloud diagram that shows the frequency of keywords used in the reviewed publications.
Truffle suite, which is a development framework for the development and deployment of Ethereum based applications.It includes many other tools listed below to create, compile, test, deploy and interact with smart contracts.• Ganache, as mentioned above, is a tool that allows users to create a local Ethereum DLT with 10 accounts in which a smart contract can be deployed.• Remix IDE (Integrated Development Environment) is a popular browser-based IDE for Javascript-based smart contracts.• Embark is an alternative framework for development, build, test and deployment of smart contracts with modular plugins.It is also compatible with Ganache for simulated blockchain.• Go Ethereum, or Get is a command-line interface (CLI) client that allows smart contract developers to interact with a blockchain and thus to deploy smart contracts.It is the Golang implementation of Ethereum protocol but other implementations exist in C++ and Python.Parity is an alternative to such interaction software, which is written in Rust.• Metamask is a browser extension that can be used to manage Ethereum wallets and the deployment of Distributed Applications.

Table 1
Classification of peer-reviewed publications that use smart contracts into different types of energy applications.D. Kirli et al.

Table 2
Selected companies working on energy smart contracts projects..