On Reﬁning Design Patterns for Smart Contracts

. The need for a Blockchain Oriented Software Engineering (BOSE) has been recognized in several research papers. Design Patterns are considered among the main and compelling areas to be developed in BOSE. Anyway, design patterns need to be enhanced with some additional ﬁelds to better support the speciﬁc needs of Blockchain development. In this paper, we discuss the use of Solidity design patterns applied to a water management use case and we introduce speciﬁc ﬁelds in their description, aiming at oﬀering to Blockchain developers more support in the critical decisions to build eﬃcient decentralized applications.


Introduction
Since the release of Ethereum, there have been many cases in which the execution of Smart Contracts managing Ether coins has led to problems or conflicts. Probably, the most well known example of such issues is "The DAO" [15,13]. The DAO, decentralized autonomous organization, was a concrete attempt to implement a funding platform, similar to Kickstarter, running over Ethereum. It went live in 2016 with between 10-20 thousand investors (estimation) providing the equivalent of about US$ 250 million in funding and thus breaking all existing crowdfunding records. However, after few months an unintended behavior of the DAOs code was exploited draining the fund of millions of dollars worth of ETH tokens. The DAO experience makes clear the importance of suitable Blockchain Software Engineering (BOSE) techniques, capable to reduce the risks connected to "poorly" designed and implemented smart contracts. However, a discipline of Smart Contract and Blockchain programming, with standardized best practices is yet in its infancy and requires new approaches since smart contracts rely on a non-standard software life-cycle; as an example, once deployed applications can hardly be updated or bugs resolved by releasing a new version of the software.
In [12] the authors discuss the need for BOSE and propose three main areas for the initial development of this discipline: a) Best practices and development methodology, b) Design patterns and c) Testing.
Our work is focused on the use of Design Patterns for the development of Decentralized Applications (DApps) [25].
DApps are a new class of applications coded in programs running on the blockchain. DApps may provide a variety of services over the underlying P2P infrastructure that up to now have only been provided in the dominant Client/Server architectures. The Peer-to-Peer (P2P) nature of DApps and the lack of a central authority as in the Client/Server paradigm, is the key ingredient to implement infrastructures supporting new forms of democratic engagement of the users. A recent report by Fluence Labs [17] presents the state of the DApps ecosystem surviving 160 projects. The main findings can be summarized in the following points: a) DApps is a modern trend: 72% of the projects started in 2018, b) 87% of the projects run on Ethereum c) A quarter of the surveyed projects are gaming DApps. d) About half of the projects used a centralized tools to connect to the Ethereum blockchain. e) Transactional fees prevailed as the central monetization model for most projects. f) New user onboarding was mentioned by more than three quarters of the respondents as the major obstacle to adoption.
Problem Statement. Design Patterns are undoubtedly a useful tool to improve the development of DApps. Due to the nature of the Blockchain, more than in other contexts DApps are at risk of generating problems, which are hard to recover from. However, most of the available Design Patterns for Blockchain do not consider some useful information that can help the developer to implement correct and efficient solutions. Contribution of the paper. In this paper we analyse and evaluate best practices in the use of Design Patterns for a typical DApp. Moreover, we refine the format description of design pattern specific for blockchain with other fields, namely Cost of execution and Decentralization level and On-chain/Off-chain components, capable to help developers in trading-off between critical design and implementation choices. As a running example, we develop a DApp interacting with Internet Of Things devices to monitor and manage resource consumption, and encourage the democratic engagement and empowerment of citizens. In particular, our use case focuses on a DApp for the management of urban water resources. However, the Design Patterns employed in this specific use case are of general interest and can support a variety of other application scenarios.

Use Case: decentralized management of urban water resources
The interactive statistics portal by the International Water Association (IWA) [8] provides data on water consumption, tariff structure and regulation of water services in 198 cities in 39 countries from all 5 continents. The IWA report stresses the importance of adopting modern emerging technologies and smart metering to improve the overall water management process in the city. In nowadays cloud solutions, data on water consumption is collected by smart meters and delivered to a cloud service allowing live monitoring of the consumption and providing evidences on consumption patterns to the users in the hope that citizens will consequently act to reduce their water consumption.
It is worth noting that the overall success of such resource management strongly depends on the active and collective participation of citizens. The virtuous behaviour of an individual is commendable, but the risk is that it is literally "a drop in the ocean" if not accompanied by the joint action of the community.
Nowadays, the Client/Server paradigm dominates the cloud services market. However, decentralized applications (DApps), an emerging P2P framework, have the potential to revolutionize this market and democratize the whole process. The hope is that the empowerment of the citizen, guaranteed by this democratic process, will improve the participation and thus the overall chances of success of smart cities initiatives. As observed in [22], smart cities often do not optimally reach their objectives if the citizens are not suitably involved in their design.
We assume the availability of suitable Internet of Things (IoT) devices, i.e. smart water meters, capable to measure the performance of a target process, i.e. reducing water consumption. However, we want then to have citizens engaged in pursuing behavioural changes. It is well-known that behavioural changes are the effective way to better performances in resource management, e.g. closing the water while brushing teeth can save up to 20 litres, and taking a shower can save up to four times the water necessary for a bath.
To support the active engagement and democratic participation of users, our proposed DApp will implement two main principles: -Citizens propose smart contracts that encode measures of the effectiveness of water management policies. Typically, such smart contracts relies on IoT data to monitor the application of policies. Citizens also select a smart contract by a fair vote. Such smart contracts, capable of attracting the greater consensus from citizens, becomes currently operative. Selection may occur regularly, on demand, or on specific conditions. -To further encourage the participation of citizens, the operative smart contract will also be in charge of distributing incentives to virtuous citizens, namely citizens that most actively contribute to fulfill policies, i.e. successfully reduce the water consumption.

Reference Architecture
The full implementation of the Proof of Concept (PoC) is available in the GitHub repository [2] and a simplified reference architecture is shown in figure 1.

Smart Contracts
The smart contracts have been developed in Solidity [11], the object-oriented, high-level language for implementing smart contracts on Ethereum, using Remix [4], the browser-based compiler and IDE that enables users to build Ethereum contracts and to debug transactions.
The manager smart contract, implemented in the ManagerContract class, is in charge to a) manage the interface with IoT sensors and safety of data, b) manage the voting process at each occurrence of it, and c) make operational the most voted proposal, which will monitor the application of policies and devolve incentives accordingly. Several variations to this general scheme are possible, of course, but for the sake of this paper such a general formulation will be adequate. In the next section we discuss the design patterns involved in the design of the proposed DApps for urban water management. The voting process code is inspired by the example on ballot available on Solidity documentation [5] . The vote starts and finishes, respectively, with the methods startVote and winningProposal. The latter, takes also care of counting the votes and electing the winner. The addProposalContract method allows users to propose a new contract, while the method vote allows user to vote for a proposal. Note that this method is payable because it has to collect the funding during the voting process and to transfer the accumulated funding to the winning proposal using the method trasferToWinner.
The proposal smart contract must essentially define a) how to measure the contribution by each citizen to the reduction of water consumption as measured by IoT sensors, and b) how to distribute incentives according to that contribution. Citizens are free to present proposals, namely alternative solutions that are democratically voted by the citizens themselves. The class ProposalContract represents a proposal of a citizen. The owner variable maintains the owner of the contract (this is crucial for the implementation of the access restriction pattern, see section 3). As already observed, the ManagerContract manages all the key phases of the process and consequently, before starting the voting phase, every participating contract should change its ownership to the ManagerContract calling changeOwner method.

Fig. 2. Interaction with the Smart Contracts
Finally, the proposal that wins the election phase become runnable and the corresponding smart contract is executed invoking the method runContract. This results in a call to the smart contract in charge of collecting the data on water consumption interacting with the oracle. This data are stored in the Proposal-Contract by the insertConsumption method. Each citizen is allowed to access only its own consumption data. The hash table consumers maintains the association between the user credentials that are used by the oracle to access the data, and their address in the blockchain.
WaterOracle is the smart contract that collects the data on the water meters from a source of data external to the blockchain.
The whole process, summarized in figure 2, which allows the citizens to select the smart contract that will become operative can be divided in three phases: 1) the proposal phase, 2) the selection phase and 3) the running phase. During the proposal phase, proposal contracts are submitted by the community. In the selection phase, proposal contracts are voted by the community. For the sake of simplicity, we assume that citizen can access the vote only by providing a fee that is used to accumulate the incentives. More realistic fee policies are scope for future work. The voted contract becomes operative in the running phase, and will actually distribute the accumulated incentives according to its own policies.
Web UI. Users can access the functions of the system by a web application running on his/her premises that interacts with the blockchain. This app is developed in Nodejs and web3.js[6], which is a collection of libraries allowing to interact with a local or remote Ethereum node, through HTTP, WebSocket and IPC connection. While in principle citizens can make their proposals in the form of free smart contracts encoded in solidity, in this paper we focus on a template smart contract where the proposals are characterized by different parameters that users can freely select accessing the Proposal page of the Web UI. Examples of the parameters defining the smart contracts are: What will be monitored (e.g. apartment, building), the Criteria to distribute the incentive (e.g. ≤ a given threshold) and the Interval in which the monitoring activity is performed and incentives are distributed (e.g. semester).
Once a proposal has been formalized, it can be voted accessing the Vote page, showed in figure 3, where users can inspect the proposals and finally vote for the most liked one. After a suitable time interval, that allows each voter to express their preferences, the winner proposal is elected and starts the running phase.
In the Run page the user can finally allow the selected smart contract to access its data on water consumption. If the criteria defining a virtuous behaviour embodied in the smart contract are meet, the corresponding incentives are automatically sent to the user.

Smart Contract Design Patterns
We used some of the Solidity design and programming patterns [24,9,25] collected by Franz Volland in his github repository [23]. The aim of this section is double: to discuss how these design patterns have been employed to implement the methods and the smart contracts in the proposed decentralized system for water management; to describe how a design pattern is expanded in the case of a blockchain design pattern (BDP).
The documentation for a design pattern describes the context in which the pattern is used, the forces within the context that the pattern seeks to resolve, and the suggested solution. A variety of different formats [14] have been used by different pattern authors. [23] uses one of these approaches. We intend to add two additional fields for describing a BDP: -The first is cost of execution -gas, i.e. the unit to measure the amount of computational effort to execute certain operations. Its presence is fundamental and necessary for public blockchains such as Ethereum: this in fact avoids that an operation performs forever on the blockchain blocking the entire network. -Secondly, there are the blockchain specific features which are a set of properties that highlights how BDP are related with peculiar characteristics of blockchains. We have identified decentralization and on-chain or off-chain properties.
For the sake of space we don't sketch the code of all patterns, the interested reader is referred to [2] and we do not report the formal description of the patterns already available at [23], but we focus our attention to the two additional descriptive fields presented above.
Ownership and Access Restriction pattern During the proposal phase, users make contract proposals. In order to participate to the next selection phase, users have to release contract ownership to the manager smart contract. This is done by implementing the Access Restriction pattern which allows the ownership of a contract to be changed. The proposer invokes the changeOwner function , providing as input the address of the manager that consequently becomes the owner. We stress here that at each instant in time there is only one owner for a contract and some functions can be invoked only by the owner because they are critical for the correct execution of the contract.
Cost of execution -gas. changeOwner() 28595 Blockchain specific features Decentralization of the BDP Decentralized BDP On-chain or off-chain solution.
The owner is stored into a variable of the smart contract, so it is an on-chain solution.
State Machine pattern In each phase, a proposal contract can be in one of three possible states: proposal, selection and running. Only the owner of a contract can change the status of the contract. The State Machine pattern [23] allows a contract to go through different states, with different functions enabled in the different states. A function modifier checks if the contract stage is equal to the required stage before executing the called function. Note that the manager, becoming the owner of the contracts, is the only one capable to change the state of a contract during the selection phase (see Access Restriction pattern: onlyBy(owner)).
Cost of execution -gas. nextStage() 27632 Blockchain specific features Decentralization of the BDP Decentralized BDP On-chain or off-chain solution.

It changes the internal state of a smart contract that lives on-chain
Oracle pattern Once in a running state, the winning smart contract needs to collect data from the smart meters to correctly dispense incentives to the users. This requires the communication with an Oracle, a centralization point, to gain access to data outside the blockchain. An Oracle is hence a trusted entity providing a unique view on a source of data considered credible. Each node in the blockchain has to validate every computation performed in a smart contract. When this requires the interaction with off-chain sources of data, as in our case with smart meters, this becomes unpractical because, due to network issues (e.g. delays), there are not guarantee that all the node will access the same information as expected thus leading to a possible break in the consensus algorithm.
In our PoC, we use the oracle service provided by Oraclize [3], see listing 1 (recently Oraclize changed its name to Provable). The function getWaterConsumption is invoked by the ProposalContract and performs the query to the oracle. The fallback function is necessary to support the necessary payments to the Oracle: only if the balance of the WaterOracle smart contract is sufficient, the query is delivered to the Oraclize contract that access the data interacting with the data source API. Once data are available a callback function is called to store the values on the ProposalContract in the public variable water. The value of water is finally used to distribute the incentives.

Decentralization of the BDP
Most oracles are points of centralization within the network. However projects on decentralized Oracles exists, such as ChainLink [1] which Provable, the new brand behind Oraclize, now supports.

On-chain or off-chain solution.
This pattern can be implemented either partly on-chain and off-chain (an oracle smart contract with external state injected by an off-chain injector) or totally off-chain (external server signing transactions). [25] 3.1 Discussion Design Patterns are descriptions or templates to solve problems that can emerge in many different situations, and consequently are usually not a finished design that can be transformed directly into code [14]. However, in the Blockchain, the implementation details have direct consequences on the execution costs of a given pattern that are crucial to determine the feasibility and the success of a project. If the costs of running a system are higher than the expected benefits, users will possibly not participate in the initiative. As far as concerns the level of decentralization this is crucial to support the democratization of an initiative and thus the active participation of the users, but can have a cost. Let's consider the oracle example. The simplest solution that relies on a single "centralised" oracle is likely the most cost effective. We can reduce the centralization requiring the same information to n independent oracles, but even assuming that we can get the exact same information (e.f. time and source) from all of them, this will result in a cost n-times higher.
The introduction of quantitative metrics (i.e. gas) to evaluate design patterns is not novel (see [7] and [10]) and necessarily require the implementation of the considered design patterns.

Related work
The need for a blockchain-oriented software engineering (BOSE) is recognised in [19] where the authors suggest that ensuring effective testing activities, enhancing collaboration in large teams, and facilitating the development of smart contracts all appear as key factors in the future of blockchain-oriented software development. Compared to traditional Software Engineering, BOSE is not yet well developed and Smart Contracts rely on a non-standard software life-cycle. As an example, once delployed, they can be hardly updated and even simple bugs are difficult to fix. [12] suggests to focus on three main areas for the development of BOSE: a) Best practices and development methodology, b) Design patterns and c) Testing.
In [9] the authors quantify the usage of smart contracts on Bitcoin and Ethereum in relation to their application domain and analyse the most common programming patterns in Ethereum.
Due to the inherent nature of blockchain based contract execution, missing low level programming abstractions, and the constant evolution of platform features and security considerations, writing correct and secure smart contracts for Ethereum is a difficult task. In [24] the authors mined a number of design patterns providing design guidelines and showed that those patterns are widely used to address application requirements and common problems.
The literature on blockchain technologies in the smart cities has been recently reviewed in [21]. The paper analyses a number of sectors where the blockchain can contribute to build a smarter city, including water management. A privacyfriendly blockchain-based gaming platform aiming at engaging users in reducing water or energy consumption at their premises is proposed in [20], but this paper does not explicitly use smart contracts.
In [18] the authors stress that lack of transparency and trust on a centralized network infrastructure could be a key factor that hinders the true realization of the citizen participatory governance model. Our proposed DApp is an example of smart urban collaboration implemented over a P2P network thus overcoming most of the limits of traditional centralized networks and guaranteeing an unprecedented level of transparency and trust. In the blockchain, the trust shift from a single and centralized third party to the whole P2P infrastructure, that is decentralized in its nature.
Voting is considered among the most important application of the blockchain technology in the public sector [16]. In our proposed approach, voting is used to select which among the proposed contracts will become actually operative. A fully aware vote requires the understanding of smart contracts and their implications and we cannot expect this is within everyone's reach. The research on the methods to wider the audience capable of understanding smart contracts is out of the scope of this paper. In our implementation, we propose a smart contract template where users can simply and freely select some of the key parameters defining the contract. .
On Refining Design Patterns for Smart Contract 11

Conclusion
In this paper we discussed the applicability of solidity design patterns to the development of decentralized application (DApp) for urban water management. The decentralized nature of DApp implements a democratic process that will hopefully encourage the active participation of the citizen to the actions necessary to reduce the water consumption. Design patterns are among the key ingredients that have been identified to develop a blockchain-oriented software engineering (BOSE) capable to reduce the risks connected to the unique life-cycle of smart contracts. The main contribution of the paper can be summarized in the following points: -Moving from a centralized Client/Server architecture, typical of current implementations of smart city service, to DApps will remove the necessity of trusting central authorities, which is considered one of the most relevant factors that limit the true realization of citizen participatory governance [18]. -The code of the proposed DApp is available on the github repository [2].
-We propose an extension of the design patterns considering two additional fields, namely cost of transaction and blockchain specific feature that helps developers in implementing a more effective DApp. -The proposed extension has been discussed in the implementation of the three design patterns [23] employed in the proposed DApp.