Peer-to-peer multi-period energy market with flexible scheduling on a scalable and cost-effective blockchain

platform is then implemented as a side chain of Polkadot, a network of blockchains designed to be secure, scalable, and economically feasible to foster an ecosystem of application-specific sidechains. This design is demonstrated to improve social welfare and achieve scalability by benchmarking the number of transactions that can be included per second, based upon typical assumptions of the market size. The result is a decentralized and performant system that allows for complex market designs to be implemented in a blockchain environment. This approach simplifies the process for participants, allowing them to bid DER or DR devices, directly and easily, even when this requires constraints across periods.


Introduction
According to the report from the International Renewable Energy Agency (IRENA), electricity will become the main source of energy by 2050 [1].As renewable energy sources have high variability, the report also suggests that existing power systems will need more Distributed Energy Resource (DER) and flexible trading to match supply with demand.In particular, peer-to-peer (P2P) microgrid electricity trading will have an important role in this transition as it incentivizes consumers to become prosumers, reduces costs, and improves grid reliability.In a study from the first real-world P2P market in Switzerland, [2] found participants became more incentivized to invest in DERs, such as photovoltaic (PV) systems.One reason is that P2P markets provide more revenue compared to the feed-in-tariff (FiT) typically offered for selling back to the grid.In a community in London, [3] showed that P2P markets can lower the overall cost for the community and recover the investment cost of storage systems.These benefits have been found to hold across a number of different technology and tariff specifications [4].Besides the economic benefits, P2P markets also increase energy security.For instance, [5] found there is less reliance on the main grid as prosumers can generate electricity locally and store excess energy.
P2P trading requires a user friendly, secure, reliable, and costeffective digital marketplace.P2P trading platforms are often built on top of blockchain technology [6].Blockchain provides a unique form of security through its distributed consensus mechanism.No single party has the power to add or change data on the blockchain unilaterally.Once committed, data is secured by cryptographic hashes and stored in many decentralized nodes, making them almost tamper-proof [7].The distributed network provides reliability as the system can continue to operate when a few nodes are down.
However, existing P2P systems proposed in the literature tend to suffer from one of several shortcomings; either they require a centralized party to control the system, operate on a blockchain that would require excessive transaction costs, or they implement a simplified market structure on a blockchain due to the complexity of providing an on-chain market optimization.
This research then proposes that recent advances in blockchain technology that combine the performance of permissioned systems with the decentralization and trust or permissionless blockchain systems can be used to implement a complex P2P market structure on a blockchain.We demonstrate such a system allows for improvements in social welfare over alternative market structures, while achieving both high levels of performance and decentralization.

Literature review 1.Market design
Several different market designs have been considered in the P2P literature.One of the simplest examples is a single sided auction (SA), which would typically be used with a single seller (or buyer), which allows for multiple bids (or offers).In P2P markets it is typical to find consumers bidding for energy, such as excess solar [9].
A double auction (DA) extends this idea to include multiple buyers and sellers.This mechanism is common in P2P markets [10].In a DA, the supplied offers are sorted by their price in ascending order, while the provided bids are sorted by their prices in descending order.The intersection of the supply and demand curve determines the auction price.Supplies offered below the auction price and demands bidding above the auction price are accepted.This mechanism is easy to implement.As such, many blockchain-based P2P markets use some variant of double auction, such as [11].
In both SA an DA approaches, different pricing mechanisms can be implemented [12].Common examples include pay-as-bid, where successful participants pay the price at which they bid, or uniform pricing, where all successful bidders pay the same market clearing price.A Vickrey-Clark-Groves mechanism, as implemented in [13], improves on these approaches to achieve "truthfulness" -the property that participants should bid or offer truthfully, but at the cost of requiring a central party to balance the difference between bids and offers.
This approach can be extended in a number of ways.Firstly, [14] proposed a continuous double auction (CDA) with an adaptive aggressiveness strategy to adjust bid or offer price based on market data.An alternative to CDA is iterative auctions, as proposed by [15], where the double auction approach is repeated in multiple rounds.In [16] the authors designed a distributed double auction mechanism where any market participant can run a local auction from a subset of peers, and forward unmatched energy requirements to a neighboring peer.In [17] the authors implemented a two-round double auction.The first round matches renewable energy producers with consumers preferring renewable energy.The second round matches all market participants.
However, [18] point out that double auctions do not consider the intertemporal constraints of energy products, such as when multiple consecutive hours of energy must be purchased together.Therefore, they proposed to model energy products as single products running for one period and continuous products that run for multiple consecutive periods, cleared by a decentralized ant colony algorithm optimizing the social welfare.
Another type of clearing mechanism is based on game theory.If information can be exchanged transparently in the microgrid, and the participants are incentivized to cooperate to improve their utilities, then the market can be modeled as a cooperative game [8].On the other hand, if each participant acts independently, then the market can be modeled as a non-cooperative game.Note that in non-cooperative games, the participants do not have to act against each other.In a multi-agent system, participants in a non-cooperative game achieved lower prices for consumers and higher prices for producers [19].Similarly, [20] designed a game to optimize consumer schedules that reduces peak demand.One common design of non-cooperative games is the Stackelberg game, where a leader makes a decision first, and then the followers base their strategies on the decision of the leader.Further, in [21], the authors proposed combing an auction mechanism with the Stackelberg game.
The last popular method of market clearing involves solving an optimization problem.The objective is usually to maximize social welfare, reduce cost, or reduce peak demand.Linear programming (LP), nonlinear programming (NLP), and alternating direction method of multipliers (ADMM) have been reported [10].For instance, [22] proposed a LP problem that maximizes the payoff and satisfaction of prosumers.Mixed Integer Linear Programming (MILP) is a special case of LP where some variables are constrained to be integers.Antunes In [23], the authors propose a multi-level optimization using modular MILP models that can be combined to achieve multiple objectives, such as minimizing cost within some discomfort constraints.Optimization approaches allow for complex market designs that can address intertemporal constraints.However, to our knowledge, this approach has not been applied to a decentralized blockchain based system, likely due to the computational complexity of the problem and constraints of a blockchain system.Next, we review blockchain systems with an emphasis on their ability to implement the market mechanisms discussed.

Blockchain technology
Most blockchains can be classified as public, private, or consortium, based on who can join the network [24].Ethereum is a popular choice of public blockchain.Overviewing more than a dozen projects, [25] found over half of the projects are smart contracts on the Ethereum.Public blockchains have larger networks, so they are more decentralized and secure.However, the blockchain trilemma is a common belief that decentralization, security, and scalability cannot be achieved simultaneously [26], as many public blockchains lack scalability.In terms of an application like P2P energy trading, this issue manifests as a transaction cost that would make trading energy with neighbors no longer economic.Ethereum has plans to improve scalability and transaction costs while remaining secure through sharding and layer 2 (L2) rollups.However, the full implementation is estimated to take years to complete.
Deployed projects with real users often opt for private blockchains.Private blockchains typically offer improved performance and often greater privacy, at the expense of decentralization and trust, that are typically the desired characteristics of a blockchain project.One notable project is the Brooklyn Microgird [27].It runs a double auction market with quarter-hour time slots implemented by a smart contract based on the Tendermint protocol. 1Quartierstrom is another project in Switzerland that has been tested in a local community [28].Similar to the market mechanism in the Brooklyn Microgrid project, it operates a double auction market with quarter-hour time slots on a private blockchain also based on the Tendermint protocol.One novelty of this project is the implementation of dynamic grid usage tariff to stabilize voltage [29].When voltage level is high, the tariff is lowered to incentivize consumers with flexible load to draw power.Other examples of private blockchains use frameworks from the Hyperledger project.For example, a Stackelberg game on Hyperledger Caliper has been designed [21], and Hyperledger Fabric and Hyperledger Besu have been used to implement a merit-order auction [30] and a decentralized ant-colony optimization clearing algorithm [18].We find then a gap, between the recent advancements in blockchain technology and the technologies applied in P2P projects.

Research gap and contribution
Despite recent progress, to the best of our knowledge there is no documented research that transformed complex market design into a secure, trusted, and economically feasible trading platform.We follow the insight of [18] that intertemporal constraints are important for households to be able to properly represent their desired energy bidding or selling behavior.For example, a consumer may wish to specify that a battery can be discharged to alleviate peak demand, but only if the charging of the battery is also cleared in the market.Or, alternatively, that some loads such as washing machines are non-interruptible and need to clear multiple periods of energy in a row.
We expand on this idea of intertemporal constraints to allow for complex consumer bidding behavior.Our extended specification of intertemporal constraints allows consumers to specify that they wish a dishwasher to be run overnight and complete before morning, and that it must run for two consecutive hours, but they do not care at what time it runs, while focusing instead on minimizing the price they pay.
Allowing for more complexity in the market design reduces the burden on participants, but it increases the computational complexity of the trading platform.This becomes an issue when we desire to deliver the system in a decentralized way.Popular public blockchains like Bitcoin and Ethereum, that provide this decentralization, suffer from high transaction cost [31] and low throughput [32].This makes the implementation of such a market economically infeasible.In [18] the authors make a trade-off and implement their complex market solution on a private Hyperledger fabric blockchain.While this provides the desired performance, it sacrifices the decentralization desired in such a system.
We find then no existing solution that provides the level of market complexity, decentralization, and performance we believe appropriate for P2P energy trading.To address this issue, we turn to recent advances in blockchain technology that combine the performance of private blockchains with the trust and decentralization of public blockchains to demonstrate that such a system is possible.
First, we present our market formulation, Continuous Social Welfare Optimized Flexible Trading (C-SWIFT).Next, we turn the market design into a trading platform by implementing it as a parachain of Polkadot.Polkadot is a blockchain of blockchains designed to connect and secure many domain-specific sidechains while maintaining scalability and low transaction fees [33].We call our application specific blockchain POETS for Polkadot Energy Trading Sidechain [45] and make this available open source. 2 In summary, the contributions of this paper are: • A market design that considers the inter-temporal constraints and flexibility in scheduling of DERs.This design simplifies the requirements of household participants to represent their needs in the market.
• The first energy market blockchain that provides the trust of public consensus but still has control over transaction costs and high transaction throughput, as demonstrated by our benchmarks.• The first application of the Substrate blockchain framework and use of the Polkdadot blockchain network for P2P energy trading in the literature.• Demonstration of how off-chain market computation can be validated on blockchain in a trustless manner.

Market design
This section first provides background information on the P2P energy trading design.Subsequently, we present our market formulation and clearing method.

P2P trading background
A P2P energy market is usually formed by consumers, prosumers, and generators in a local microgrid to trade without a traditional intermediary [34].Consumers are usually households buying energy for their appliances.They bid on the quantity and price they want to buy from the market.Generators own devices that can provide energy from renewable sources, such as PV panels, wind turbines, and hydrogen fuel cells [35].They propose offers on the quantity and price they are willing to sell to the market.Prosumers can assume the role of both consumers and generators.They usually have storage capacity to help balance the microgrid by storing excess supply that they can sell back later [5].
The trading price is determined by bids and offers, typically above the FiT, to encourage prosumers to sell to the local microgrid, and below retail price to encourage consumers to purchase locally.According to [8], community manager, non-profit organization, or automated rules often function as the distributor or auctioneer.Moreover, [34] found blockchains can act as the intermediary without a central entity.The distributed nature of blockchain technology, coupled with its capabilities to provide trust, traceability, and data security, make it well-suited for building a P2P trading platform.Furthermore, blockchain also handles peer discovery and minimizes communication overhead well compared to a pure P2P network.
Besides trading at the virtual layer, P2P trading can also consider the physical layer for energy delivery and power fluctuation.It can be over the traditional grid or a new infrastructure [10].In either case, the microgrid is often still connected to the main grid to sell surplus and supply shortage.We base ourselves on such a case, where P2P trading is not the sole source of energy, and local constraints are not considered, as with the majority of P2P literature [9].However, we note this to be an interesting extension for future work and next turn to our formulation, which does not consider physical constraints.

Market formulation
Our proposed C-SWIFT market is a time-ahead, multi-period market with a uniform pricing scheme and simultaneous clearing based upon the work of [18].It assumes the role of auctioneer in the energy market.C-SWIFT allows consumers and prosumers to propose trades for multiple periods.At the end of the trading window, all proposed trades are cleared together to account for their inter-temporal constraints.The uniform pricing scheme simplifies C-SWIFT to have one clearing price per period, but it still ensures that only bids above the clearing price and offers below the clearing price are accepted.The rationale is that the bid price is the maximum price a buyer is willing to pay, while the offer price is the minimum price a seller is willing to accept.
Each bid or offer is a market product with the following properties: • Price: For a bid, this is the maximum price which the consumer is willing to buy.For an offer, this is the minimum price the producer or prosumer is willing to sell.
link: https://doi.org/10.5281/zenodo.10886425 C.-T. Huang and I.J.Scott • Quantity: Units of energy to buy or sell at each period.
• Starting period: The starting period to buy or sell energy.
• Ending period: The ending period to buy or sell energy.
A product that spans multiple periods is a continuous product [18].Otherwise, we call it a single product.Each period is of equal length.Let t denote a period and d be the total number of periods in a trading window with t ∈ ⟦0, d⟧.Let B be the set of all bids and O be the set of all offers.Each bid b ∈ B is a product with a starting period s b,j ∈ ⟦0, d⟧ and ending periods e b,j ∈ ⟦0, d⟧ so the operating period is o b,j = ⟦s b,j , e b,j ⟧.A bid has a single price p b,j and quantity q b,j throughout the operating period.An offer has similar notation but with subscript o.
In addition, we introduce the concept of flexible products to encourage consumers to shift usage from peak hours [35].This also incentivizes prosumers to supply during peak demand.A flexible product is expressed as a list of products where at most one of them can be accepted.C-SWIFT will pick a schedule that maximizes social welfare.A flexible bid is indexed by j = ⟦0, k b ⟧ with a binary activation variable A flexible offer has a similar notation but with the subscript o.
A practical application for flexible energy consumption involves charging an electric vehicle.In this scenario, the vehicle owner might be agnostic about when the vehicle is charged, as long as it is completed before the next day.With a typical market, the owner must decide in which periods to place bids, and hope that these clear, or to bid in multiple periods and risk clearing more energy than needed as all periods are cleared at once.Instead, with C-SWIFT the owner can place a single bid using multiple period constraints that represents "procure four hours of charging overnight".Leveraging this flexibility, the market can strategically shift the demand to the lowest priced hours, such as the middle of the night.This not only accommodates the owner's preferences but also alleviates competing demands on the distribution grid during peak hours, benefiting the entire distribution grid.In addition, allowing the user to enforce integers means they can ensure that the full quantity of energy required is provided for the full period.This may be useful in the case of machines that can only be switched on or off, potentially with smart plugs, such as washing machines or driers, increasing the range of potential devices that can contribute to the market.These flexible bids are incorporated into the following market formulation.
The C-SWIFT market is formulated with the objective to match bids and offers such that the social welfare is optimized.Formally, social welfare is defined as the difference between the total utility for consumers and the total cost for prosumers [8].
In addition, C-SWIFT has the following constraints: 1.The bid price is the maximum price the buyer is willing to pay.Therefore, each bid price must be greater than or equal to the auction price v t throughout the operating period: 2. The offer price is the minimum price the seller is willing to deliver.Therefore, each offer price must be less than or equal to the auction price throughout the operating period: 3. The accepted bid quantity and offer quantity are equal for each period: 4. Only one product in a flexible bid can be accepted.The same applies to an offer: The third constraint of matching quantity is hard to satisfy if a product is neither fully accepted or rejected.Since DERs such as batteries can be partially charged or discharged, the market introduces a new variable c ∈ ⟦0, 1⟧ to denote the percentage of quantity that is accepted with c = 1 if the product cannot be partially accepted.
To summarize, the market objective is to maximize social welfare, subject to the constraints defined in eqs. 2 to 5. The market problem can be expressed as: In eq. ( 6), the first constraint satisfies eq. ( 2).If the bid is accepted, i b,j = 1 and, therefore, v t < p b,j i b,j .If the bid is not accepted, i b,j = 0 so U is an upper bound on auction price.We pick the retail price to buy from the grid.The second constraint satisfies eq. ( 3).If i o,j = 1, then v t > p o,j i o,j .Otherwise v t > 0. The third constraint is an expansion on eq. ( 4) to consider partially accepted products.The fourth constraint satisfies eq. ( 5) for all bids and the last constraint satisfies eq. ( 5) for all offers.

Market clearing
The market problem defined in eq. ( 6) has three kinds of variables to solve: • c the percentage of a product that will be accepted.
• i which schedule in a flexible product will be accepted.
• v t the estimated auction price for each period.It is between the constraints of eq. ( 2) and eq.( 3).In our market, the final auction price is the lowest bid price above this estimate.This gives prosumers a better price to incentivize their participation.
Eq. ( 6) is not linear because the objective is a product of i and c, but we can use the Big-M method to linearize it [36].We apply it to move the binary activation variables from the objective function into two constraints.Recall that c ∈ ⟦0, 1⟧ and i ∈ {0, 1}.If c > 0, then i = 1.So, the first additional constraint is: In eq. ( 7), c = 0 and i = 1 is a valid solution.To ensure i = 0 when c = 0, the second additional constraint is: C.-T. Huang and M must be sufficiently large to satisfy eq. ( 7).C-SWIFT assumes that at least 1% of a product has to be accepted, so we pick M = 100.With eqs.( 7) and ( 8), the objective function can be simplified to: The transformed market problem is a MILP optimization problem.A common technique to solve it is through the branch and bound algorithm [37].This paper uses the implementation from the open-source solver COIN CBC [38].Results are presented in Section 4.

Blockchain tradingplatform
To realize the proposed market design, we implemented a trading platform as a blockchain.This section begins with background information on blockchain technology, the characteristics that make it suitable for building P2P trading platforms, and a comparison of popular blockchain designs.Next, we present an overview of the Substrate framework used to build our parachain on the Polkadot network.Our parachain implementation and the architecture of the trading platform concludes this section.

Blockchain technology overview
Although it is often associated with cryptocurrencies, blockchain is a more generalized technology that enables cryptocurrencies.In essence, a blockchain is an append-only database maintained by a decentralized network.The key characteristics of blockchains are [6]: • Decentralization: Data is stored in a P2P network.There is no central authority to decide what can be stored or modified.• Trust: Although there is no central authority, there is trust in this system because any update must be validated and agreed to by the majority of the network.A malicious node cannot compromise the network.• Openness: The data is opened for access by anyone in the network.
The rules that operate the system are also transparent.• Traceability: Records are stored permanently, including the author of a transaction.If something is transferred through multiple transactions, the path can be traced back.• Data security: Data cannot be tampered with unless the majority of the nodes are compromised.• Anonymity: Parties exchanging data do not need to reveal their identities.
Trust, traceability, and data security provide security guarantees for a trading platform.Decentralization removes the need for a trusted third party, such as a traditional energy company.It also provides higher resilience.A blockchain can continue to operate if a few nodes are down, whereas, with a centralized operator, the platform would experience an outage if the operator were down.
There are many blockchain designs with different permission models, consensus protocols, application layers, scalability options, and cost models.Ethereum is the most popular public blockchain for developing decentralized applications.Polkadot is an emerging network to solve the scalability and isolation concerns of existing blockchains.Hyperledger is a group of open-source distributed ledger frameworks, usually deployed as permissioned blockchains for enterprise applications.The following facets need to be considered in blockchain design:

Permission model
The permission model decides who can join the network.It also has implications for the privacy of identity, transaction confidentiality, performance, and governance.Most blockchains can be classified as one of the following: public, private, or consortium.A public blockchain has an open model which means transactions are transparent and anyone can join the network.Usually the network is larger, so it is harder to compromise, but on the other hand, it takes longer to reach consensus and it is harder to upgrade the software.While Ethereum and Polkadot are both public blockchains, many literatures reviewed opt for permissioned blockchains.According to [39] this is because the identity of the market participants is usually known by at least some party in the system.For example, the grid operator usually knows their identity when energy is delivered by the main grid.Additionally, consumers often do not want their demand and bid price to be publicly known, which can be a limitation of the transparency of a fully public blockchain.

Consensus protocol
The consensus protocol plays a crucial role in the security model and carbon footprint of the blockchain.Proof-of-work (PoW) protocol consumes a lot more energy, which defeats the purpose of P2P energy trading.Proof-of-stake (PoS) protocol is energy efficient comparing to PoW.The block production frequency is also more predictable and therefore allows for a better transaction throughput.Both Ethereum (after upgrading in 2022) and Polkadot use PoS-based protocols.A preliminary study [31] on Ethereum's transition to use PoS found energy consumption was reduced by 99.98%.Tendermint is another kind of PoS adopted by some permissioned blockchains, such as the Brooklyn Microgrid and projects.

Application layer.
Blockchains by themselves are just databases.They need to be programmable to build useful applications on top of them.Ethereum supports smart contracts.They cannot be changed once deployed, making them tamper-proof, which makes them hard to update, leading to hard to fix security vulnerabilities [39].Another approach is building application-specific blockchains, such as Polkadot's network of parachains.Polkadot also supports smart contracts, but one would need to find a suitable parachain to deploy to and the application would then be subject to their economic design and without control over fee levels.Another strength of Polkadot is its forkless upgrade without downtime.The runtime logic is compiled into WebAssembly (WASM) and stored in the blockchain state.A new version is distributed to all nodes during the consensus process.

Scalability
Scalability is the concern of transaction throughput.The major deciding factors are consensus protocol and network size.Private and consortium blockchains have smaller networks and hence higher throughput.Ethereum has a roadmap to become more scalable without compromising on security.The first step is layer 2 (L2) and rollup solutions.L2s are standalone blockchains that aggregate multiple transactions into one and rollup to layer 1 (L1), which is Ethereum.This way, L2 transaction fees are reduced, while maintaining the security benefit of L1.However, L2 and rollup do not increase the throughput of L1 Ethereum, which is still limited to 15 TPS [40].TPS will be improved in the Ethereum's next milestone, Danksharding [41].The goal is to further reduce L2 transaction fees and scale to >100,000 TPS through a new sharding design.However, it is estimated this will take multiple years to implement.On the other hand, Polkadot adopts a multi-chain solution.Each parachain is a shard in the Polkadot network.They aggregate and submit their transactions to the relay chain, similar to how L2 rolls up to L1.It is estimated that the TPS will scale from 100,000 to 1000,000 [42].We benchmark the scalability of our implementation and find it sufficient for P2P energy trading.
Cost: The network operators of private and consortium blockchains have control over the transaction costs.Whereas, on Ethereum, executing a smart contract consumes fees, called gas, that are proportional to the complexity of the contract.Gas fees are a real concern such that [17] stated saving gas as an objective of their proposed double auction algorithm.Others [19] also listed using different blockchains with lower transaction fee as a possibility to improve payoff to participants.Finally, [31], in a study of the Ethereum blockchain, found the median fee to transfer ETH peaked at $28 in May 2021, dropped to $0.5 before the upgrade and raised to $1.7 after transition to PoS.Smart contracts have more instructions to execute than transferring ETH, so gas price will be higher than the median fee to transfer ETH.For Polkadot developers, there is a fixed cost to acquire a slot for their parachains to connect to the network through an auction.Smaller applications can deploy to Kusama (a canary network for more experimental projects) or use the production-grade network of Polkadot.Once connected, parachains do not pay transaction fees to have their blocks included in the relay chain.It is up to the parachain to decide if and how much transaction fees to charge from their end users.Some applications might still find parachain too costly.To address this, Polkadot provides a parathread model that allows multiple applications to share the same parachain slot [43].Parathreads and parachains are similar from a technological perspective, except that parathread bids for block space, meaning a parathread bids to have each block it wants included on a block-by-block basis.

Privacy
The network operators of private and consortium blockchains can have control over who has access to the transaction history, although typically strict privacy cannot be maintained from these operators.In a public network, the entire transaction history is public, ensuring transparency but preventing any strict form of privacy.In both cases, privacy is typically achieved through pseudonymity, where the on-chain identifier for a user (typically an account) is not directly linked to the actual user.A user, wishing to improve privacy, can generate unlimited accounts and use a new one for each transaction.
Table 1 provides a comparison summary of comparison between Ethereum and Polkadot.In this paper, we adopt Polkadot for its higher TPS, higher control over the transaction costs and flexibility to build a blockchain specialized for the energy market.

Polkadot and substrate framework
The Polkadot ecosystem provides a software development kit, Substrate, 3 to simplify the development of blockchain nodes.A node consists of a runtime, off-chain workers, and client with outer node services.A Polkadot parachain is run by collator 4 nodes, which collect transactions and form blocks, while the wider network is secured by validator nodes, which validate that blocks follow the rules of the blockchain and can be added.To develop a blockchain with substrate one is only required to implement their desired logic as a collator node.The collator node collects user transactions and adds them to blocks, calculating the transition of the internal state.Then, if the project wishes to benefit from the decentralization of the wider Polkadot network, they can make use of the existing decentralized validator nodes to "validate" these state transitions.The focus of this paper is then to implement the runtime and off-chain worker of a collator node.
Fig. 1 provides a visualization of the architecture of a collator node.It provides all the functionality for a blockchain to run, including networking, consensus, remote procedure call (RPC) functionality, and storage.The developer's job is to provide some of the runtime logic.Here we implement the code that users can interact with through transactions.This is similar to how smart contracts work on most blockchains; they are implemented and deployed by developers and users interact with them through transactions.
A couple of features of the runtime should be noted.Firstly, to prevent abuse, each transaction has a fee that is proportional to the execution time, which is measured as weight.Weight here is analogous to "gas" on the Ethereum blockchain, representing the amount of block space (and calculation time) a transaction requires.Secondly, a node can perform computation on off-chain workers, meaning computation can be performed not directly "on-chain".This off-chain worker environment is not trusted, so the runtime still needs to validate results from the workers.
In the next section we present how the systems architecture is implemented within this framework.

System architecture and implementation
Our trading platform, POETS [45], 5 is a parachain that provides the following functionalities to market participants: 1.An API to submit and update bids.Each bid is a flexible product.
2. An API to submit and update offers.Each offer is a flexible product.
3. An API to propose a solution to the market problem.It should include the auction prices for each period, bids accepted, and offers accepted.4. A baseline solution to compare with solutions proposed by other market participants.5.An API to query proposed bids and offers.
6.An API to query market clearing results, auction prices, and accepted bids and offers.
These functionalities are implemented as runtime logic and off-chain worker.Each participant has an account which is identified anonymously by the public key.Functionalities 1-3 are implemented as signed transactions: • submit_bids: POETS enforces a limit on the number of bids that can be submitted by a user, because each bid is stored, and weight is proportional to the number of accesses to storage.It also requires the bid price to be higher than FiT to incentivize prosumers to sell.• submit_offers: similar to submit_bids, except that it enforces the offer price to be lower than the retail price since eq.( 6) uses it as the upper bound.
• submit_solution: POETS provides this transaction to encourage market participants to develop better algorithms.It accepts auction prices for each period, the list of accepted bids, and offers.To accept a new solution, it must be demonstrated to improve the social welfare value and to be a valid solution to the optimization problem.The calculation of social welfare is done on-chain and is a straightforward sumproduct, as defined in Eq. ( 9).The validation of the proposed solution is more complex; effectively both the primal and dual solutions of the optimization must be verified.First, to verify physical constraints in the primal optimization problem, the on-chain transaction verifies whether each accepted bid and offer was indeed submitted and whether the sum of bids accepted is equal to the sum of offers at each point in time.The dual solution must also then be tested.For this to be the case, the bid price must be higher than or equal to the auction price, and the offer price must be lower than or equal to the auction price for each accepted bid or offer.This still leaves some room for flexibility in the exact price provided when there is a gap between the highest accepted offer price and the lowest accepted bid price.Future implementations could look to implement a benefit sharing pricing rule here.
In this paper, we developed a program [46] 6 that queries POETS for the proposed bids and offers, uses them as input of eq. ( 6) and calls the COIN solver to find the optimal solution.Then it calls the sub-mit_solution transaction for validation.POETS compares it against solutions proposed by other market participants.In case no one submits a solution, POETS provides functionality 4 as a fallback.It is implemented as a double auction running in the off chain-worker.The double auction algorithm tries to find the intersection of supply and demand for each period, but it does not consider the intertemporal constraints or flexibility in scheduling.To simplify the implementation, we assume the first schedule in a flexible product is the preferred one and only considers that. 7If the auction finds a feasible solution, the off chain-worker calls the submit_solution transaction for another validation.
Functionalities 5 and 6 are already provided by Substrate, via an RPC to query the state of the parachain.Fig. 2 provides a visualization of user interactions with POETS.
This solution has been designed to provide a number of advantages, broadly to achieve the performance needed for a complex P2P market structure, while retaining a high level of decentralization.However, as always, trade-offs need to be made in design decisions.
Firstly, the level of decentralization cannot be considered the same as in a completely public system, such as Ethereum.For one, the blockchain is designed and implemented by a single party.If the blockchain allows for runtime upgrades the single party could change the operation of the blockchain, although all participants would be aware of this.This risk is of a similar level and type to the risk of upgradeable smartcontracts on Ethereum.
In addition, while the blockchain creator has control over transaction costsa huge advantage over Ethereumif they wish to join a public network to achieve decentralization, such as Kusama or Polkadot, they must pay for a parachain or a parathread slot.While these are Fig. 1.Architecture of a collator node. 6Available here: https://github.com/chungthuang/milp-solverand at the permanent link: https://doi.org/10.5281/zenodo.10886420 7This "fallback" solution is unlikely to be optimal, but is designed to be simple to calculate on-chain.Participants have an incentive then to provide their own market clearing solutions which perform better than the fallback solution.The provision of fees to market clearing solution providers is one area that could be expanded, if desired.reasonably affordable, this price is set by supply and demand and is not under direct control of the blockchain designer [33].
Finally, one consideration when designing the system is privacy.Operating on a public network, parachains cannot offer strict privacy of transactions details and history.This has the advantage of transparency; all market participants can see that the market operated fairly and in line with their expectations.Privacy is typically provided through pseudonymity, where users on chain addresses from which they send transactions do not store identifying information about the user.
However, participants may be concerned about leaking information about their household energy consumption to their neighbors or the public in general.For instance, a neighbor may be able to identify one transaction from a specific user.Specifically, they could see that they charged an electric car at a time when a certain blockchain address cleared a bid to do so.In such a case, the neighbor could see all transactions from that address and potentially learn about the energy use or financial transactions data of the specific user, despite pseudonymity.
To alleviate this issue, a participant can use a different address for each transaction.A blockchain wallet can typically generate as many unique addresses as needed.The user simply needs to prove to the required party (utility, distribution network operator, seller of energy) that they own the address that cleared a given bid / offer (which they can do by signing a message with the private key associated with the address).

Resultsanddiscussion
This section first presents the market simulation using data from the work of [18] and a comparison of the results.Next, we present another market simulation with flexible products and demonstrate the advantages of our market design.Finally, we present benchmarks on the performance of the blockchain to evaluate transaction throughput of the trading platform.

Single and continuous products
First, we compare our market with the DeMarket proposed by [18] since our design was inspired by theirs.Their simulation used data collected by [44] on energy demand in the Midwest U.S.However, the prices were chosen randomly between FiT and grid price of Netherlands because there is no regulation on how to price energy products.Table 2 summarizes the simulation data.Agents 1-3 are producers, while agents 4-6 are consumers.Agents 3 and 6 each have a continuous product.The remaining agents only have single products.
Without flexible products, C-SWIFT is similar to [18]'s DeMarket but allows for partial acceptance of continuous products and ensures auction prices are within the range of accepted bid and offer prices.
The resulting trade of each agent is presented in Table 3.The allocated quantity and auction price of each period is summarized in Table 4.The social welfare score of DeMarket is around 43.57, while C-SWIFT achieved a similar score of 42.67 which, when we account for differences in the model, we believe to be the superior solution. 8 C-SWIFT was able to match equal or more quantity in each period.In addition, C-SWIFT guarantees buyers will not pay for more than their bid prices and sellers will not receive less than their offer prices.In contrast, DeMarket will have agent 4 pay 9 c€/kWh in delivery period 2, while the agent's highest bid price is only 8.7 c€/kWh.

Flexible products
Next, we simulate C-SWIFT with flexible products.As we did not find other papers with similar experiments, the price and quantity were chosen arbitrarily to create a range of values with prices roughly between European wholesale and retail prices and quantities in line with a large household [4].Table 5 shows the simulation data and results.Products 1 and 4 are flexible products with 2 potential schedules.First, we simulate when all products have to be fully accepted.Then, we test with the same dataset, but this time making it so all products can be partially accepted.
The result is shown in the last 4 columns of Tables 5 and 6.When all products must be fully accepted, the first schedule of product 1 and the second schedule of product 4 are accepted.The total utility is the sum of price × quantity × (end period − start period) from products 1, 3, 5 and 6, which is 478.Whereas the total cost is the same formula, but from products 2 and 4, which is 364.The overall social welfare is the total utility minus total cost, 478 − 364 = 114.When all products can be partially accepted, the first schedule of product 4 was accepted instead of the second one, because its overall cost is lower.The social welfare score increased to 154.The auction price for each period is determined from the lowest bid price.In period 1, the lowest bid price is from product 6.Both runs resulted in the same auction prices.

Performancebenchmarks
To benchmark the blockchain implementation, we calculate the Fig. 2. User interactions with POETS. 8There are minor reporting issues in the original paper; for example, the allocated quantity for agent 1 in the first delivery period is 3.49 kWh, which is more than its offer of 1.5 kWh Table 2.In addition, the authors allow for the constraint that the accepted offer quantity must equal the accepted bid quantity to be violated by up to 5% every period, although in practice it is violated by 0.05 kW.Accounting for these differences, the C-SWIFT result is superior.transactions weights, which estimate the required computation time.As blocks must be added at fixed intervals, including all steps in the computation and validation process, there is maximum weight per block.The computation weight for a transaction then directly determines the performance characteristics of the system.A transaction's weight is determined by four main factors, the hardware, size of input, type of database, and the number of times it reads and writes to the database.The result 9 is a linear model for each transaction.The unit is in picoseconds (10 − 12 seconds).Let r denote the   No 0 0% 0 9 The benchmarks were measured on a laptop with 11th Generation Intel (R) Core (TM) i7-1195G7 @ 2.90GHz processor and 16 GB of RAM, repeated 10 times.
constant time to read from the database and w denote the constant time per database write.Eqs. 10 and 11 provide the calculation of the weight of extrinsic transaction to submit bids and offers respectively.They have the following variables and coefficients: • c: input size, the number of bids/offers submitted by a user.
• b: number of bids already in the database.
• o: number of offers already in the database.
• B 1 , B 2 and B 3 : coefficient for c, b and o.
The estimated coefficients tested with different input ranges are presented in Table 7.The table shows that the base time (B 0 ) and process time per product (B 1 ) increases with the input range.On the other hand, B 2 and B 3 are negligible comparing to B 1 .This concludes the number of items already in storage is not as important as input size for computation time.
Eqs. 10 and 11 can also be used to estimate transaction throughput.We consider three measures, weight per transaction (W/T), transaction per second (TPS), 10 and transaction per block (TPB).According to Polkadot Protocol Specification v0.2.1, the block production time is 6 s, 11  so TPB = 6 × TPS.
Firstly, we plot the relationship between the weight and number of existing bids in the system (displayed in Fig. 3.This relationship is important as it could mean the platform was unable to process a transaction if the weight would not fit within a block.We can see this relationship is linear in the number of existing bids, as implied by Eqs. 10 and 11, however, the linear relationship changes with the size of the number of bids the user is trying to submit.We can see that even with 100,000 existing bids for a given market (representing up to 100,000 participants in a single day's auction) and a participant submitting 10,000 of their own bids, the blockchain is still easily able to process such a transaction.The result of the calculated throughput, assuming maximum input in each transaction, is presented in Table 8.Note that in this calculation we only consider the computation time, but not the amount of data.The protocol specification limits the block size to 5 MB.
Eq. 12 provides the calculation of the weight of the extrinsic to submit a solution.When writing the benchmark, we follow the principle of testing the most computationally expensive case.Thus, the benchmark assumes all submitted bids and offers are accepted.The equation has the following variables and coefficients: • b: input size, the number of accepted bids.
• o: input size, the number of accepted offers.
• B 1 and B 2 : coefficient for b and o.
The estimated coefficients tested with different input ranges are presented in Table 9.Similar to the findings from Table 7, the base time and coefficients increase as the input range grows.We then plot the relationship between weight and the number of existing bids and offers in Fig. 4. The throughput is summarized in Table 10.
We find again a linear relationship between the number of existing bids and offers and the transaction weight.This transaction must verify each accepted bid and offer against the bids and offers on the blockchain, as previously described, and this computation is included in the weight.We again see that even with 100,000 bids and 100,000 offers the platform is capable of fitting 4 such transactions in a block.We could extrapolate this to estimate that the platform would need roughly 4 to 5 times this number of existing bids or offers before it started to have performance issues.This represents a vastly greater number of participants than those seen in the literature [9].
The benchmarking results are in line with those previously provided for substrate-based blockchains (see [33]).They demonstrate that the execution time of a transaction is proportional to the input size, but not the current storage size.For a reasonable upper bound of 1000 bids or offers per user, submit_bids and submit_offers transactions have good throughput.The submit_solution transaction can handle up to 10,000 accepted bids and offers with reasonable throughput.

Discussionandconclusion
In this paper, we proposed a complex market design C-SWIFT that considers the multi-period requirements and flexible schedule of household appliances and DERs.We then implement this design on POETS, a blockchain that provides the necessary performance to make this possible while retaining decentralization.
Compared to double auctions used in the majority of the literature, our market design makes it easier for consumers to shift usage from peak demand and incentivize prosumers to supply during surges.It does so by allowing participants to directly specify their requirements with multiperiod constraints.This allows for bidding patterns such as "purchase energy to run the dishwasher before the morning" as a single bid cleared by the market.The market problem is formulated as a MILP optimization on overall social welfare.
C-SWIFT is first simulated using data from another published paper [18].On this data, our solution was able to match more supply with demand and guarantee buyers will not pay more than their bid prices and sellers will not pay less than their offer prices.Then, we simulate C-SWIFT against a synthetic dataset to demonstrate the usefulness of flexible schedules.The result shows C-SWIFT automatically helps users pick the optimal schedule that increases overall social welfare.Future research could also account for the interaction of the physical layer and market layer for energy trading, such as the capacity and voltage limits of the local distribution grid.In addition, trade should only be settled when energy is delivered.Another research direction would be better incentive mechanisms to encourage market participants to develop more optimal clearing mechanisms.In future work, the C-SWIFT mechanism could be expanded to include pricing similar to a Vickrey-Clark-Groves mechanism to achieve bidding truthfulness.
To implement the complex market structure of C-SWIFT in a decentralized manner we introduce POETS, a parachain of Polkadot.This approach offers the trust of a public blockchain and the performance of a private blockchain, to demonstrate its feasibility.In addition, we provide an off-chain optimizer that can query market data from the blockchain, solve the market problem using the open-source MILP optimizer, and submit the result to the blockchain for validation.
The trading platform POETS collects bids, offers, and solutions, from market participants.It also runs a double auction in case no market

Table 6
Result of market with flexible products.This work provides a demonstration of the benefits of modern blockchain platforms that provide both performance and

Table 7
Weight coefficients of submit_bids and submit_offers transactions.

Table 8
Weight and throughput of submit_bids and submit_offers transactions.C.-T. Huang and I.J.Scott decentralization.In future research, blockchains such as POETS should join networks such as Rococo, the test network of Polkadot.Then, finally, to bring POETS to production, we can auction for a parachain slot on Kusama, the canary network of Polkadot, that is productiongrade but cheaper to auction.Such a system can then be used for real world test cases to study how real users interact with the platform.From such an experiment, we can measure the performance on a real blockchain network under real world conditions.Finally, and importantly, we can test if the level of decentralization achieved is understood and desired by users and provides them with the ability to "trust" the system.
In addition, we note the performance demonstrated in this blockchain structure could allow for even more complex market designs that bring additional benefits for participants.One such extension of our complex market would be a Vickrey-Clark-Groves auction clearing mechanism, which while computationally complex, has the benefit of ensuring that the best strategy for each participant is to bid truthfully, which may lead to fairer outcomes.

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.

Table 10
Weight and throughput of submit_solution transaction.
C.-T. Huang and I.J.Scott units of weight is approximately 1 s, so TPS = 10 12 /weight per transaction. 11https://spec.polkadot.network/id-weights#defn-polkadot-block-limitsC.-T. Huang and I.J.Scott participant submits a valid solution.The use of blockchain technology ensures data is tamper-proof and settlement is handled automatically by pre-defined trading rules.Each transaction is benchmarked to analyze its weight and throughput.For a reasonable input size of 1000 bids or offers, POETS can process hundreds of transactions per second.
T. Huang and I.J.Scott

Table 3
Results of DeMarket vs. C-SWIFT per agent.

Table 4
Allocated quantity and auction prices of DeMarket vs. C-SWIFT.

Table 5
Flexible product simulation.

Table 9
Weight coefficients of submit_solution transaction.