Smart Contract Negotiation using Upgrad- able Smart Contracts Master’s thesis in Computer Science and Engineering STEPHEN OCHIENG ODHIAMBO Department of Computer Science and Engineering CHALMERS UNIVERSITY OF TECHNOLOGY UNIVERSITY OF GOTHENBURG Gothenburg, Sweden 2023 Master’s thesis 2023 Smart Contract Negotiation using Upgradable Smart Contracts STEPHEN OCHIENG ODHIAMBO Department of Computer Science and Engineering Chalmers University of Technology University of Gothenburg Gothenburg, Sweden 2023 STEPHEN OCHIENG ODHIAMBO © STEPHEN OCHIENG ODHIAMBO, 2023. Supervisor: Gerardo Schneider, Computer Science and Engineering Examiner: Wolfgang Ahrendt, Computer Science and Engineering Master’s Thesis 2023 Department of Computer Science and Engineering Chalmers University of Technology and University of Gothenburg SE-412 96 Gothenburg Telephone +46 31 772 1000 Typeset in LATEX Gothenburg, Sweden 2023 iv Abstract Recently, there has been a noticeable transition from centralized computing sys- tems towards decentralized distributed platforms, significantly influenced by the rise of blockchain technologies, exemplified by innovations like Bitcoin. This advent has spurred the growth of decentralized applications (dApps) spanning diverse sec- tors, from real estate and banking to insurance and digital identity. Key to this widespread adoption is blockchain’s inherent transparency, tamper-resistance, and trustworthiness, which it achieves through smart contracts. Industries are leverag- ing smart contracts to streamline negotiations. However, the immutable nature of smart contracts poses challenges, especially when continuous negotiations demand adaptability. This situation leads us to explore Upgradeable Smart Contracts that can accommodate the dynamic nature of negotiations. In this thesis, we first exam- ine the state of the art, focusing on upgradeable mechanisms such as proxy patterns. We then present a proof of concept implementation of the transparent proxy pattern to investigate how they can be used to facilitate negotiation. We use the logistics industry as a case study. Keywords: Ethereum, Blockchain, Upgradeable Smart Contracts. v Acknowledgements First and foremost, I extend my deepest appreciation to my supervisor, Gerardo Schneider, for your unwavering guidance, patience, and expertise. Your wisdom and feedback have been instrumental in shaping this research, and your commitment to my growth as a scholar has left an indelible mark on my academic journey. I am also immensely grateful to Wolfgang Ahrendt, my examiner, for your meticulous critique and invaluable suggestions. Your keen insights and in-depth evaluations have greatly enhanced the quality and rigour of this work. Lastly, my heartfelt thanks go to my family and friends. Your constant encourage- ment, patience, and belief in my abilities have been the foundation of this academic venture. Your unwavering faith in my capabilities and continuous support inspired and motivated me. To all of you who have been a part of this journey, directly or indirectly, I owe my deepest gratitude. This thesis stands as a testament to my efforts and the collective commitment, guidance, and encouragement I’ve been fortunate enough to receive. Thank you. Stephen Ochieng Odhiambo, Gothenburg, 2023-12-10 vii Contents List of Figures xi List of Tables xiii 1 Introduction 1 1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Goals and Research Questions . . . . . . . . . . . . . . . . . . . . . . 2 1.3 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.4 Approach and Implementation . . . . . . . . . . . . . . . . . . . . . . 3 2 Theoretical Background 5 2.1 Blockchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.2 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.3 Types of Blockchain . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.4 Blockchain and Contract Management . . . . . . . . . . . . . . . . . 7 2.5 Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.5.1 Ether and Gas System . . . . . . . . . . . . . . . . . . . . . . 8 2.6 Smart Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.7 Upgradeable smart contracts . . . . . . . . . . . . . . . . . . . . . . . 10 2.7.1 Importance of upgrading smart contracts . . . . . . . . . . . . 11 2.7.2 Strategies to upgrade smart contracts . . . . . . . . . . . . . . 11 2.7.3 Upgrade mechanisms . . . . . . . . . . . . . . . . . . . . . . . 12 2.7.3.1 Contract migration . . . . . . . . . . . . . . . . . . . 12 2.7.3.2 Data separation . . . . . . . . . . . . . . . . . . . . . 12 2.7.3.3 Strategy pattern . . . . . . . . . . . . . . . . . . . . 13 2.7.3.4 Proxy pattern . . . . . . . . . . . . . . . . . . . . . . 13 2.7.3.5 Diamond pattern . . . . . . . . . . . . . . . . . . . . 13 3 Architecture 15 3.1 Command Line Interface (CLI) . . . . . . . . . . . . . . . . . . . . . 16 3.1.1 HardHat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2 Ethereum Local Network . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.3 Upgrade engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3.1 OpenZeppelin . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3.2 Proxy Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3.3 Transparent proxy pattern . . . . . . . . . . . . . . . . . . . . 20 ix Contents 3.3.4 Universal Upgreadable proxy pattern . . . . . . . . . . . . . . 20 4 UseCase and Implementation 23 4.1 Scenario: Contract renegotiation in Logistics . . . . . . . . . . . . . . 23 4.2 Changes in Regulation . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4.2.1 Workflow: Use case Execution . . . . . . . . . . . . . . . . . . 24 4.3 System description . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 4.4 Building the Upgradeable smart Contract . . . . . . . . . . . . . . . . 25 4.4.1 State Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 25 4.4.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 4.4.3 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 4.4.4 Upgradeability Mechanism . . . . . . . . . . . . . . . . . . . . 26 4.4.4.1 deployProxy() . . . . . . . . . . . . . . . . . . . . . 27 4.4.4.2 upgradeProxy() . . . . . . . . . . . . . . . . . . . . 28 4.4.4.3 The bigger picture: Upgradeable Contract lifecycle . 28 4.5 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.5.1 Descriptive Evaluation . . . . . . . . . . . . . . . . . . . . . . 29 4.5.2 Negotiable terms analysis . . . . . . . . . . . . . . . . . . . . 30 4.5.2.1 Delivery Time . . . . . . . . . . . . . . . . . . . . . . 31 4.5.2.2 Freight Charges and Price . . . . . . . . . . . . . . . 33 4.5.2.3 Refunds rate . . . . . . . . . . . . . . . . . . . . . . 34 5 Related Work 37 5.1 Related work review . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 5.1.1 Taxiarchis et al [24] . . . . . . . . . . . . . . . . . . . . . . . . 37 5.1.2 Krohling et al [25] . . . . . . . . . . . . . . . . . . . . . . . . 38 5.2 Comparative Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 39 5.2.1 Methodologies and Approaches . . . . . . . . . . . . . . . . . 39 5.2.2 Results and Findings . . . . . . . . . . . . . . . . . . . . . . . 40 5.3 Evaluation of Contributions and Novelty . . . . . . . . . . . . . . . . 40 6 Conclusion 43 6.1 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Bibliography 45 A Appendix 1 I x List of Figures 3.1 Highlevel Architecture diagram. . . . . . . . . . . . . . . . . . . . . . 15 3.2 Transparent Proxy overview . . . . . . . . . . . . . . . . . . . . . . . 18 3.3 Visual explanation of the upgradeTo() function . . . . . . . . . . . . 18 3.4 Influencing proxy types through upgrade pattern placement. . . . . . 20 3.5 Overview of the Transparent Proxy Pattern. . . . . . . . . . . . . . . 20 3.6 Overview of the UUPS Proxy Pattern. . . . . . . . . . . . . . . . . . 20 xi List of Figures xii List of Tables 2.1 Comparison among public and private blockchain . . . . . . . . . . . 7 2.2 Properties of consortium blockchain . . . . . . . . . . . . . . . . . . . 7 2.3 Ethereum in Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 8 xiii List of Tables xiv 1 Introduction 1.1 Motivation Over the years, several network applications have shifted away from centralized com- puting with a central server and clients to more decentralized distributed systems. This shift has primarily been influenced by the popularity of blockchain technologies such as bitcoin [1]. Blockchain is a decentralized peer-to-peer network where partic- ipants maintain a replica of a shared ledger containing digitally signed transactions. Records are stored in groups called blocks; each time-stamped and linked to the previous block using cryptographic functions [2]. Since its inception, there has been a rise in decentralized applications (dApps) applied in many different fields, such as real estate, banking, digital identity and in the insurance industry. Blockchain leverages the distributed shared ledger, which is always in sync as the single source of truth. It enforces increased transparency and tamper-proof transac- tions among all members, increasing trustworthiness in the network by capitalizing on smart contracts. The latter, a concept formalized by Nick Szabo [3], has been pivotal to achieving this level of trust in dApps. Smart contracts are decentralized agreements built-in computer code and stored on a blockchain [4]. Nick Szabo’s main idea was to use a distributed ledger to store smart contracts and diminish contracting costs, enforcing contractual agreements and making payments while at the same time ensuring trust and compliance with the absence of a central authority [3]. Ethereum [5] has been at the forefront of smart contract development, specifically created and designed to support smart contracts. This has led businesses to utilize smart contracts to make their processes more seamless. For instance, in the real estate industry, where negotiation is prevalent, smart contracts have been deployed to create dApps that help negotiate terms to get the best deal. However, this negotiation process is characterized by lengthy back-and-forth until an agreement is reached, which is a big challenge because of the immutability of smart contracts. This begs the question, how do we design our smart contracts to accommodate the above problem or what techniques can be used to address the ever-changing clauses resulting from negotiation. Undoubtedly, smart contracts have revolutionized how businesses and individuals interact with each other, but they fall short in that they do not provide dynamism 1 1. Introduction due to the property of immutability. Upgradeable smart contracts (USC) [6] can solve the problems related to the negotiation spectrum that make it hard to translate them directly to smart contracts. USC are a type of smart contract that allows the replacement of contract code once it is deployed to the blockchain. The concept of upgradable smart contracts has evolved due to ongoing research and development in the Ethereum community. Introducing new ways to deploy smart contracts that can be replaced or upgraded allowed for more flexibility and ease of maintenance for smart contract development. Upgradeable smart contracts offer companies a reliable and cost-effective process for negotiating with their partners, clients, and suppliers. USC can enable parties to quickly and easily update their terms without needing to re-negotiate the entire agreement, thereby eliminating costly and time- consuming processes associated with traditional negotiations. Furthermore, since upgradeable smart contracts allow behavioural change of a contract, businesses can swiftly adjust to changing regulations and legal obligations, resulting in more up-to- date and reliable agreements. 1.2 Goals and Research Questions This thesis aims to explore the domain of upgradable smart contracts and ultimately design a smart contract that utilizes those domain concepts. This will be done to see how changing the behaviour of smart contract code can help facilitate the negotiation of contract terms between two parties in a specific use case. The pivotal research questions guiding the objectives of this study include: 1. What are the different mechanisms used in upgradeable smart con- tracts? This research question seeks to understand how to make smart contracts up- gradeable. To answer this research question, I performed a literature review on some popular upgrade mechanisms and planned to implement at least one to demonstrate the concept of upgradeability. 2. Can a smart contract be designed using an upgrade mechanism that facilitates negotiation? This question aims to assess the technical feasibility of the POC application. This will be answered at the end of the implementa- tion phase. 3. What are the implications of using upgradeable smart contracts? This research question seeks to answer the issues of using upgradeable smart contracts to facilitate negotiation. This will be answered by investigating the product of the implementation and pointing out areas where upgrading contracts would not be viable. This research intends to make the following contribution: • Examine the state of Blockchain technology to leverage its features to facilitate negotiation using upgradeable smart contracts. Additionally, it aims to assess the viability of upgradeable smart contracts and demonstrate the use of smart contract upgrading mechanisms to tackle the negotiation process between two 2 1. Introduction parties in a specified use case. In conclusion, propose better ways to han- dle the negotiation process through knowledge sharing to promote knowledge generation and dissemination. This contribution will be assessed by imple- menting a proof of concept application (POC) that uses the most befitting upgrade mechanism to demonstrate the feasibility of upgradable contracts in the negotiation spectrum. 1.3 Limitations This body of work will not cover the administration of upgradeable contracts. This means that rather than focusing on who is in charge of the upgrades, more attention will be given to proving that the upgrade mechanism patterns can be leveraged to achieve negotiation in smart contracts. An example of an administrative activity is implementing a multi-signature governance system. This will not be covered due to insufficient knowledge and experience with the Ethereum ecosystem. Also not covered in this study is the cost (gas, in the context of Ethereum) introduced by a particular smart contract upgrade pattern. For example, copying the current state to a new contract due to migration requires many transactions, thus increasing gas fees. While this is an important concern, it is not the particular focal point of this study. Due to the different upgrade mechanisms available, I will focus on only two of them to limit the scope due to the time constraints of the thesis period. 1.4 Approach and Implementation The methodology employed is broken down into the following: 1. Literature survey. 2. Identification of Blockchain platform. 3. Identify the different Upgrade Patterns. 4. Select relevant libraries for the application. 5. Design and develop the POC using the negotiation mechanism. A literature survey was conducted on blockchain and smart contract usage in the negotiation spectrum. This involved the study of relevant publications, scholarly journals and other pertinent sources. The next step was identifying a blockchain platform to implement smart contracts. The two ideal platforms for building POC applications in blockchain are Ethereum and IBM Hyperledger Composer. This is because they allow one to iterate and provide additional requirements quickly. How- ever, the latter’s support was deprecated on 29th August 2019, so Ethereum is the most suitable candidate as it is widely popular in creating Dapps. To be conversant with Ethereum’s language of choice - Solidity [7], the technical documentation pro- vided by the official Ethereum team will be used as the primary reference material. 3 1. Introduction Knowledge gained from learning this programming language will enable the devel- opment of smart contracts and the creation of a proof of concept application (POC). Upon successful completion of the previous steps, the next step includes research of the different smart contract upgrade patterns as listed below: • Contract migration • Data Separation • Proxy patterns • Strategy Pattern • Diamond pattern The upgrade patterns above are essential and relevant to the fundamental topic of the thesis. Detailed explanations of these patterns will be explained in a later section. The upgrade mechanism of choice is the proxy pattern, as it allows for a more flexible and less disruptive way to update and upgrade smart contracts. The proxy pattern is divided into two types: Transparent Proxy Pattern and UUPS Proxy Pattern. These two patterns are the most commonly used methods for upgrading smart contracts on the Ethereum blockchain. The implementation phase will consist of selecting which libraries to use, for example, Truffle or HardHat in Ethereum development. Once the libraries are selected, a negotiation process using the chosen upgrade mechanism will be designed and developed. As a result, a proof- of-concept application that uses either mechanism will be realised. 4 2 Theoretical Background In this Chapter, we look at the technical background of our work. We provide a background on Blockchain and how it works. We also look at different types of Blockchains and contract management in Ethereum. We explain concepts such as Smart Contracts and Upgradeable smart contracts. In Upgradeable smart con- tracts, we look at the importance of upgrades, different strategies for upgrading the contracts, and the different mechanisms. 2.1 Blockchain More than a decade ago, Blockchain Technology was proposed as a solution to solv- ing the problem of maintaining the order of transactions and avoiding the double- spending problem [1]. Its name is owed to how transaction data is stored in blocks linked through cryptography, forming a chain. This revolutionary technology has since become renowned for its consequential role in cryptocurrency and most fa- mously in Bitcoin by maintaining a secure and decentralized record of transactions. The guarantee of fidelity and security of data records promotes increased trust with- out requiring a third party - this is the innovation with Blockchain. The number of cryptocurrencies illustrates Blockchains importance, currently exceeding 1900 and growing [8]. 2.2 How It Works Blockchain, in principle, should be viewed as a distributed timestamped append-only data structure. More formally, Blockchain is a type of distributed ledger technology described as a secure fixed (immutable) ledger facilitating the process of transaction recording and asset tracking in a business network. An asset refers to something tangible (land, car, house) or intangible (patents, intellectual property). This ledger is maintained by a network of computers called "nodes". When a transaction is requested or initiated, it becomes part of a block on the chain. Each block con- tains the details of multiple transaction information, including the sender, receiver, timestamp and any other important relevant information. To protect this data, encryption is performed and the resultant encrypted data is stored in a digital signature. This signature is unique to each transaction and provides a secure way to validate the authenticity of the data. The digital signature 5 2. Theoretical Background also helps protect the data from any malicious parties, as any changes to the data would invalidate the signature. The information is broadcast to the entire network, where every node verifies the transaction using a consensus algorithm. This implies that all nodes must agree on the validity of transactions. Once the transaction is verified, it is added to a block, which is then linked to previous blocks through a cryptographic hash to form a chain. As a consequence of this hash, it is impossible to alter, insert or remove any block from the chain, preventing tampering whilst ensuring data integrity and immutability of the ledger. Hence, each additional block fortifies, verifying the preceding block and the whole blockchain. 2.3 Types of Blockchain Highlighted below are four different types of blockchains, namely: • Public Blockchain This is a permissionless, non-restrictive distributed ledger where anyone can join, read or write transactions. It is completely transparent, meaning any- one with an internet connection can access it and view historical transactions. There is no authoritative party responsible for decision-making. Instead, some members of the Blockchain take part in making decisions. Public blockchain networks can be leveraged to facilitate voting, ensuring openness and trust, and fundraising to promote transparency. Examples of public blockchain plat- forms are Ethereum, Litecoin and Bitcoin. • Private Blockchain This blockchain network works within a restricted context and is often opti- mal for private organizations and businesses. Participants join the network by invitation, where their identity or any prerequisite information is verified. Organizations can use private blockchain networks to customize authorization and accessibility preferences, among other relevant security options. Examples of private blockchains are Hyperledger projects [9] such as Sawtooth, Fabric, Corda and Multichain. • Permissioned Blockchain This permission-based system works in coordination with a permissionless sys- tem allowing organizations to get the best of both worlds. It is also known as a hybrid blockchain. It enables a better structure when placing restrictions on who has the right to participate in the network and in which transactions. Transactions are typically not made public, but if necessary, they can be vali- dated by granting access to participants via a smart contract. An example of a hybrid blockchain is Dragonchain [10]. • Consortium Blockchain This type of blockchain is similar to the permissioned blockchain in that it has both public and private components, except that multiple organizations man- age a single consortium network, also known as a federated blockchain. The organizations within this consortium decide who can conduct transactions or access data. They are ideal for collaboration and coordination with multi- 6 2. Theoretical Background ple organizations. Examples of consortium blockchains are R3, Energy Web Foundation, etc. Property Public Private Consensus determination All nodes Selected nodes Read permission Public Could be public or restricted Immutability Nearly impossible Could be tampered Centralised No Partial Consensus process Permissionless Permissioned Efficiency Low High Source: [11] Table 2.1: Comparison among public and private blockchain Property Consortium blockchain Consensus determination Through one organization Read permission Could be public or restricted Immutability Could be tampered Centralised Yes Consensus process Permissioned Efficiency High Source: [11] Table 2.2: Properties of consortium blockchain The tables 2.1 and 2.2 compare the three types of blockchain mentioned at the begin- ning of this section based on different properties. In the tables above, immutability within blockchain technology can be articulated as follows: the inherent difficulty in altering the logic of contracts once stored on the chain. Due to the decentralized storage of transaction data across various nodes in a public blockchain network, al- tering this type of blockchain is extremely challenging. On the other hand, in the case of a consortium or private blockchain, if a significant portion of the network, such as a majority in a consortium or a controlling entity in a private blockchain, decides to modify the data, it becomes feasible to alter or reverse transactions within these blockchains. 2.4 Blockchain and Contract Management Smart contracts are built upon blockchain technology, ensuring the correct execu- tion of the contracts [12]. When certain predefined conditions are met in a smart contract, contract clauses written in computer programs are automatically executed. Transactions in a smart contract are essentially stored, replicated and kept up to date in distributed blockchains. Conventional contracts, on the other hand, require a centralised intervention of a centralised manner through a trusted third party, re- sulting in extra costs and a longer duration of execution. With the integration of 7 2. Theoretical Background Blockchain technology into smart contracts, the ’peer-to-peer market’ dream will be realized. Blockchain-powered contracts remove the need for intermediaries, ef- fecting faster transactions and fewer manipulations. Moreover, Blockchain offers a transparent and verifiable trail of transactions on the network, promoting data in- tegrity and accuracy. Due to the utilization of advanced cryptography, the integrity of transactional data and the protection of sensitive information within the contract processes are heavily safeguarded. In conclusion, it is evident that Blockchain tech- nology has and will continue to revolutionize the contract management space due to its features. 2.5 Ethereum Ethereum [13] was proposed by Vitalik Buterin and published in 2014 before its launch at the end of 2015. It was built as a community-driven, open-source platform based on blockchain technology, that has evolved astronomically since its launch. The table below substantiates the pervasiveness of Ethereum. Projects built on Ethereum 2970 Accounts (wallets) with an ETH balance 71M+ Smart contracts on Ethereum 50.5M The value moved through the Ethereum network in 2021 $11.6T Creator earnings on Ethereum in 2021 $3.5B Number of transactions today 964K Source: Ethereum.org, 2022 [6] Table 2.3: Ethereum in Numbers The Ethereum platform has been influential to developers by providing them with tools to rapidly build and run the code of decentralized applications (Dapps). It does this by providing an abstraction layer (i.e., blockchain with a built-in Turing- Complete Machine programming language) allowing the development of scripts (known as Smart Contracts) that execute as blockchain transactions [13]. The blockchain network is used to synchronize the state of the applications globally, verifiable by any participant in the network [14]. 2.5.1 Ether and Gas System Applications built on the Ethereum network share a finite pool of resources and a mechanism is needed to ensure that no application consumes all network resources. Ethereum implements a pricing mechanism that utilizes its native cryptocurrency known as Ether (ETH) [13]. The pricing mechanism requires users to pay a fee (known as gas) for each transaction they make on the Ethereum network to be val- idated on the chain. The complexity of the transaction carried out on the network determines the amount of gas required. This ensures even distribution of network resources in the network. Gas price in Ethereum is measured using two denomina- tions, wei and gwei. The former is the smallest amount of Ether used in technical 8 2. Theoretical Background implementations such as Ethereum Yellowpaper [15] to perform calculations. At the same time, the latter is a more human-readable format to describe gas fees on Ethereum. Ether is critical in ensuring the growth and evolution of the Ethereum Platform. 2.6 Smart Contracts A smart contract is a program or protocol that encodes and enforces an agreement [3]. When a specific situation is achieved, contractual conditions included in smart con- tracts will be automatically enforced. A trivial metaphor used by Nick Szabo is that a vending machine could be viewed as a primitive predecessor of smart contracts by enforcing the agreement that a coin can be traded for a can of soda. Smart contracts are made possible by blockchain and the accepted contractual provisions are trans- formed into computer programs that can be executed. The logic to implement these provisions takes the form of logical flows where the logical linkages between contrac- tual provisions have been retained (e.g., through the use of the if-else-if statement). Each contract statement’s execution is documented as an unchangeable blockchain transaction. In addition to contract enforcement, smart contracts also guarantee access control. Access authorization for each contract function in particular, can be provided by developers. Any time a check is made and a condition in a smart contract is met, the triggered statement will predictably and automatically perform the relevant function. For instance, Alice and Bob concur on the fine for breaching the agreement. If Bob breaks the agreement, the contract’s stipulated penalty will be automatically paid (subtracted) from Bob’s deposit. Solidity and Vyper are two high-level languages used to develop smart contracts. However, more experienced developers use Yul or Yul+ (an extension to Yul) as an intermediate language for the Ethereum Virtual Machine (EVM). Ethereum em- ploys the EVM (Ethereum Virtual Machine) to execute smart contracts. The smart contract is compiled into EVM bytecode and permanently saved on the blockchain when deployed to Ethereum by developers. 1 // SPDX -License -Identifier: MIT 2 pragma solidity ^0.8.0; 3 4 // A simple contract for a digital wallet 5 contract DigitalWallet { 6 // The owner of the wallet 7 address public owner; 8 9 // Constructor to set the owner of the wallet 10 constructor () { 11 owner = msg.sender; 12 } 13 14 // Function to deposit ether into the wallet 15 function deposit () public payable {} 16 17 // Function to withdraw ether from the wallet 18 function withdraw(uint amount) public { 9 2. Theoretical Background 19 require(msg.sender == owner , "Only the owner can withdraw") ; 20 require(amount <= address(this).balance , "Insufficient balance"); 21 22 payable(msg.sender).transfer(amount); 23 } 24 25 // Function to check the balance of the wallet 26 function getBalance () public view returns (uint) { 27 return address(this).balance; 28 } 29 } Listing 2.1: Smart Contract example to give a sense on what Solidity contract syntax is like. The code in listing 2.1 above is an example of a solidity contract that models a rudimentary digital wallet that only its creator can use to deposit and withdraw Ether (the coin used by Ethereum). In the Solidity smart contract for a digital wallet, the owner variable is crucial as it stores the address of the wallet’s owner, which is set during the contract’s deployment through the constructor. The deposit() function is designed to allow anyone to send Ether to the wallet, operating on the inherent transaction capability of Ethereum without the need for additional code. The withdraw (uint amount) function is exclusive to the owner, enabling them to withdraw a specified amount of Ether. This function includes two require statements for enhanced security: one to verify that the caller is the owner and another to check that the wallet has sufficient balance for the withdrawal. Lastly, the getBalance() function provides the functionality to check the wallet’s current balance, reflecting the total amount of Ether it holds. 2.7 Upgradeable smart contracts Smart contracts are fundamental in blockchain technology. They allow us to create automated and immutable agreements that eliminate the need for intermediaries. However, this mechanism has limitations, especially in its conventional form. It cannot be adjusted or modified once deployed. This is where upgradable smart contracts prove to be helpful. Upgradeable smart contracts allow developers to change a smart contract after its deployment to a blockchain. This contrasts with traditional smart contracts, which are fixed and cannot be changed once deployed. This key feature allows the contract to be improved over time rather than fixed in its initial form. Upgradeable smart contracts are implemented using various techniques, including proxy contracts, del- egate calls, and storage refactoring. These techniques allow developers to change the contract’s code or data without redeploying the contract. This is important, as redeploying a contract can be costly and may require the contract to be re-approved by users. In summary, upgradeable smart contracts allow developers to continuously improve their contracts to ensure they remain relevant and valuable to users. 10 2. Theoretical Background 2.7.1 Importance of upgrading smart contracts The immutability of smart contracts as a design feature averts any amendments to the business logic after it is deployed. While immutability is imperative for security, decentralization of smart contracts and trustlessness is a potential downside in some cases. One way immutable code can be problematic is that it can make it difficult or impossible to fix developer vulnerabilities in contracts (on Ethereum, such vulnerabilities may lead to a hacker stealing funds). As research into smart contracts has progressed, various approaches have been de- veloped to upgrade them while maintaining their immutability. These approaches, known as upgrade patterns, involve separating the business logic of a smart contract into different contracts, which can then be upgraded individually while maintaining immutability. Here are a few reasons why upgradeable smart contracts may be useful: • Bug fixes Even the most carefully written smart contracts may contain bugs or vulnerabilities discovered after deployment. Upgradeable smart contracts allow these issues to be fixed without the need to deploy a new contract. • Feature updates As users’ needs evolve, adding new features or functionality to a smart contract may be desirable. Upgradeable smart contracts allow these updates to be made without deploying a new contract. • Improved security Upgradeable smart contracts can be designed with secu- rity in mind, using techniques such as contract separation and upgradeability guards to ensure the contract can be safely modified without introducing vul- nerabilities. Overall, upgradeable smart contracts offer a way to update and improve upon exist- ing smart contracts without the need to deploy a new contract, which can be costly and time-consuming. 2.7.2 Strategies to upgrade smart contracts Upgrading smart contracts entail modifying the underlying logic of the contract whilst preserving the prevailing state of the contract. It is important to note that the ability to upgrade a smart contract does not necessarily mean that the con- tract is mutable or can be changed at any time. Upgradeability and mutability are distinct concepts in the context of smart contracts. Through updates of its code, the behaviour of a smart contract can be changed but the actual program on the Ethereum network cannot be altered once it has been deployed. Some of the ways in which this can be done include [6]: • Create a new contract version and migrate the existing data, or state, from the old contract to the new one. This requires the deployment of a new instance of the contract and migrating the state from the old contract to the new one. • Creation of different contracts for storing state and business logic. Separating 11 2. Theoretical Background business logic from the state of the contract into different contracts allows the business logic to be updated or modified without changing the state of the contract, or the data stored within it. • Creation of an immutable main contract that communicates with satellite contracts to perform specific tasks. These satellite contracts can be more flexible and updated or modified as needed, while the main contract remains unchanged. • Delegating function calls from a proxy contract to logic contracts by exploiting the diamond pattern. This allows the logic contracts to be updated or modi- fied without changing the proxy contract, which can be useful for updating a contract without interrupting its operation. • Utilize a proxy pattern, which involves an immutable proxy contract that redi- rects (delegates) function calls to a modifiable logic contract. The proxy con- tract is fixed and cannot be changed, while the logic contract can be updated or modified as needed The proxy pattern and diamond pattern may seem similar because they are except that the diamond pattern is an improvement of the proxy pattern. A detailed explanation of all patterns is expounded on in the next section. 2.7.3 Upgrade mechanisms 2.7.3.1 Contract migration Contract migration is a process for upgrading a smart contract by deploying a new version of the contract and transferring the existing data, or state, from the old contract to the new one. This involves creating a new instance of the contract with empty storage, recovering the state from the previous contract, and writing it to the new contract. Following this, all contracts that interacted with the old contracts need to be updated to mirror the new address. Finally, users need to be persuaded that the new contract version will preserve all user balances and addresses, hence maintaining the overall immutability of the contract. Generally, the contract migration mechanism is a relatively simple and secure pro- cess. However, the manual transfer of user data and balances to the new contract may be expensive in terms of gas costs and time. 2.7.3.2 Data separation This approach is premised on maintaining separate, independent contracts for data storage and business logic, meaning that users interact with the logic contract. At the same time, the state is saved in the storage contract. Embedded into the logic contract is code executed by the user when interacting with the application. Addi- tionally, it stores the address of the storage contract enabling the interaction with it to get and set data. Consequently, the logic contract owns the storage contract, which restricts unauthorised contracts from connecting to the storage contract and 12 2. Theoretical Background updating its data. On the other hand, the storage contract holds the state of the smart contract, user balances and addresses. The storage contract by default is immutable, but the logic contract it references can be replaced with a new imple- mentation. Consequently, the logic contract’s address needs to be updated in the storage contract and similarly configured the storage contract’s address on the new logic contract. Data separation is arguably easier to implement in comparison to contract migration. Still, it requires managing multiple contracts and implementing complex authoriza- tion schemes to secure smart contracts from malicious upgrades. 2.7.3.3 Strategy pattern This method entails building smart contracts that make function calls from other contracts. The core business logic is contained in the main contract, which connects to other smart contracts, known as satellite contracts, to perform specific func- tions. The addresses of each satellite contract are stored in the main contract with the flexibility to switch between different implementations of the satellite contract, essentially facilitating change in strategies for a smart contract. The main disadvan- tage of this method is that its utility is majorly for rolling out minor upgrades. In the event that the main contract is attacked, say through a hacking attempt, this method can longer be used. 2.7.3.4 Proxy pattern Due to the inability to modify the code of an already deployed smart contract, proxy contract architecture enables the utilization of newly deployed contracts as if the primary logic has undergone an upgrade. This mechanism is achieved through a proxy contract, which acts as an intermediary between the external callers and the implementation contract. The proxy contract references the implementation contract, which can be updated to a new version when necessary. This allows for the seamless upgrade of the smart contract, as all calls from external entities will continue to be directed to the same proxy contract. At the same time, the underlying implementation can be changed. 2.7.3.5 Diamond pattern Diamonds are modular smart contract systems that can be upgraded/extended after deployment and have virtually no size limit. More technically, a diamond (proxy contract) is a contract with external functions that are supplied by contracts called facets. Facets are separate, independent smart contracts that can share internal functions, libraries, and state variables and represent the logic contracts in this pat- tern [16]. The diamond pattern is considered an improvement of the proxy pattern with the added advantage that any number of diamonds can use a deployed facet in the network. In other words, a diamond proxy contract can delegate function calls to more than one logic contract [6]. When a user calls a function, the proxy contract checks the mapping to find the facet responsible for executing that function. Then it invokes delegatecall (using the fallback function) and redirects the call to 13 2. Theoretical Background the appropriate logic contract [6]. Some of the reasons to use diamond patterns include: • Its smart contracts can exceed 24KB, storing all related logic in one place, especially in complex contracts requiring many functions. This is possible because the diamond pattern does not define a maximum size for the contract. • A diamond can be immutable. It is possible to deploy an immutable diamond or make an upgradeable diamond immutable at a later time [16]. • Can reduce gas costs (i.e., by reducing the number of external function calls) [17] • A diamond can be immutable. It is possible to deploy an immutable diamond or make an upgradeable diamond immutable at a later time [16]. 14 3 Architecture Figure 3.1: Highlevel Architecture diagram. 15 3. Architecture This chapter presents a detailed architecture of our proposed solution of using USC to facilitate negotiation. The system will be built on the Ethereum blockchain. This architecture aims to offer a platform that enables evolving business rules. Utilizing USCs allows us to decouple the data storage and business logic, thus enabling the contract to undergo alterations without disrupting the user experience or needing contract redeployment. Figure 3.1 shows the general overview of the system we propose in tackling negotia- tion using smart contracts. The system will consist of the following components: 1. CLI application: The command-line interface serves as the entry point for users to interact with the application and initiate contract negotiation actions. 2. Ethereum Local Network: This is the decentralized ledger where the smart contract code and data are stored, providing transparency and immutability to the negotiation process. It will also act as our development network. 3. Upgrade Engine: This is the core component that facilitates the negotiation process between parties involved in the contracts. It manages offers counterof- fers and updates contract terms accordingly. 3.1 Command Line Interface (CLI) The CLI bridges users and the system, allowing for fast and automated command execution. This section focuses on HardHat [18], intended to make interaction with Ethereum-based contracts easier. 3.1.1 HardHat It is a development environment and testing framework for Ethereum. It helps developers write code to interact with the Ethereum network locally. It offers a vast amount of features, for example: • Scripting. Allows developers to write scripts that interact with their con- tracts, thus enabling automation and management of the development process. This reduces the time to execute contracts. • Smart Contract Compilation. It can compile solidity, the language used in writing smart contracts in Ethereum. • Testing. It supports Javascript, making it easier for developers to write and run tests for smart contracts. 3.2 Ethereum Local Network The Ethereum Local Network is the system’s basic infrastructure, providing a secure, transparent, and tamper-proof environment for smart contract deployment and ex- 16 3. Architecture ecution. In this system, we will build a proof-of-concept application that will run on a local network to see if it supports our central argument that USC can help us achieve negotiation. One of the main reasons we decided to take this approach was that it reduces the overhead when acquiring Ether from a public testnet. In section 3.1, we saw that we would use Hardhat to interact with our application. However, it also provides a local Ethereum network to develop smart contracts. 3.3 Upgrade engine The upgrade engine is essential as it supports the formation of mutable smart con- tracts. The OpenZeppelin architecture and its role as an upgrade engine will be introduced in this part, as will the notion of Proxy patterns and two significant proxy patterns, Transparent and Universal Upgradeable Proxy Standards (UUPS). 3.3.1 OpenZeppelin OpenZeppelin [19] is a framework and library that enables Ethereum developers and organizations like Coinbase [20] and Ethereum Foundation [21] to develop secure and reliable smart contracts. It serves as the upgrade engine to upgrade contracts when negotiation occurs. Some of the features it offers include: • Proxy Contracts. It uses proxy patterns to implement upgradeable con- tracts. • Reusable Components. Components that can be integrated into projects to save development time. • Modularity and upgradability. It is designed this way to allow developers to upgrade and extend smart contracts in any way. • Developer tools. Provides a CLI which simplifies the process of deploying, upgrading and managing smart contracts. • Security. Heavily audited components that save development time as they adhere to established standards, thus reducing vulnerability risks. 3.3.2 Proxy Patterns As seen in section 2.7.3, several mechanisms exist for upgrading smart contracts; however, each has strengths and weaknesses. We chose the proxy pattern as it is widely used due to several reasons: 1. Ease of use: Proxies are developer-friendly and abstract most of the complex- ities away. OppenZeppelin [19] has contributed to this by providing this pat- tern in their ecosystem. It has also allowed developers to work with contracts as if they were developing regular contracts on the Ethereum Blockchain. 2. Efficiency: Gas consumption of proxy patterns is way less than other mech- anisms because it avoids multiple external function calls. This has therefore 17 3. Architecture resulted in considerable savings in a blockchain context where computational and storage expenses are high. 3. Minimal Data Migration: This pattern does not necessitate data transfer, which can be costly, time-consuming, and unsafe due to data loss or corruption. 4. Interoperability: Like other patterns, the proxy design ensures that contract addresses remain unchanged between updates. This is critical for preserving compatibility with other contracts and external integrations since they will no longer need to change their stored addresses. As mentioned in section 2.7.3.4, this pattern has a contract known as the Proxy contract, which serves as an intermediary between the user and the implementation contract as shown in Figure 3.2. Figure 3.2: Transparent Proxy overview The proxy contract is used when the external world (users, dapps, other contracts) references the system. It also stores the balances and maintains the internal state of the application. This enables the implementation contract to be changed with- out impacting the address or state of the proxy contract. To achieve upgradeabil- ity in this pattern, some critical functions are needed. One of them is the up- gradeTo(newImplementation). This function is called when we deploy a new logic contract. It takes the address of the new implementation, thus allowing the proxy contract to route future requests to the new implementation contract as illus- trated in Figure 3.3. Figure 3.3: Visual explanation of the upgradeTo() function Proxies tend also to use a lot of low-level functionality. One of the most used functions is the delegatecall(). This function enables code in the target contract to be executed in the context of the calling contract. An example is if you have two contracts, A and B, as shown in Listing 3.1. 18 3. Architecture 1 // SPDX -License -Identifier: MIT 2 pragma solidity 0.8.7; 3 4 contract A { 5 // Declare a 'value ' variable in Contract A 6 uint public value; 7 8 address public contractB; 9 10 constructor(address _contractB) { 11 contractB = _contractB; 12 } 13 14 function doDelegateCall(uint val) public { 15 // Perform a delegate call to 'setVal ' function of Contract B 16 (bool success , bytes memory data) = contractB.delegatecall( 17 abi.encodeWithSignature("setVal(uint256)", val) 18 ); 19 require(success , "Delegate call failed."); 20 } 21 } 22 23 contract B { 24 // Declare a 'value ' variable in Contract B 25 uint public value; 26 27 function setVal(uint val) public { 28 value = val; 29 } 30 } Listing 3.1: Delegatecall demonstration. Contract A will implement the logic of contract B. When contract B’s setVal func- tion is executed via contract A, it behaves as if it were a component of contract A, resulting in the value being set and stored in contract A’s storage rather than B’s. When paired with a fallback() function, this mechanism allows users to delegate calls from one contract (contract A) to another (contract B). It returns a boolean value that determines the success of these delegate calls. If the call is successful (true), the operation is completed without errors. An error occurs if the call fails (success is false). This allows the proxy contract to have the same address forever but allows the implementation contracts to change as much as possible. There are many proxy patterns. However, the most used are Universal Upgradeable proxy standard (UUPS) and Transparent proxy pattern [22]. The two patterns have the same working principle but are designed differently. The placement of the function within the contract architecture results in two distinct patterns: the Transparent Proxy Pattern when the upgrade function is located in the proxy contract and the UUPS Proxy Pattern when the function resides in the implementation contract. 19 3. Architecture Figure 3.4: Influencing proxy types through upgrade pattern placement. 3.3.3 Transparent proxy pattern Figure 3.5: Overview of the Transparent Proxy Pattern. The Transparent proxy pattern is a simple and efficient approach to imple- menting upgradeable contracts. Figure 3.5 shows the architectural overview of the pattern. Here a proxy contract forwards all function calls to the implementation contract. The implementation contract is then stored as a variable in the proxy contract. If an upgrade to the implementation contract is desired, a new implemen- tation contract can be deployed, and the address of the implementation contract can be updated in the proxy contract. All function calls made through the proxy contract will be forwarded to the new implementation contract. 3.3.4 Universal Upgreadable proxy pattern Figure 3.6: Overview of the UUPS Proxy Pattern. Universal Upgradeable Proxy pattern as shown in figure 3.6 is a more complex but flexible approach to implementing upgradeable contracts. This pattern sepa- rates the upgradeability and implementation logic, allowing for greater control over the upgrade process. This pattern has three contracts: the proxy and implemen- tation contracts. The proxy contract forwards function calls to the upgradeability 20 3. Architecture contract, which determines which implementation contract to forward the call to. If an upgrade is desired, the upgradeability contract checks whether the caller has permission to upgrade the implementation contract. If permission is granted, a new implementation contract is deployed, and the upgradeability contract updates the proxy contract to forward all function calls to the new implementation contract. We opted for the Transparent Proxy pattern in the context of the patterns discussed in Section 3.3.2. This choice was primarily motivated by its prevalent adoption in the domain. The popularity of this pattern can be attributed to its lucidity and the distinct separation of concerns it offers. Noteworthy implementations of this pattern can be found in projects such as OpenZeppelin [19]. Their Software Development Kit (SDK) has been pivotal in implementing and propagating the Transparent Proxy pattern. Consequently, numerous Ethereum projects that employ the OpenZeppelin SDK indirectly incorporate the Transparent Proxy pattern. Opting for the Univer- sal Upgradeable Proxy pattern would be predicated on requirements for enhanced flexibility, with a particular emphasis on gas efficiency, which we were not focusing on at this stage. 21 3. Architecture 22 4 UseCase and Implementation This section demonstrates a use case for USC in the logistics industry. The trans- portation and logistics industry has come a long way since the days of the horse and carriage. Technology and infrastructure improvements have considerably in- creased global trade and commerce by enabling faster, more effective transportation of products and people. Companies are specializing in the movement of goods with warehouses, distribution centers and transportation networks all working together to move products from manufacturers to consumers. However, there are still de- velopments and enhancements that call for more flexible and effective methods of managing agreements between parties. Smart contract technology has the poten- tial to revolutionize the contractual process by increasing transparency and security. One of the biggest challenges in logistics is the market’s volatility. Regulations and requirements change over time, necessitating updates to the initial agreement en- suring compliance and efficiency. USCs provide flexibility that allows these changes without disrupting the supply of goods from the logistics provider and the customer. This is valuable, especially when considering the frequent negotiations that may occur over factors such as delivery time, freight charges, price and payment terms, quality and quantity of goods and insurance. 4.1 Scenario: Contract renegotiation in Logistics Consider a scenario involving a Logistics company A and an educational institution B. A specializes in the delivery of academic books and is a trusted supplier. On the other hand, B is an institution with a public library that requires a regular supply of books. In their agreement, several contractual elements are defined that are negotiable, and they include: • Delivery Time A recurring monthly delivery time agreed upon by the two parties for books delivered over twelve months. • Freight Charges A specific fee is agreed upon for each cargo based on weight, distance, and current fuel rates. • Price and Payment Terms A per-unit pricing is set for each book, along with a payment plan. 23 4. UseCase and Implementation • Quality and quantity of goods The quality of books is established, as are the criteria and certification requirements. B’s needs determine the number of books to be delivered monthly, which may fluctuate due to student enrollment or curriculum adjustments. • Insurance The insurance cost is determined by the distance between A’s warehouse and B’s institution and the amount of risk involved with the delivery. This might involve the possibility of damage, loss, or theft. These elements are encapsulated in a Solidity contract published to the Ethereum network as a USC. This provides the ability to manage any changes to the agreement over time. In this thesis, we assume the contract proposal and approval between parties A and B happened before being uploaded to the Ethereum network, and the negotiation occurs after the contract has been finalized. 4.2 Changes in Regulation After several months, a government regulation mandated delivery time transparency empowering manufacturers to provide accurate arrival estimates, allowing consumers to streamline their operations and reduce downtime. Moreover, the act standardized pricing structure introduced for freight charges, payment, and price terms fostering a fair and collaborative environment where manufacturers and logistics providers work together to optimize costs. Stricter regulations on the quality and quantity of goods during transit were enacted with the aim of elevating the commitment to excellence. Consequently, ensuring manufacturers maintained product integrity which in turn enhanced consumer satisfaction and trust. The mandatory insurance coverage underscored accountability and security alleviating financial risks for both parties and paving the way for stronger, more reliable partnerships between man- ufacturers and consumers in the ever-changing logistics landscape. The workflow below shows how using a USC would facilitate efficient contract renegotiation as a result of the changes following the new regulation. 4.2.1 Workflow: Use case Execution 1. Initiation of renegotiation process: Company A learns about the new regulations and realizes they cannot meet the original delivery schedule. They contact institution B and propose a revised delivery schedule that considers the time for additional checks and verification needed to satisfy the new regu- lations. 2. Proposal Review: Institution B is alerted of the proposed changes by com- pany A, and they review them. 3. Accept Changes: Once the proposal is reviewed, institution B approves the updated delivery schedule. 4. Update Contract: The USC is ultimately updated with the new delivery schedule. 24 4. UseCase and Implementation 5. Enforcement of the Revised Contract: The updated USC will automati- cally enforce the new delivery time. This use case shows that USCs allow the logistics industry to adapt and renegotiate contracts seamlessly despite the market’s volatility. 4.3 System description The POC defines a contract between a logistics company and a customer. Those will be the two participants of the network. The contract stipulates all the terms agreed on after the first negotiation has taken place. We assume that the two parties met and agreed on specific terms before uploading the contract to the Ethereum Network. The following are the functional requirements of the POC implementation: 1. Contract Creation: The system should enable the initial formulation of a digital agreement on Ethereum network. This involves writing and encoding the terms, conditions, and rules of the contract into self-executing code. 2. Contract Upgreadability: This feature is crucial in addressing changes in the market, regulations or unforeseen circumstances that necessitate a renego- tiation. Hence, it should allow modifying an existing contract without creating a new one. 3. Contract Deployment: The system should initialize and activate a self- executing digital contract on Ethereum network. Once activated, the smart contract runs autonomously, carrying out predetermined operations. 4. Contract Execution: The system should automatically enable the fulfill- ment of predefined terms and conditions encoded in the smart contract. In the event that specific criteria are met, the smart contract independently trig- gers actions, transfers assets, or executes agreements without the need for intermediaries. 4.4 Building the Upgradeable smart Contract The contract will be built using Solidity, a statically typed language. When writ- ing this thesis, the latest version was v0.8.20. Solidity offers features allowing developers to create efficient, complex, secure smart contracts. 4.4.1 State Variables We established the state variables before creating any functions within the smart contract. These variables are stored persistently in the contract’s storage after the contract has been deployed. The first contract LogisticsV1 stores the variables of the agreed-upon terms after negotiation. The contract terms include delivery time, price of the goods, payment terms, quantity of the goods and insurance cost. The second contract LogisticsV2 will be a replica of version one except for the newly modified values. 25 4. UseCase and Implementation 4.4.2 Functions The functions used in the contracts are for setting values to the variables based on our assumption in section 4.3. They include: • setDeliveryTime(): This function is critical for scheduling the delivery pro- cess. It allows the contract to store the expected delivery date of the goods. • setPrice(): This function is designed to facilitate the financial aspect of the goods transaction. It sets the price for the goods in the contract • setPaymentTerms(): This function aids in defining the terms of payment for the goods. This component ensures a mutual understanding between parties on the payment conditions, be it "60 days after delivery", "payment due upon receipt", or any other agreed terms. • setQuantity(): This function provides a way to stipulate the quantity of the goods in the contract. This documents the agreed quantity of goods involved in the transaction, adding to the clarity of the contractual agreement. • setInsuranceCost(): This function is implemented to assign the insurance cost for the goods in transit. This feature safeguards the information about the cost of insuring the goods during transportation and is an important part of the financial aspects of the contract. These functions all work together to define the main transactional terms for the Logistics smart contract. 4.4.3 Events Events are major occurrences or triggers that are tracked and recorded on a blockchain network. When particular criteria are satisfied, these events defined within the smart contract code are carried out automatically. Events operate as a channel for infor- mation sharing and alerting third parties or applications to changes or actions inside the smart contract. Smart contracts ensure transparency, auditability, and accurate record-keeping by capturing and preserving these occurrences on the blockchain. This increases confidence and reliability in various decentralised applications and business processes. In our POC, one of the events is LogContractData. It emits all the state variable values and provides a mechanism to log the changes to contract details when they occur. 4.4.4 Upgradeability Mechanism This section uses OpenZeppelin’s proxies and hardhat plugins to achieve off-chain upgradeability. Offchain upgradeability implies that most upgrade process functions are not run on the blockchain. These plugins were made available via node package manager (npm), a Javascript package manager. They are intended to improve the productivity and efficacy of Ethereum contract creators. The plugins enabled the execution of Solidity, the core programming language for Ethereum smart contracts on the local machine and provided instant access to fault diagnostics. This sped 26 4. UseCase and Implementation up the development process and added more flexibility while minimizing the limits inherent in the contract development lifecycle. When performing the upgrades, some essential activities that were performed off-chain include the following: 1. Script Preparation: The script or code describing the upgrade is written and prepared off-chain. This involves creating new contract code as well as modifying old code. Later in the section, we will look at some important functions used during this process. 2. Testing: The upgrading script is carefully verified off-chain before any mod- ifications are deployed. Unit testing, integration testing, and, in some cir- cumstances, simulated deployments on testnets, which emulate the blockchain environment but are not part of the actual blockchain, are all part of this. We chose the Transparent Upgreadable Proxy, which utilizes two key contracts, the Proxy Contract and the Logic (or Implementation) contract. The proxy contract delegates calls to the desired implementation contract, making it appear that the implementation code was executed in the context of the Proxy contract. The two main functions needed to achieve this upgrade come from the OpenZeppelin hardhat upgrades. They include the following shown below : 4.4.4.1 deployProxy() The deployProxy() function is essential in deploying upgradeable smart contracts. It is part of the functions provided by OpenZeppelin libraries that simplify the cre- ation and management of upgradable smart contracts in the Ethereum ecosystem. This function automates deploying new smart contracts by creating an instance of the contract and then integrating the proxy address with the respective implemen- tation contract. The function takes the parameters shown in listing 4.1 1 async function deployProxy( 2 Contract: ethers.ContractFactory , 3 args: unknown [] = [], 4 opts?: { 5 initializer ?: string | false , 6 unsafeAllow ?: ValidationError [], 7 constructorArgs ?: unknown[], 8 timeout ?: number , 9 pollingInterval ?: number , 10 redeployImplementation ?: 'always ' | 'never ' | 'onchange ', 11 kind?: 'uups' | 'transparent ', 12 usePlatformDeploy ?: boolean , 13 }, 14 ): Promise Listing 4.1: Parameters that the deployProxy function takes [23]. Here is a breakdown of the arguments shown in 4.1: 1. contract: This parameter specifies the factory instance for deploying the contract. It uses ethers.ContractFactory to create new contract instances. The contract factory is a way to create these instances in Ether.js. 27 4. UseCase and Implementation 2. args: This array takes arguments that will be passed to the initialize function of the contract. In upgradable contracts, the initializer is used instead of a constructor. 3. opts(options object): This is an optional parameter where you may provide different configurations such as the type of proxy you may want to use or how long you have to wait for a transaction and many more as shown in listing 4.1. When called, the function creates a Transparent or UUPS proxy contract and re- turns a contract instance with the proxy address and implementation interface. If arguments were passed to the array, a function named initialize()function is run with the provided arguments. However, when the function is called multiple times, it will launch several proxy contracts that will all be linked to a single instance of the implementation contract [23]. 4.4.4.2 upgradeProxy() To utilize a newly created contract and make the system start referencing it, we call the upgradeProxy() function. This function upgrades a UUPS or Transparent proxy to a new implementation contract at a given address. It also provides a contract instance that combines the proxy address with the recent implementation interface [23]. As parameters, it takes similar arguments as the deployProxy() function. The difference is an extra proxy parameter that takes the proxy address, and the opts parameter takes different configuration options. The structure of the function is shown in the code snippet in listing 4.2 1 async function upgradeProxy( 2 proxy: string | ethers.Contract , 3 Contract: ethers.ContractFactory , 4 opts?: { 5 call?: string | { fn: string; args?: unknown [] }, 6 unsafeAllow ?: ValidationError [], 7 unsafeAllowRenames ?: boolean , 8 unsafeSkipStorageCheck ?: boolean , 9 constructorArgs ?: unknown[], 10 timeout ?: number , 11 pollingInterval ?: number , 12 redeployImplementation ?: 'always ' | 'never ' | 'onchange ', 13 kind?: 'uups' | 'transparent ', 14 }, 15 ): Promise Listing 4.2: Parameters that the upgradeProxy function takes [23]. 4.4.4.3 The bigger picture: Upgradeable Contract lifecycle These functions are used in tandem by running the deploy proxy function first. The addresses returned by running the function are the logistics (proxy) address and ImplementationAddress as shown in listing 4.3 28 4. UseCase and Implementation 1 >npm run deploy 2 3 > Compiled 6 Solidity files successfully 4 > Deploying Logistics ... 5 > 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 logistics(proxy) address 6 > 0x5FbDB2315678afecb367f032d93F642f64180aa3 ImplementationAddress Listing 4.3: Output after running deployProxy. Over time, contractual terms may be added or modified. If traditional contracts are in use, this would require full redeployment and state migration, which may be cumbersome. However, since we are using upgradeable smart contracts, it allows continuous development. This is done by calling the upgrade proxy function, which deploys new versions of contract logic without disrupting the ongoing operations. The function returns the new implementation address and proxy address as shown in listing 4.4 1 > npm run upgrade 2 > 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 original Logistics( proxy) address 3 > upgrade to LogisticsV2 ... 4 > 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 LogisticsV2 address( should be the same as the proxy address) 5 > 0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9 ImplementationAddress Listing 4.4: Output after running upgradeProxy. In summary, this two-step process allows for flexible contract development, enhanc- ing smart contracts practical usability in real-world applications. 4.5 Evaluation This section assesses the efficiency of the Proof of Concept (POC) proposed in chapter 3. To begin with, we go over the general scripts that we will utilize to perform our evaluation after which we go into detail on how each contractual term will be updated based on the resulting negotiation sessions between the two parties involved. For more details on the source code for some of the contracts mentioned in this section, the reader is directed to the appendices where all the contracts are located. 4.5.1 Descriptive Evaluation The evaluation of negotiation using USC was held using scenarios based on the terms mentioned in section 4.1. We utilize Hardhats’ local network as this platform gives us a local Ethereum network made explicitly for development. It provides us with features such as debugging and testing contracts which we employed to ascertain the upgrades were executed as planned. We crafted scripts to streamline the testing process to facilitate deployment and upgrades shown in listing 4.5. The contents 29 4. UseCase and Implementation of the scripts are located in the appendix; we will explain some of them in later sections. 1 "scripts": { 2 "call -contract": "npx hardhat run --network localhost scripts/ call -contract.js", 3 "deploy": "npx hardhat run --network localhost scripts/deploy. js", 4 "upgrade": "npx hardhat run --network localhost scripts/upgrade .js", 5 } Listing 4.5: Scripts to run deployement and upgrades. The most fundamental action is deploying the original contract after the initial ne- gotiation between the two parties. Figure 4.6 shows the smart contract deployment on the Ethereum local network using Hardhat. 1 >npm run deploy 2 3 > Compiled 6 Solidity files successfully 4 > Deploying Logistics ... 5 > 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 logistics(proxy) address 6 > 0x5FbDB2315678afecb367f032d93F642f64180aa3 ImplementationAddress Listing 4.6: Upgradeable Smart Contract deployment. We obtained two addresses during the deployment, the proxy address and the Implementation address. The proxy address should stay the same whenever ne- gotiation needs to occur however, the implementation address will always change after the contract is updated with the new negotiation values. Using the scripts we created earlier, we view the values of the original contract by running line 1 shown in listing 4.7. The output shows us the version of the current contract in line 12 before any renegotiation occurs. 1 > npx hardhat run --network localhost scripts/call -contract.js 2 3 BigNumber { _hex: '0x64', _isBigNumber: true } 4 Contract Data: { 5 deliveryTime: '2023 -06 -30', 6 charges: '100', 7 price: '500', 8 paymentTerms: '30 Days After Delivery ', 9 quantity: '200', 10 insuranceCost: '50' 11 } 12 Version number: 1.0.0 Listing 4.7: Values stored in the original contract. 4.5.2 Negotiable terms analysis In this section, we look at scenarios which would necessitate renegotiation and how the POC addresses these changes. Our main thesis contribution was to show how 30 4. UseCase and Implementation these scenarios could be handled using USC even if smart contracts were meant to be immutable. 4.5.2.1 Delivery Time This is the recurring monthly time that goods need to be delivered, agreed upon by the two parties. The following scenarios could potentially lead to renegotiation: • Party A asses their production capabilities and stock availability and realise they cannot meet the regular delivery time. • During certain months, unforeseen circumstances such as public holidays may cause the standard delivery time to change, and a potential discussion about alternative dates will be crucial. We first create a new contract named LogisticsV2 with a new value stored for the delivery variable. Below in listing 4.8, we show a snippet of the new contract with the delivery time changed. 1 contract LogisticsV2 { 2 string private _deliveryTime; 3 uint256 private _charges; 4 uint256 private _price; 5 string private _paymentTerms; 6 uint256 private _quantity; 7 uint256 private _insuranceCost; 8 9 // Define an event 10 event LogContractData( 11 string _deliveryTime , 12 uint256 _charges , 13 uint256 _price , 14 string _paymentTerms , 15 uint256 _quantity , 16 uint256 _insuranceCost 17 ); 18 19 function store () public { 20 setDeliveryTime (); 21 setCharges (); 22 setPrice (); 23 setPaymentTerms (); 24 setQuantity (); 25 setInsuranceCost (); 26 27 emit LogContractData( 28 deliveryTime , 29 charges , 30 price , 31 paymentTerms , 32 quantity , 33 insuranceCost 34 ); 35 } 36 31 4. UseCase and Implementation 37 function setDeliveryTime () public { 38 _deliveryTime = "2023 -07 -01"; 39 } Listing 4.8: Logistics contract version 2. We then ran the upgrade script to move from version one of the logistics contract to version two. While still using the same proxy address, we viewed the new value uploaded to the chain after the first renegotiation. The following code in listing 4.9 shows the code used to interact with LogisticsV2. 1 const { BigNumber } = require("ethers"); 2 const { ethers } = require("hardhat"); 3 async function main() { 4 // Retrieve the contract instance 5 const MyContract = await ethers.getContractFactory("LogisticsV2 "); 6 const myContract = await MyContract.attach("0 x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"); 7 8 // After Upgrade 9 const upgradedData = await myContract.retrieve (); 10 const upgradedContractData = { 11 deliveryTime: upgradedData [0], 12 charges: upgradedData [1]. toString (), // converting BigNumber to string 13 price: upgradedData [2]. toString (), 14 paymentTerms: upgradedData [3], 15 quantity: upgradedData [4]. toString (), 16 insuranceCost: upgradedData [5]. toString () 17 } 18 const changeDelivery = await myContract.setDeliveryTime (); 19 console.log(changeDelivery); 20 const version = await myContract.version (); 21 const test2 = await myContract.retrieve (); 22 console.log(test2.toString ()); 23 console.log("Contract Data:", upgradedContractData); 24 console.log("Version number: ",version); 25 } 26 27 main() 28 .then (() => process.exit (0)) 29 .catch ((error) => { 30 console.error(error); 31 process.exit (1); 32 }); Listing 4.9: Test to view values of the LogisticsV2 contract. We then proceeded to call the script above. Renegotiation is assumed to have occurred, and the parties involved wish to change the delivery terms. We assumed the delivery time was revised by utilising lines 18-19 in listing 4.9 for testing purposes. The result of this is shown in listing 4.10. 32 4. UseCase and Implementation 1 > npx hardhat run --network localhost scripts/call -contract.js 2 Contract Data: { 3 deliveryTime: '2023 -07 -01', 4 charges: '100', 5 price: '500', 6 paymentTerms: '30 Days After Delivery ', 7 quantity: '200', 8 insuranceCost: '50' 9 } 10 Version number: 2.0.0 Listing 4.10: Values stored in the version2 contract. 4.5.2.2 Freight Charges and Price In this scenario, we tested that it is possible to change two negotiable terms. Here we look at the freight charges, which are the fees agreed on by the two parties for each cargo based on weight and distance and the per-unit pricing for each book. The following scenarios are what we took into account when testing the renegotiation process: • Due to regular bulk shipments, party B renegotiates for reduced freight charges. • Due to different transport modes available, party B may opt for a cheaper one leading to renegotiation. • Changes in raw materials or other external factors may necessitate renegotiat- ing new terms. We adjust the charges and price in the new version of the contract, which is LogisticsV3. The listing 4.11 shows the snippet of the change that the new contract undergoes. 1 contract LogisticsV3 { 2 3 function setCharges () public { 4 _charges = 1,000; 5 } 6 7 function setPrice () public { 8 _price = 3,000; 9 } Listing 4.11: Logistics contract version 3. As mentioned earlier, the process of upgrading stays the same by running the up- grade script. We end up moving from version 2 of the contract to version 3. The code in listing 4.12 shows a snippet of what functions will be used to change the aforementioned terms. 1 const { BigNumber } = require("ethers"); 2 const { ethers } = require("hardhat"); 3 async function main() { 4 // Retrieve the contract instance 5 const MyContract = await ethers.getContractFactory("LogisticsV3 "); 33 4. UseCase and Implementation 6 const myContract = await MyContract.attach("0 x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"); 7 8 // After Upgrade 9 const upgradedData = await myContract.retrieve (); 10 const upgradedContractData = { 11 deliveryTime: upgradedData [0], 12 charges: upgradedData [1]. toString (), // converting BigNumber to string 13 price: upgradedData [2]. toString (), 14 paymentTerms: upgradedData [3], 15 quantity: upgradedData [4]. toString (), 16 insuranceCost: upgradedData [5]. toString () 17 } 18 const changeCharges = await myContract.setCharges (); 19 const changePrice = await myContract.setPrice (); 20 console.log(changeCharges); 21 console.log(changePrice); 22 const version = await myContract.version (); 23 const test2 = await myContract.retrieve (); 24 console.log(test2.toString ()); 25 console.log("Contract Data:", upgradedContractData); 26 console.log("Version number: ",version); 27 } 28 29 main() 30 .then (() => process.exit (0)) 31 .catch ((error) => { 32 console.error(error); 33 process.exit (1); 34 }); Listing 4.12: Test to view values of the LogisticsV3 contract. When the script in listing 4.12 is run, we look at the newly revised freight charges and price. The results are in listing 4.13 1 > npx hardhat run --network localhost scripts/call -contract.js 2 Contract Data: { 3 deliveryTime: '2023 -07 -01', 4 charges: '1,000', 5 price: '3,000', 6 paymentTerms: '30 Days After Delivery ', 7 quantity: '200', 8 insuranceCost: '50' 9 } 10 Version number: 3.0.0 Listing 4.13: Values stored in the version3 contract. 4.5.2.3 Refunds rate In this scenario, we tested adding new terms that were never considered during the creation of the original contract. We added a new term in our solidity contract known as returnsAndRefunds. This clause was proposed by party B as they realized 34 4. UseCase and Implementation there might be a situation in which they received damaged goods and had no clause to address it in the original contract. The two parties meet and renegotiate a refund rate in case of damaged goods, and the new clause is added to the contract after the agreement. One rule to follow when adding a new variable to the upgradeable smart contract is that you cannot change the order in which the variables are declared nor their type. 1 contract LogisticsV3 { 2 string private _deliveryTime; 3 uint256 private _charges; 4 uint256 private _price; 5 string private _paymentTerms; 6 uint256 private _quantity; 7 uint256 private _insuranceCost; 8 uint256 private _returnsAndRefunds; 9 } Listing 4.14: State variables of the contract. In our initial contract shown in listing 4.14, we cannot change the order in which the state variables were initially declared, the data type of the variables and lastly, if a new variable is added, for example, line 8 in listing 4.14 it should be at the bottom. This is because it may lead to storage collision since the proxy contract knows the state of the application when the first version was deployed. We added the refunds term in our contract’s new version, LogisticsV4. The upgrade process remains the same as mentioned in earlier scenarios. We then view our new changes shown in listing 4.15 1 > npx hardhat run --network localhost scripts/call -contract.js 2 Contract Data: { 3 deliveryTime: '2023 -07 -01', 4 charges: '1,000', 5 price: '3,000', 6 paymentTerms: '30 Days After Delivery ', 7 quantity: '200', 8 insuranceCost: '50', 9 returnsAndRefunds: 45; 10 } 11 Version number: 4.0.0 Listing 4.15: Values stored in the version4 contract. We discovered the following benefits of using USC through our implementation and evaluation. • Longevity: Negotiations can stretch over long periods, and using USC allows the underlying logic to be continuously updated. This will allow the contract to adapt to changing external environments, thus ensuring the POC remains relevant for longer. • Flexibility: The capacity to incorporate new capabilities or repair defects after deployment is the significant advantage of upgradable smart contracts. 35 4. UseCase and Implementation This is especially important in negotiating procedures, which frequently need repeated modifications. However, it must be noted that USC presents certain challenges. Some include: • Complexity: Using proxy patterns adds a layer of complexity, leading to increased chances of vulnerabilities occurring. • Unintended Consequences: Improper implementation of the pattern can cause data loss or even unintended behavioural changes. In our use case, applying USC to negotiation helped as it allowed us to have dy- namic terms that allowed parties to introduce new terms without restarting the whole negotiation process. It also makes it easier to incorporate newer blockchain technologies. However, the complexity of designing them can also hinder their adop- tion. It is also somewhat of an easier process compared to using regular contracts. This is the case because the whole application would have to be halted for data and contract migrations, which can result in long downtimes and data loss during migration. While in USC, as long as the initial upgrade logic was correctly defined, all that is needed is the newly drafted smart contract. The proxy references this contract as the new implementation, and we avoid data migration. Thus enabling the continuity of the application and avoiding pitfalls that may come with activities such as data migration. 36 5 Related Work This chapter presents a comparative analysis of our thesis with related research pa- pers in the field. The chapter aims to provide a comprehensive understanding of the current state of research on smart contract negotiation and highlight the distinctive contributions and novelty of our work. With the help of upgradeable smart con- tracts, our thesis aims to overcome traditional smart contracts’ drawbacks in terms of adaptability and upgradeability after deployment. Our thesis is contrasted with relevant research articles that also investigate the application of smart contracts in negotiation scenarios to provide a thorough overview of the research landscape. The chosen research papers offer valuable insights and findings in this field, presenting a sublime opportunity for comparative analysis. This chapter will critically examine and compare both works’ methodologies, results, and contributions. The intention is to draw attention to each study’s specific findings, contributions, limitations and unique aspects. We aim to contribute to the existing body of knowledge and of- fer insights into the developments and challenges within the field of smart contract negotiation using upgradeable smart contracts by comparing and contrasting our thesis with the related research papers. 5.1 Related work review 5.1.1 Taxiarchis et al [24] This paper examines the rising pervasiveness of blockchain technology, which is pre- dominantly propelled by the success of Bitcoin. It gives a high-level overview of blockchain as a decentralised peer-to-peer network that maintains a record of trans- actions that have been digitally signed. The study looks at how blockchain technol- ogy has developed beyond cryptocurrencies, showing how it supports self-executing programmes known as smart contracts on platforms like Ethereum and Hyperledger Fabric. Additionally, it highlights the development of private blockchains as opposed to early public blockchains where participants are authorised. The authors address the issues of data privacy and ownership while also discussing possible blockchain uses in a number of industries. They recommend a blockchain that ensures public verifiability while protecting individual participant privacy as a trade-off between privacy and transparency. Furthermore, the research also highlights the limitations of smart contracts in their 37 5. Related Work current form. Smart contracts offer immutability, but due to the fact that they cannot be easily changed once they have been deployed, they are less adaptable than traditional paper-based contracts. In volatile environments, where terms may need to be modified often, this lack of adaptability is costly. The authors propose mechanisms that would increase the adaptability and application of smart contracts in dynamic situations by enabling parties to propose and agree on new conditions and terms within them, enhancing their versatility. This paper aimed to thoroughly compare Ethereum (a public blockchain) and Hy- perledger Fabric (a private blockchain), emphasising their architectural similarities and differences in data ownership. The second goal of the thesis was to create a system for two parties to negotiate the terms of smart contracts. Building on the prior comparison, it investigated the feasibility of implementing this process in both kinds of blockchain networks. To better demonstrate the comparative analysis, a role-based access control (RBAC) paradigm was developed and put into action in a real-world use case application. Additionally, the authors designed a library that bilaterally negotiates contracts. Overall, this study provides insightful information about the benefits, drawbacks, and potential applications of blockchain technology. 5.1.2 Krohling et al [25] The study examines the possibility for prosumers to efficiently trade utility sur- pluses, such as heating, cooling, and electric power, inside Eco-Industrial Parks (EIPs) Peer-to-Peer (P2P) Markets. The researchers suggest a P2P Market pro- totype that automates the negotiation and enforcement of exchange terms using smart contracts, blockchain transactions, and Internet of Things (IoT) technologies. The P2P Market design prototype supports socially acceptable behaviour across prosumer enterprises, overcoming the inherent selfishness of each participant by col- laboratively co-generating and trading utilities and industrial services. During the simulation of the Eco-Industrial Park, each prosumer in the Eco-Industrial Park is represented by a negotiating agent [26], which chooses whether to negotiate with other prosumers or with more established service providers, such as the primary electric or gas providers. Based on their personal preferences and the contextual facts at their disposal, the negotiating agents make informed choices. Reinforcement Learning techniques are employed to develop policies that guide the negotiation pro- cess, taking into account the policies of other prosumers and the prevailing context [27]. The simulation results demonstrate the potential economic benefits of the P2P Market prototype. Prosumers can optimize their profits by directly exchanging utilities, eliminating intermediaries, reducing costs, and promoting a win-win col- laboration strategy [28]. The research highlights the transformative power of P2P Markets in driving economic growth, reducing emissions, and promoting sustainable practices within Eco-Industrial Parks. The study contributes to the body of knowledge on P2P Markets-related topics like industrial symbiosis, IoT, automated negotiation, blockchain, and smart contracts. It lays out the potential financial gains and environmental benefits that prosumers in Eco-Industrial Parks might obtain through cooperative utility surplus trading. 38 5. Related Work The P2P Market prototype demonstrates the opportunity and value of this method in encouraging effective and sustainable resource utilisation by allowing prosumers to achieve larger revenues. In conclusion, the study underscores the significance of blockchain, smart contracts, and IoT technologies in establishing efficient and secure P2P Markets for trading utility surpluses. The proposed prototype demonstrates the feasibility and benefits of implementing such a system in Eco-Industrial Parks, fostering collaboration, economic growth, and sustainable resource utilization among participating prosumer companies. 5.2 Comparative Analysis 5.2.1 Methodologies and Approaches Taxiarchis et al [24] employed a methodology to assess Design Science and Infor- mation System research that is predicated on the conceptual framework developed by Hevner et al. [29]. The framework places a strong emphasis on important qual- ities including usability, completeness, correctness, consistency, performance and reliability. The authors decided to use the descriptive assessment approach in keep- ing with the goals of the thesis and the distinctiveness of blockchain technology. The two essential parts of this approach are scenario construction and an informed argument. The well-informed argument makes a convincing case for the usefulness of the deployed artefact by referencing pertinent research. In order to demonstrate the viability and efficacy of the solution, comprehensive scenarios must be created. Moreover, a targeted performance assessment was carried out, with a particular focus on the Ethereum implementation, to examine the gas consumption of the deployment and use of smart contracts in real-time scenarios. This methodology allows the study to offer an in-depth assessment of the artifact’s utility, viability, and performance within the blockchain technology framework. Krohling et al [25]: The key points of the methodology and approach are high- lighted as follows. Firstly, the authors propose a mechanism design that encourages prosumers to participate in trading surpluses by creating a P2P Market prototype. This design allows for the synergistic co-generation and trading of utilities and in- dustrial services among prosumer companies, enabling them to reach significant economic benefits and reduce emissions. Secondly, the authors utilize Blockchain transactions and Smart Contracts, combined with IoT technologies such as smart meters, to ensure the secure and automatic enforcement of agreed-upon terms of exchange. This approach eliminates the need for intermediaries and reduces trans- action costs, fostering socially desirable behavior despite the inherent selfish na- ture of individual prosumer companies. Thirdly, the methodology incorporates a simulation-based evaluation, where negotiation agents representing prosumers make decisions based on private preferences and contextual information. Reinforcement Learning is employed to develop negotiation policies, considering other peer poli- cies and models. The simulation results demonstrate the effectiveness of automated negotiations, enabling prosumers to achieve higher profits in the P2P Market from trading utility surpluses. Overall, this research provides a robust methodology and 39 5. Related Work approach for the design and implementation of a P2P Market within an EIP, high- lighting the transformative potential of such a system in driving economic growth, reducing emissions, and promoting sustainable practices. 5.2.2 Results and Findings Taxiarchis et al [24]: The findings of this study demonstrate how blockchain technol- ogy may affect business transactions. It has been determined through comparative analysis that the blockchain may be used successfully in the dynamic environment of contemporary company. Before implementing blockchain adoption, it is essential to have a deep grasp of the unique business requirements. The study also shows that a bi-directional contract terms negotiation system may be implemented within the blockchain architecture. Notably, the blockchain has built-in mechanisms for guaranteeing data ownership, especially in the context of private blockchain ecosys- tems. The study also emphasises how crucial it is to create scalable solutions for the Ethereum blockchain because each computation uses ether, which must be recovered by miners. These findings highlight the necessity for thorough planning and optimi- sation in order to properly capitalise on the potential advantages and considerations associated with blockchain adoption in corporate environments. Krohling et al [25]: The findings from the simulation conducted in this study pro- vide valuable insights into the potential impact of automated negotiations within the proposed P2P Market. By enabling prosumers to directly exchange utility surpluses with one another, the need for intermediaries is eliminated. This direct peer-to-peer exchange not only streamlines the trading process but also reduces transaction costs, making it economically advantageous for participating prosumers. By optimizing their profits through direct utility exchanges, prosumers can capitalize on their sur- plus resources and enhance their financial performance. Moreover, the automated negotiation mechanism within the P2P Market promotes a win-win collaboration strategy among prosumers. The system allows prosumers to leverage their private preferences and contextual information to make informed decisions on whether to engage in peer-to-peer negotiations or conduct transactions with traditional service providers. This flexibility empowers prosumers to maximize their benefits while considering the larger context of the Eco-Industrial Park. More importantly, pre- liminary results reveal that trust issues in the P2P Market of the EIP are resolved by the Blockchain approach presented in this work. In this sense, Smart Contracts assure prosumers, represented by negotiation agents, that every agreement reached during a negotiation is to be executed. Such a trustworthy mechanism rids pro- sumers of the inconvenience of unveiling their private preferences or needs to a third party or general coordinator of the P2P Market [25] . 5.3 Evaluation of Contributions and Novelty The evaluated studies set a good precedence for our research. However, they all address different ways of going about the negotiation process in smart contracts. One of the critical concepts that Taxiarchis et al [24] use is parameterization by 40 5. Related Work developing a library to enforce negotiation. It can be a bottleneck when new terms or functions need to be added or updated in the smart contract. The rationale behind this is that you cannot add new logic nor can you add storage of new vari- ables; essentially, all you can do is update parameter values. Conversely, our choice to use upgradeable smart contracts to facilitate negotiation offers several critical advantages that are not factored in when developing a library. These include: • Flexibility and adaptability: Upgradeable smart contracts allow for modifica- tions and updates without requiring complete redeployment. This flexibility enables contract negotiation to evolve and adapt to changing business require- ments, legal frameworks, or market conditions. With upgradeable contracts, parties can introduce new terms, adjust existing clauses, or add functionalities without disrupting the underlying contract infrastructure. • Enhanced contract lifecycle management: Upgradeable smart contracts pro- vide a streamlined approach to managing the lifecycle of contracts. Instead of relying on external libraries or separate contract instances, upgradeable con- tracts allow for seamless updates and maintenance within a single contract address. This simplifies the management process, reduces fragmentation, and improves version control. • Future-proofing and scalability: Upgradeable smart contracts provide a future- proof solution for negotiation by allowing for seamless updates and enhance- ments. As the blockchain technology and ecosystem evolve, upgradeable con- tracts can accommodate new features, regulatory changes, or business require- ments, ensuring long-term viability and scalability of the negotiation process. However, it is crucial to acknowledge that the decision between utilizing upgradeable smart contracts or a library is contingent upon individual project needs, technical limitations, and the assessment of trade-offs. This evaluation must be conducted on a case-by-case basis, taking into account specific project requirements and consider- ations. A master’s project in development by Evgeny Groshev [30] seeks to develop a frame- work that captures generic contract terms and others unique to specific domains and evaluates whether it will be feasible. Additionally, his work aims to establish the feasibility of the negotiation being either on-chain (placing the contracts on the plat- form he chooses for hosting the contracts) or off-chain (being in a separate system) in the blockchain system. In contrast, my work aims to utilize built-in mechanisms popularized by ZeppelinOS and AragonOS to facilitate changes from the process of negotiations in a smart contract that enable negotiation by exploiting upgradeable smart contracts. 41 5. Related Work 42 6 Conclusion This chapter concludes the thesis by discussing our findings of using upgradable contracts to facilitate negotiation. 6.1 Discussion In this thesis, we first looked at what upgradeable smart contracts are in order to understand how they are used in the context of developing distributed applica- tions using Ethereum. Smart contracts have the capacity to automate processes and promote trust. However, their static nature, once deployed, poses a limitation. Specifically, we looked at the different upgrade mechanisms available to achieve "mu- tability". We noted that the proxy pattern was the most used as upgradeability is still a new field. However, while trying to chase the concept of mutability, we lose the guarantees that regular smart contracts give us. Their immutability provides predictability in the contract’s behaviour, which gives users confidence that the contract will remain the same during execution. This is important for certain types of agreements. Regular smart contracts are also more straightforward in design, which makes them easier to understand. They provide solid arguments for their usage; however, they are very limited regarding flexibility. Our research shows that upgradeable smart contracts address the limitation of flexibility. They allow the parties involved to update and introduce new features to the contract but simultaneously lose the guarantees regular smart contracts give users. From the points previously stated, we can see that regular contracts offer predictability but at the cost of being unable to introduce contractual changes from a behavioural view post-deployment. In contrast, upgradeable smart contracts provide flexibility but at the cost of raising centralization and the risk of unforeseen changes. In our thesis, we use case selection of the logistics domain was motivated by it being a field where a lot of renegotiation occurs. This would allow us to show the workings of USCs efficiently since it would allow us to demonstrate the behavioural changes in the smart contract logic code when renegotiation occurs. From our POC implemen- tation, we found out that it has the possibility of addressing the lack of flexibility offered by paper-based contracts during negotiation. From analysing previous stud- ies, we found that using upgradeable smart contracts can be a better alternative in addressing clauses that were never in the initial contract. This is because it has low 43 6. Conclusion overheads when performing changes compared to techniques proposed by Taxiarchis et al [24]. One of the shortcomings of this use case is that it was not really efficient to demonstrate the power of upgradeable smart contracts and showcase their true potential. The theory that upgradeable smart contracts can be utilized to achieve negotiation has been answered by the research questions in this thesis and is further substan- tiated by implementing our POC. The reader can find a summary of our research questions below: • Question 1: What are the different mechanisms used in upgradeable smart contracts? • Question 2: Can a smart contract be designed using an upgrade mechanism that facilitates negotiation? • Question 3: What are the implications of using upgradeable smart contracts? Research Question 1 is answered in Section 2.7 of Chapter 2 which presents what upgradable contracts are and what different mechanisms exist to achieve upgrade- ability. Research Question 2 was answered in Chapter 3 and 4, which presents the architecture and use case implementation and evaluation respectively. Similarly, research Question 3 has also been answered in Chapter 4, section 4.5. To sum it all up the choice between the two approaches mentioned previously de- pends on the project’s needs and whether the parties involved are okay with the advantages and disadvantages the chosen type offers. Some applications seek trust and immutability, while for others, the ability to evolve over time is essential. 44 Bibliography [1] S. Nakamoto and A. Bitcoin, “A peer-to-peer electronic cash system,” Bitcoin.– URL: https://bitcoin. org/bitcoin. pdf, vol. 4, p. 2, 2008. [2] J. Brito and A. Castillo, Bitcoin: A primer for policymakers. Mercatus Center at George Mason University, 2013. [3] N. Szabo, “Formalizing and securing relationships on public networks,” First Monday, vol. 2, 1997. doi: 10.5210/fm.v2i9.548. [Online]. Available: https: //firstmonday.org/ojs/index.php/fm/article/view/548. [4] J. M. Sklaroff, “Smart contracts and the cost of inflexibility,” U. Pa. L. Rev., vol. 166, p. 263, 2017. [5] C. Dannen, Introducing Ethereum and solidity. Springer, 2017, vol. 1. [6] Ethereum.org, Upgrading smart contracts, https : / / ethereum . org / en / developers/docs/smart-contracts/upgrading/. [7] Ethereum.org, Solidity, https://docs.soliditylang.org/en/v0.8.17/. [8] F. Casino, T. K. Dasaklis, and C. Patsakis, “A systematic literature review of blockchain-based applications: Current status, classification and open issues,” Telematics and Informatics, vol. 36, pp. 55–81, 2019, issn: 0736-5853. doi: https://doi.org/10.1016/j.tele.2018.11.006. [9] L. Foundation, Hyperledger foundation, https://www.hyperledger.org/use. [10] D. Chain, Dragon chain, https://dragonchain.com/about. [11] Z. Zheng, S. Xie, H.-N. Dai, X. Chen, and H. Wang, “Blockchain challenges and opportunities: A survey,” International Journal of Web and Grid Services, vol. 14, p. 352, Oct. 2018. doi: 10.1504/IJWGS.2018.095647. [12] Z. Zheng, S. Xie, H.-N. Dai, et al., “An overview on smart contracts: Chal- lenges, advances and platforms,” Future Generation Computer Systems, vol. 105, pp. 475–491, 2020, issn: 0167-739X. doi: https://doi.org/10.1016/j. future.2019.12.019. [13] V. Buterin et al., “A next-generation smart contract and decentralized appli- cation platform,” white paper, vol. 3, no. 37, pp. 2–1, 2014. [14] E. Hildenbrandt, M. Saxena, N. Rodrigues, et al., “Kevm: A complete formal semantics of the ethereum virtual machine,” in 2018 IEEE 31st Computer Security Foundations Symposium (CSF), 2018, pp. 204–217. doi: 10.1109/ CSF.2018.00022. [15] G. Wood et al., “Ethereum: A secure decentralized generalised transaction ledger,” Ethereum project yellow paper, vol. 151, no. 2014, pp. 1–32, 2014. [16] Ethereum.org, Erc-2535: Diamonds, multi-facet proxy, https://eips.ethereum. org/EIPS/eip-2535. 45 Bibliography [17] F. Kochan, The diamond standard (eip-2535) explained: Part 1, https:// www.quicknode.com/guides/smart-contract-development/the-diamond- standard-eip-2535-explained-part-1. [18] H. Team, Hardhat, https://hardhat.org/hardhat-runner/docs/getting- started. [19] OPENZEPPELIN, Proxy patterns, https://blog.openzeppelin.com/proxy- patterns/. [20] Coinbase, Coinbase, https://www.coinbase.com/about. [21] Ethereum.org, Ethereum foundation, https://ethereum.org/en/foundation/. [22] Moralis, What are upgradable smart contracts? full guide, https://moralis. io/what-are-upgradable-smart-contracts-full-guide/, 2021. [23] OPENZEPPELIN, Upgrade plugins, https : / / docs . openzeppelin . com / upgrades-plugins/1.x/api-hardhat-upgrades. [24] M. K. Vaios Taxiarchis, “Comparative analysis of blockchain technologies for data ownership and smart contract negotiation,” M.S. thesis, Chalmers Uni- versity, 2018. [25] D. E. Krohling, F. Mione, F. Hernández, and E. Martnez, “Automated ne- gotiation of smart contracts for utility exchanges between prosumers in eco- industrial parks,” in III Simposio Argentino de Informática Industrial e Inves- tigación Operativa (SIIIO 2020)-JAIIO 49 (Modalidad virtual), 2020. [26] K. M. Eisenhardt, “Agency theory: An assessment and review,” Academy of management review, vol. 14, no. 1, pp. 57–74, 1989. [27] R. S. Sutton and A. G. Barto, “Reinforcement learning: An introduction,” Robotica, vol. 17, no. 2, pp. 229–235, 1999. [28] Y. Liu, L. Wu, and J. Li, “Peer-to-peer (p2p) electricity trading in distribution systems of the future,” The Electricity Journal, vol. 32, no. 4, pp. 2–6, 2019, Special Issue on Strategies for a sustainable, reliable and resilient grid, issn: 1040-6190. [29] A. Hevner, A. R, S. March, et al., “Design science in information systems research,” Management Information Systems Quarterly, vol. 28, pp. 75–, Mar. 2004. [30] E. Groshev, “A framework for smart contract negotiation,” Unpublished, 2022. 46 A Appendix 1 Our POC consists of four files stored in two different directories named Contracts and Scripts. These files include: • LogisticsV1.sol • LogisticsV2.sol • Deploy.js • Upgrade.js The source code of LogisticsV1.sol is listed below: 1 // contracts/Logistics.sol 2 // SPDX -License -Identifier: MIT 3 pragma solidity ^0.8.0; 4 5 import "@openzeppelin/contracts -upgradeable/proxy/utils/ Initializable.sol"; 6 7 contract Logistics { 8 string private _deliveryTime; 9 uint256 private _charges; 10 uint256 private _price; 11 string private _paymentTerms; 12 uint256 private _quantity; 13 uint256 private _insuranceCost; 14 15 // Define an event 16 event LogContractData( 17 string _deliveryTime , 18 uint256 _charges , 19 uint256 _price , 20 string _paymentTerms , 21 uint256 _quantity , 22 uint256 _insuranceCost 23 ); 24 25 function store () public { 26 setDeliveryTime (); 27 setCharges (); 28 setPrice (); 29 setPaymentTerms (); 30 setQuantity (); I A. Appendix 1 31 setInsuranceCost (); 32 33 emit LogContractData( 34 _deliveryTime , 35 _charges , 36 _price , 37 _paymentTerms , 38 _quantity , 39 _insuranceCost 40 ); 41 } 42 43 function setDeliveryTime () public { 44 _deliveryTime = "2023 -06 -30"; 45 } 46 47 function setCharges () public virtual{ 48 _charges = 100; 49 } 50 51 function setPrice () public { 52 _price = 500; 53 } 54 55 function setPaymentTerms () public { 56 _paymentTerms = "30 Days After Delivery"; 57 } 58 59 function setQuantity () public { 60 _quantity = 200; 61 } 62 63 function setInsuranceCost () public { 64 _insuranceCost = 50; 65 } 66 67 function retrieve () public view virtual returns (string memory , uint256 , uint256 , string memory , uint256 , uint256) { 68 return (_deliveryTime , _charges , _price , _paymentTerms , _quantity , _insuranceCost); 69 } 70 71 function version () public pure virtual returns (string memory) { 72 return "1.0.0"; 73 } 74 } The source code of LogisticsV2.sol is listed below: 1 // contracts/LogisticsV2.sol 2 // SPDX -License -Identifier: MIT 3 pragma solidity ^0.8.0; 4 5 import "./ Logistics.sol"; 6 II A. Appendix 1 7 contract LogisticsV2 { 8 string private _deliveryTime; 9 uint256 private _charges; 10 uint256 private _price; 11 string private _paymentTerms; 12 uint256 private _quantity; 13 uint256 private _insuranceCost; 14 15 // Define an event 16 event LogContractData( 17 string _deliveryTime , 18 uint256 _charges , 19 uint256 _price , 20 string _paymentTerms , 21 uint256 _quantity , 22 uint256 _insuranceCost 23 ); 24 25 function store () public { 26 setDeliveryTime (); 27 setCharges (); 28 setPrice (); 29 setPaymentTerms (); 30 setQuantity (); 31 setInsuranceCost (); 32 33 emit LogContractData( 34 deliveryTime , 35 charges , 36 price , 37 paymentTerms , 38 quantity , 39 insuranceCost 40 ); 41 } 42 43 function setDeliveryTime () public { 44 _deliveryTime = "2023 -06 -30"; 45 } 46 47 function setCharges () public { 48 _charges = 88888; 49 } 50 51 function setPrice () public { 52 _price = 11111; 53 } 54 55 function setPaymentTerms () public { 56 _paymentTerms = "30 Days After Delivery"; 57 } 58 59 function setQuantity () public { 60 _quantity = 108888880; 61 } 62 III A. Appendix 1 63 function setInsuranceCost () public { 64 _insuranceCost = 2222; 65 } 66 67 function retrieve () 68 public 69 view 70 virtual 71 returns ( 72 string memory , 73 uint256 , 74 uint256 , 75 string memory , 76 uint256 , 77 uint256 78 ) 79 { 80 return ( 81 _deliveryTime , 82 _charges , 83 _price , 84 _paymentTerms , 85 _quantity , 86 _insuranceCost 87 ); 88 } 89 90 function version () public pure virtual returns (string memory) { 91 return "2.0.0"; 92 } 93 } The source code of Deploy.js is listed below: 1 // scripts/deploy.js 2 async function main() { 3 const Logistics = await ethers.getContractFactory("Logistics") 4 console.log("Deploying Logistics ...") 5 const logistics = await upgrades.deployProxy(Logistics , { initializer: 'store ' }) 6 7 console.log(logistics.address ," logistics(proxy) address") 8 console.log(await upgrades.erc1967.getImplementationAddress( logistics.address)," getImplementationAddress") 9 console.log(await upgrades.erc1967.getAdminAddress(logistics. address)," getAdminAddress") 10 } 11 12 main() 13 .then (() => process.exit (0)) 14 .catch(error => { 15 console.error(error); 16 process.exit (1); 17 }); IV A. Appendix 1 The source code of Upgrade.js is listed below: 1 // scripts/upgrade.js 2 const { ethers } = require("hardhat"); 3 4 const proxyAddress = '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 ' 5 6 async function main() { 7 console.log(proxyAddress , " original Logistics(proxy) address") 8 const LogisticsV2 = await ethers.getContractFactory("LogisticsV2" ) 9 console.log("upgrade to LogisticsV2 ...") 10 const logisticsV2 = await upgrades.upgradeProxy(proxyAddress , LogisticsV2) 11 console.log(logisticsV2.address , " LogisticsV2 address(should be the same)") 12 13 console.log(await upgrades.erc1967.getImplementationAddress( logisticsV2.address), " getImplementationAddress") 14 console.log(await upgrades.erc1967.getAdminAddress(logisticsV2. address), " getAdminAddress") 15 } 16 17 main() 18 .then (() => process.exit (0)) 19 .catch(error => { 20 console.error(error); 21 process.exit (1); 22 }); V