<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.0 20120330//EN" "JATS-archivearticle1.dtd">
<article xmlns:xlink="http://www.w3.org/1999/xlink">
  <front>
    <journal-meta />
    <article-meta>
      <title-group>
        <article-title>Towards Bridging Traditional and Smart Contracts with Datalog-based Languages</article-title>
      </title-group>
      <contrib-group>
        <contrib contrib-type="author">
          <string-name>Markus Nissl</string-name>
          <xref ref-type="aff" rid="aff0">0</xref>
        </contrib>
        <contrib contrib-type="author">
          <string-name>Emanuel Sallinger</string-name>
          <xref ref-type="aff" rid="aff0">0</xref>
          <xref ref-type="aff" rid="aff1">1</xref>
        </contrib>
        <aff id="aff0">
          <label>0</label>
          <institution>TU Wien</institution>
          ,
          <addr-line>Vienna</addr-line>
          ,
          <country country="AT">Austria</country>
        </aff>
        <aff id="aff1">
          <label>1</label>
          <institution>University of Oxford</institution>
          ,
          <addr-line>Oxford</addr-line>
          ,
          <country country="UK">UK</country>
        </aff>
      </contrib-group>
      <fpage>68</fpage>
      <lpage>82</lpage>
      <abstract>
        <p>The distinction of traditional and smart contracts has been subject for long discussions over the last years. While there is an agreement that a one-to-one mapping of the whole contract is not the desired goal, there is an understanding that traditional and smart contracts have certain properties in common. In this paper, we present our technical insights we derived with our industrial partners by discussing the importance of a rule-based language for bridging the gap between traditional and smart contracts and introduce a translation tool for logic-based Smart Contracts for supporting well-known blockchain platforms.</p>
      </abstract>
      <kwd-group>
        <kwd>eol&gt;Contracts</kwd>
        <kwd>Blockchain</kwd>
        <kwd>Datalog</kwd>
      </kwd-group>
    </article-meta>
  </front>
  <body>
    <sec id="sec-1">
      <title>1. Introduction</title>
      <p>
        Distributed ledger technology (e.g., blockchains) represents a vibrant area of new technology
spreading into diferent research domains. In particular, smart contracts, i.e. executable code on
the blockchain that facilitates the process of executing and enforcing the terms of an agreement
between (untrusted) parties, create a rich field of applications in areas such as supply chain
management [
        <xref ref-type="bibr" rid="ref1">1</xref>
        ], decentralised finance [
        <xref ref-type="bibr" rid="ref2">2</xref>
        ] or legally binding agreements [
        <xref ref-type="bibr" rid="ref3">3</xref>
        ].
      </p>
      <p>Example 1. Real Estate. Buying a property has many connected agreements such as warranty,
payment agreements or credit agreements. A legally binding agreement usually describes the
obligations of the seller, the cash flows to the seller depending on the construction process, the
warranty rights of the buyer, and many more agreements. One easily sees that smart contracts
are capable of streamlining the process of buying real estate, not only simplifying the process
but also saving money as no escrow agent or other parties are required.</p>
      <p>
        Usually, when lawyers draft legal agreements, such as Example 1, they have to consider many
diferent aspects of the agreement such as the currently valid law and the implications on the
requirements of the client. They may even have an iterative process of improving the legal text
of the contract with the client to optimally fit the clients’ goals. Using the same process for the
creation of smart contracts causes several challenges, which we list next [
        <xref ref-type="bibr" rid="ref3 ref4 ref5">4, 5, 3</xref>
        ]:
• Lawyers are usually not programmers and hence it is unlikely that the have the technical
knowledge to build smart contracts on their own. On the other hand, programmers often
do not know the exact legal considerations hidden in the contract to build a reliable smart
contract. Even if a lawyer has some coding background, there are still clients who are
not experts in coding, making an iterative process with the client impossible. Even the
creation of standard templates from domain experts of both fields for certain kinds of
agreements still do not solve the problem when an extension is required.
• Smart contracts are usually written in object-oriented programming languages such as
Solidity [
        <xref ref-type="bibr" rid="ref6">6</xref>
        ] for the Ethereum blockchain. The procedural style of these languages makes
it hard for non-experts to verify whether the legal considerations are reflected in code.
• A legal contract contains many clauses which have no direct executable action. For
example, the place of jurisdiction will not trigger any event on the blockchain, while
a required payment will initiate a transfer of the tokens from the buyer to the seller.
Depending on the use case of the contract one may want to include or exclude such
information.
      </p>
      <p>
        While some of the challenges are strategic decisions, some of the issues can be tackled by
using logic-based smart contract languages. It is our experience, that logic-based rules improve
the readability of the code for non-experts and improve the communication between diferent
stakeholders [
        <xref ref-type="bibr" rid="ref7">7</xref>
        ]. Diferent suggested solutions for logic-based languages include the use of
domain-specific languages [
        <xref ref-type="bibr" rid="ref8">8</xref>
        ], finite state machines [
        <xref ref-type="bibr" rid="ref9">9</xref>
        ], Prolog [
        <xref ref-type="bibr" rid="ref10 ref5">5, 10</xref>
        ], Active-U-Datalog [
        <xref ref-type="bibr" rid="ref11">11</xref>
        ],
or formal contract logic [
        <xref ref-type="bibr" rid="ref4">4</xref>
        ]. We also recently introduced in the setting of financial activities
the concept of modelling smart contracts with DatalogMTL [
        <xref ref-type="bibr" rid="ref12">12</xref>
        ] to emphasize the need of
expressing temporal operations in such settings.
      </p>
      <p>While these concepts give the possibility to provide the toolset, their usage is currently
limited: Not only is the research regarding logic-based languages in its infancy, there is usually
either no distributed ledger technology natively supporting the suggested language, or the
blockchain is not established and supported by a wide range of people, which can easily cause
security issues (e.g., creating forks and rewriting the immutable history).</p>
      <p>Contributions. In summary, while logic-based smart contracts would have all the advantages
discussed so far, it is all but impossible for such a language to gain acceptance until it is supported
by a major, widely adopted current blockchain. Achieving this is precisely the goal of this paper.
Our main contributions are:
• A theoretical discussion of each component of our DatalogMTL language including
required characteristics of our language due to typical procedural smart contract settings.
• A novel translation system converting DatalogMTL smart contracts into executable</p>
      <p>Solidity smart contracts, the predominant platform in practice.</p>
      <p>• An experimental evaluation including a discussion of possible improvement potentials.
Organization. The remainder of the paper is structured as follows: In Section 2 we summarize
DatalogMTL. In Section 3 we introduce DatalogMTL as smart contract language building on
the concepts introduced in our previous work. In Section 4 we present our translation engine,
which we evaluate in Section 5. We discuss related work in Section 6 and conclude this work in
Section 7.</p>
    </sec>
    <sec id="sec-2">
      <title>2. DatalogMTL</title>
      <p>
        DatalogMTL [
        <xref ref-type="bibr" rid="ref13 ref14 ref15">13, 14, 15</xref>
        ] extends Datalog with the metric temporal logic (MTL) in two ways:
(i) it assigns to each fact a set of valid timepoints (i.e., a validity interval) and (ii) it contains
temporal operators that modify the validity of the interval. We expect knowledge regarding
MTL, but note that readers familiar with LTL[
        <xref ref-type="bibr" rid="ref16">16</xref>
        ] will find the familiar operators used in a
diferent context.
      </p>
      <p>Intervals. Formally, intervals are defined over an ordered set of rational numbers Q where
each interval  is of the form ⟨− , +⟩ with the endpoints − , + ∈ Q ∪ {−∞ , ∞}, for each
 ∈  we have − ≤  ≤ + and ⟨ is either open (‘(’) or closed (‘[’) and ⟩ is either open (‘)’) or
closed (‘]’). An interval is punctual if it is of the form [, ], in which case we write  instead,
positive if − ≥ 0, and bounded if − , + ∈ Q.</p>
      <p>Syntax. DatalogMTL with stratified negation is defined over a function-free first-order
vocabulary consisting of disjoint sets of constants, variables and predicates. Each predicate is equipped
with a non-negative arity. A term is either a constant or a variable. An atom is of the form  ( ),
where  is a predicate and  is a tuple of  terms, with  matching the arity of  . A literal is
an expression of the form</p>
      <p>::=⊤ | ⊥ |  ( ) | ⊟  | ⊞  |  |  |    |   
where  is a positive interval. A rule is an expression of form
1 ∧ · · · ∧
 ∧ not +1 ∧ · · · ∧
not + → 
where ,  ≥ 0, each  is a literal and  is a literal not mentioning , ,  or  . The
conjunction is the body of the rule, where the literals 1 ∧ · · · ∧  denote positive body atoms
and +1 ∧ · · · ∧ + denote negated body atoms, and the literal  is the rule head. Instead of
∧ we sometimes use “,” to denote conjunction. A rule is safe if each variable occurs in at least
one positive body atom. A program Π is a finite set of safe rules and stratifiable if there exists a
stratification of a program Π. A stratification of Π is a function  mapping each predicate 
in Π to positive integers s.t. for each rule . . .  ′( ′) . . . →  ( ) in Π we have  ( ′) ≤  ( )
and for each rule . . . not  ′( ′) . . . →  ( ) in Π we have  ( ′) &lt;  ( ). A program, rule,
atom is ground if it contains no variables. A fact is an expression over an interval  of the form
 ( )@ where  ( ) is a ground atom. A dataset  is a finite set of facts.</p>
      <p>
        Semantics. An interpretation M is based on a domain for the individual variables and constants
that specifies for each time point  ∈ Q and each ground atom  ( ), whether  ( ) is satisfied
at , written as M,  |=  ( ). The notion of satisfiability of an interpretation M is extended
inductively to ground literals according to Figure 1. An interpretation M is a model of not 
(M,  |= not ), if M,  ̸|= , of a ground rule , if M,  |=  for 0 ≤  ≤  and M,  |= not 
for  + 1 ≤  ≤  +  for every , of a rule when it satisfies every possible grounding of the rule
and of a a program, if it satisfies every rule in the program and the program has a stratification.
An interpretation M is a model of a fact  ( )@, if M,  |=  ( ) for all  ∈  and a model
of a set of facts  if it satisfies each of these facts. A program Π and a dataset  entail a fact
 ( )@ ((Π, ) |=  ( )@) if M |=  ( )@ for each model of both Π and .
M,  |= ⊞ 
M,  |=   ′ if M,  |= ′ for some  with  −  ∈  ∧ M,  |=  for all  ∈ (, )
M,  |=   ′ if M,  |= ′ for some  with  −  ∈  ∧ M,  |=  for all  ∈ (, )
M,  |=  if M,  |=  for some  with  −  ∈ 
M,  |=  if M,  |=  for some  with  −  ∈ 
if M,  |=  for all  with  −  ∈ 
if M,  |=  for all  with  −  ∈ 
for each 
for no 
Negation and Arithmetics. As smart contracts vitally require negation and arithmetics,
we allow mild variants of both of them. First, we allow sequential stratified negation [
        <xref ref-type="bibr" rid="ref17">17</xref>
        ].
This allows the usage of negated body atoms in recursive rules in case the negated body
atoms maintain the monotonicity property. Analogously to stratified negation [
        <xref ref-type="bibr" rid="ref17">17</xref>
        ], we allow
sequential stratified arithmetic (in particular +,− ,× ,÷ ). We note that this is a much milder
form of arithmetic as e.g. in Vadalog [
        <xref ref-type="bibr" rid="ref18">18</xref>
        ], where arithmetic is also allowed in full recursion.
With the help of these two extensions we are able to express many of today’s use cases of smart
contracts (e.g., the transfer of tokens require arithmetic, toggling a value requires the negation
of the previous state).
      </p>
      <p>Example 2. Consider following DatalogMTL rule modelling a agreement – signed at some
point in the past – of a payment after the successful fulfillment of a specific Achievement .</p>
      <p>[0,∞)SignedPaymentAgreement(Buyer , Seller , Amount , Achievement ),</p>
      <sec id="sec-2-1">
        <title>SuccessfulFulfillment(Achievement ) → Payment(Buyer , Seller , Amount )</title>
      </sec>
    </sec>
    <sec id="sec-3">
      <title>3. Modelling Smart Contracts with DatalogMTL</title>
      <p>
        In this section we discuss the modelling of smart contracts with DatalogMTL over the integer
fragment [
        <xref ref-type="bibr" rid="ref14">14</xref>
        ]. We have introduced the modelling of smart contracts at EcoFinKG [
        <xref ref-type="bibr" rid="ref12">12</xref>
        ], a
ifnancial workshop, and present in this paper an extended form where we consider special
symbols/variables used in blockchains (we focus on Ethereum-based blockchains) and add a
discussion and detailed explanation on the derivation of each component. We introduce our
running example:
Example 3. Smart contracts often follow best-practice patterns, such as in Solidity [
        <xref ref-type="bibr" rid="ref19">19</xref>
        ],
the leading smart contract language. We consider one of the main patterns here, namely
that contracts often are modelled as state machines. Let us consider a state machine with
the following four stages: Init, AcceptingBids, Execution, and Finished. A contract is being
initialized, stays in the “accepting bids” state for exactly 10 days, then is in execution and
ifnally finished.
      </p>
      <sec id="sec-3-1">
        <title>3.1. Smart Contract Initialization</title>
        <p>In procedural smart contract languages one usually sets up the initial values with the constructor
which is invoked when deploying the smart contract in the blockchain. In DatalogMTL this
corresponds to providing the initial values as a given dataset at a certain timestamp. For the
timestamps, we have two options:
• Local timestamp. The smart contract does not depend on any other timestamps (either
time-information such as the current date or information from other contracts). Then
one can initialize the timestamp  with 0 or any other number.
• Global timestamp. The smart contract uses the timestamp of the blockchain for
initialization. This allows to use a shared timestamp and the actual current time inside the
contract. As for the contract itself, the initial value has no influence on the reasoning (it
is just shifted to a diferent timestamp), we always use a globally shared timestamp. This
is, we set the  = now (), where now is the current timestamp in the blockchain.
Example 4. (continued) The initial values are given by the following dataset encoding the
initial stage of the state machine: {Stage(Init )@}, where  is the deployment timestamp as
discussed above.</p>
      </sec>
      <sec id="sec-3-2">
        <title>3.2. Invoking a Smart Contract</title>
        <p>Usually, to invoke a smart contract in Ethereum one calls a method of a smart contract. Each
call is initialized by a transaction, which allows the called smart contract to invoke other smart
contracts. In DatalogMTL we only have rules that fire (i.e., derive the rule head) when the body
is satisfied. In order to model an invocation of a method in DatalogMTL, we mark predicates as
activators. These activators can be “called” by adding the activator for the current timestamp
to the dataset. By writing rules that use these activators in the body one hence triggers the
derivation of further facts. As we use activators for triggering rules, they have to obey the
following restrictions to enforce compatibility with Ethereum: (i) an activator is only allowed
in the body of the rule, (ii) only one activator is allowed to be executed per timestamp (to have
an implicit method call order and prevent conflicting states).</p>
        <p>Example 5. (continued) The set of activators for the bidding state machine consists of the
following activators: {Bid, Execute}.</p>
      </sec>
      <sec id="sec-3-3">
        <title>3.3. State Transitions</title>
        <p>One usually encodes in a method of a smart contract the transition of data/state before and after
the execution of a method. We already covered in the previous section the activation via an
“activator”. This activator triggers a set of rules that state how the current dataset at timepoint 
is changed for the next state at timepoint  + 1. This implies that such rules are not allowed to
derive facts for entries in the past.</p>
        <p>Example 6. (continued) The rules for the state machine are given as follows:</p>
        <sec id="sec-3-3-1">
          <title>Stage(Execution), ¬Execute, Bid(_, _) → ⊞ [1,1]Stage(Execution)</title>
        </sec>
        <sec id="sec-3-3-2">
          <title>Stage(Execution), Execute → ⊞ [1,1]Stage(Finished )</title>
        </sec>
        <sec id="sec-3-3-3">
          <title>Stage(Execution), Execute → DoAction . . .</title>
        </sec>
        <sec id="sec-3-3-4">
          <title>Stage(AcceptingBids), Bid(S , A) → VBid(S , A)</title>
          <p>
            VBid(S , A), HighBid(_, CA),  &gt;  → ⊞ [
            <xref ref-type="bibr" rid="ref1 ref1">1,1</xref>
            ]HighBid(S , A)
VBid(_, A), HighBid(S , CA),  &lt;=  → ⊞ [
            <xref ref-type="bibr" rid="ref1 ref1">1,1</xref>
            ]HighBid(S , CA)
HighBid(S , CA), ¬VBid(_, _), Bid(_, _) → ⊞ [
            <xref ref-type="bibr" rid="ref1 ref1">1,1</xref>
            ]HighBid(S , CA)
          </p>
          <p>
            HighBid(S , CA), ¬VBid(_, _), Execute → ⊞ [
            <xref ref-type="bibr" rid="ref1 ref1">1,1</xref>
            ]HighBid(S , CA)
Rule 1 defines the duration of the AcceptingBids stage, Rule 2 marks the start of the Execution
and Rule 3 extends this stage in case there was no Execute-action. Rule 4 translates the stage
to Finished in case of an execution and Rule 5 simulates a possible action of the execution.
Rules 6-10 manage the bidding phase, which defines on how the data is changed in the possible
settings (there is a bid which is higher/not higher and there is no bid). Note, that we model also
the “unchanged” values (3, 9-10) in DatalogMTL to derive a well-defined next state (requiring
always some given activator for a given timepoint for executing the rules only for the eligible
time).
          </p>
        </sec>
      </sec>
      <sec id="sec-3-4">
        <title>3.4. Interaction between Contracts</title>
        <p>So far, we focused on modelling a single smart contract. However, a method of a smart contract
can invoke a diferent (target) smart contract and use the return value in the remaining method.
In order to handle this case in DatalogMTL, we require the following extensions:
• Namespaces to uniquely identifies a given smart contract.
• Triggers to “trigger” an activator of a diferent smart contract. Note that due to the
restrictions of one activator per timestamp, this creates a temporal chain of calls.
• A Default Activator (Caller.default) to handle the passing of “return values” to the calling
smart contract. In case diferent default activators are required, one can introduce
additional intermediary smart contracts, which default activator triggers a named activator of
the original contract.
Example 7. (continued) A namespace for the running example could be “BidingContract” and
the DoAction could be an invocation of a contract (e.g., namespace Token) to transfer tokens,
e.g., Token.transferFrom(Src, Tgt , 20). After a successful application it uses the default
activator to trigger the calling smart contracts so that it can continue the execution.</p>
      </sec>
      <sec id="sec-3-5">
        <title>3.5. The Contract Definition</title>
        <p>Combining the introduced concepts, we derive the following definition:
Definition 1.</p>
        <p>A smart contract is a quadruple (, Π, , ) where:
•  is a unique name of the contract (namespace).
• Π is the DatalogMTL program encoding the rules of the smart contract
•  is the initial dataset encoding the initial state of the smart contract.
•  is the set of activators containing predicates which may be invoked by other smart contracts
or parties.</p>
      </sec>
      <sec id="sec-3-6">
        <title>3.6. Blockchain-specific Parameters</title>
        <p>While the introduced concept so far allows one to model several use cases, there is one open
point for discussion, namely blockchain-specific parameters. In this paper, we study the most
important properties of Solidity and how we can ensure the usage in DatalogMTL. Typically,
one distinguishes between three diferent classes of properties:
• Block-specific properties, such as the block number, or the timestamp.
• Transaction-specific properties, such as the initiator of the transaction (origin) considering
the full chain of executions starting from an external call to the activator.
• Message-specific properties, such as the caller or the number of coins sent to the invoked
contract.</p>
        <p>We inject these properties by introducing pre-defined predicates which are added to the dataset,
e.g., Block(Number ), Transaction(Origin) or Msg(Caller ). The only property we do not
consider in this mapping is the timestamp as this causes ambiguity and hence has to be treated
in a special way, which the following two points highlight:
• Timestamp per block. In Ethereum, the timestamp is provided per block and the only
requirement for the timestamp is that it is higher than the previous block. This means,
that the timestamp received in a method is the timestamp of the block. That is, each
transaction, and hence each method invocation (i.e., message) shares the same timestamp
and the actual timestamp is dependent on the miner of the block and may not model the
exact time.
• Time and ordering. For modelling smart contracts we require two diferent kinds of
timestamps. One that models the real time, for example to check if something happened
within the last 24 hours, and one to model the sequential order of method invocations.
In order to handle this representation problem in DatalogMTL, we decided to assign each
message its own timestamp. This is possible as the main goal is the conversion to the Ethereum
platform, where the natural mapping discussed above can be used.</p>
        <p>What we have seen is that for the purposes of this paper, namely translation, this yields a
quite natural, relatively simple structure of time. We remark that for future work that includes
verification of smart contracts, there is an interesting subtlety between the “logical” clock of
messages, and the real-world clock (as the number of messages per block vary and are unknown
in advance). While this is far beyond the scope of this paper, we want to note it is an interesting
item for possible research.</p>
      </sec>
    </sec>
    <sec id="sec-4">
      <title>4. Translating DatalogMTL to Solidity</title>
      <p>In the previous section we established the required formalism to model a Ethereum-compatible
smart contract in DatalogMTL. In this section, we present our proof of concept for translating
DatalogMTL rules into Solidity. Figure 2 shows a general overview of the process, where each
step is discussed in the following.
Phase 1 - Parser. The first phase is all about parsing and normalizing the program. For this, we
read a DatalogMTL smart contract from file and apply a normalization procedure to ensure that
each rule has a head without a temporal operator and the body either has literals containing no
temporal operator, or consists of exactly one literal with a single temporal operator.</p>
      <p>Example 8. (continued) Rule (3) of the running example would be rewritten by introducing
an auxiliary predicate and moving the temporal operation into the body as follows:
Stage(Execution), ¬Execute → Temp1()</p>
      <p>
        [
        <xref ref-type="bibr" rid="ref1 ref1">1,1</xref>
        ]Temp1() → Stage(Execution)
Phase 2 - Grouping of Rules and Method Detection. The goal of this step is to group rules
executed together and sort them by execution order to create a method in a Solidity contract. By
the usage of the activators we directly derive the starting points of the methods. These points
can be used to trace the derivation to check whether additional rules are activated. Next to that,
we find some other common patterns in rules:
• Negated activators are often used for describing the continuation of the current state
which does not require any handling in Solidity. If this is not the case, such negated
activator has to be checked before each method call.
• Global rules may not be triggered by any activator, i.e., they can depend on the current
state of the smart contract. Similar to the second case of negated activators, these rules
have to be enforced before any method call. Such rules are detected by checking the body
of the rule whether it is not only directly enforced by a rule containing an activator, e.g.,
there is a initial state or some time delay in between.
• Initial rules. These are similar to global rules, but are only executed on deployment of the
smart contract. These rules typically live in the constructor and have no time-dependent
condition in the future (as otherwise they would be global rules).
      </p>
      <p>Example 9. (continued) The group of rules for the running example are the execution group
(4-5) containing the Execute activator, the bidding rules (6-8) containing the Bid identifier
and the global group (1-2) which are activator independent. Rule (3) and (9) are detected as
negated activators copying the current state and are removed as no further consideration in
Solidity is requireda.
aNote that we have added those rules at the beginning to allow the smart contract to be interpreted by a Datalog
reasoner. When the only goal is the conversion to Solidity, one can ignore the rules when writing the smart
contract in DatalogMTL.</p>
      <p>Phase 3 - Data Types. We distinguish between the following two types:
• Term Type. We derive the data type of a term where possible from the internal values
(e.g., from the dataset). However, when there is an activator, we are unaware of which
values are provided by the user (e.g., is it 8bit or 256bit integer). Therefore, we extend the
activator syntax to provide data types for the activators.
• Atom Type. An atom can be either stored by one or more variables, each either being a
primitive, array or map. First, we distinguish whether there exists only one valid atom per
time unit, then single values are suficient and per term a variable is created. Otherwise,
we check if there is a pattern for accessing the atom to identify a map type (e.g., there is
an access in body and head and some variables are shared).</p>
      <p>Example 10. (continued) The activator for bidding would be Bid(). Note that with the
introduction of the message-specific parameters the sender  is extracted into an own atom
Msg(). The atom type of HighBid would consists of multiple primitives.
Phase 4 - State Types. For the state of the smart contract we have to distinguish between local
state where the derived fact is not shared with any other method and does not need historical
information, state variables where we only require the latest state (are not time-dependent),
variables where we need a last-timestamp of action, and variables were we need a history of
changes for a time period. For detecting the local state, we use the grouping to check whether
there exists not another group that contains the same atom and uses information from other
time units. In such a case, we can inline the state at contract generation. For detecting the
latest state atoms, we check whether the state always depends on the previous timestamp in
DatalogMTL. To distinguish between the remaining cases, we diferentiate on whether we have
to check if some condition is currently fulfilled or whether there is a more complex comparison
where the other case is not enough1.</p>
      <p>Example 11. (continued) Variables Stage0, HighestBid0 and HighestBid1 are identified as
global state, where the numbers reference to the term position. In addition a variable storing
the timestamp when Stage(InitState) become true is created.</p>
      <p>Phase 5 - Contract Generation. What now remains is the processing of the rules per group.
We start by adding preliminary checks, then continue per activator. This is, we structure the
rules by a dependency graph and convert each rule to Solidity. In case there is an option to
handle multiple rules at the same time, we try to find specific structures that follow a specific
pattern. For example, for the bidding rules, we detect that these rules are a typical if-else
structure and furthermore that only the if part is relevant.</p>
      <p>Example 12. (continued) The generated function for bidding is as follows, with checks for the
correct phase and a valid ofer. Note that __global is a modifier executed before the function
that handles automatic state transitions.
function bid(int a_) public __global {
require(compareStrings(_stage0, "AcceptingBids"),</p>
      <p>"invalid request");
require(a_ &gt; _highestbid1, "invalid request");
_highestbid0 = msg.sender;
_highestbid1 = a_;
}</p>
    </sec>
    <sec id="sec-5">
      <title>5. Evaluation</title>
      <p>
        In this section, we discuss the results of our smart contract language and generation process
by encoding the ERC-20 token in our language and comparing the generated code with the
original Solidity code [
        <xref ref-type="bibr" rid="ref20">20</xref>
        ]. The results of our generation are given in Figure 3. We provide the
corresponding DatalogMTL program in the Appendix.
      </p>
      <p>In general, the generation of the smart contract shows similar code as the compared original
code. This means, that the supposed steps of the pipeline achieve the desired goals. In a detail
comparison, we detected some possible improvement potentials: (i) reduce code, (ii) check for
variable range (e.g., overflows), (iii) improve variable types to reduce execution costs.</p>
      <p>Besides the discussed limitations, we want to remark that the current implementation is a
proof-of-concept not supporting all cases yet. The most relevant part is to detect the required
state types and their dependencies given by the rules, which we identified as one point that
needs more detailed investigation. Still, as the results have shown, the generation process is
feasible and we continue sharpening the generator to cover more advanced tasks in the future.
1Note that by the definition of state transitions, non-local state is only allowed to be set for future time points.</p>
    </sec>
    <sec id="sec-6">
      <title>6. Related Work</title>
      <p>One can group the related work around logic-based smart contracts into two categories: work
including and work not including temporal properties.</p>
      <p>
        Non-temporal-based related work. Idelberger et al. [
        <xref ref-type="bibr" rid="ref4">4</xref>
        ] suggest the formulation via formal contract
logic, a (deontic) defeasible logic. Frantz and Nowostawski [
        <xref ref-type="bibr" rid="ref8">8</xref>
        ] decompose institutions and
suggest a mapping of the components to Solidity smart contracts using a domain-specific
language. Stancu and Dragan [
        <xref ref-type="bibr" rid="ref10">10</xref>
        ] suggested a Python-to-Prolog interface to forward clauses to
a Prolog process for verification of the contract. Suvorov and Ulyantsev [
        <xref ref-type="bibr" rid="ref9">9</xref>
        ] suggest to use LTL
to express possible state transitions in a finite state machine which can be used to generate a
Solidity smart contract.
      </p>
      <p>
        Temporal-based related work. Hu and Zhang [
        <xref ref-type="bibr" rid="ref11">11</xref>
        ] propose a smart contract model based on
Active-U-Datalog (an extension of Datalog that can remove or add atoms from the dataset)
with a temporal extension given by a periodic expression and lower and upper bound where
this expression is valid. Critically, this approach deletes elements which are not valid at the
current time point disallowing to check the existence of previous values. In comparison, we
use an append-only data structures and model the change by going forward in time. Ciatto et
al. [
        <xref ref-type="bibr" rid="ref5">5</xref>
        ] suggest a new language based on Prolog ofering several temporal predicates to get the
current timestamp, delay the execution for some time units or execute a method periodically.
This suggestion is the closest to our solution, as it is the only solution considering temporal
properties, however neglecting intervals and requiring an own blockchain. Our paper builds on
our work presented at EcofinKG [
        <xref ref-type="bibr" rid="ref12">12</xref>
        ] providing new key insights in the smart contract design
and a novel translation technique to Solidity.
      </p>
    </sec>
    <sec id="sec-7">
      <title>7. Conclusion</title>
      <p>This work, to the best of our knowledge, is the first one to have a temporal logic-based smart
contract language that is executable on a widely used blockchain. While it is still a proof of
concept, it already handles many of the subtleties and challenges, in particular
blockchainspecific variables, state types, etc. It is able to produce meaningful code for widely used
patterns, including the ERC-20 token. In future work, we want to concentrate on improving the
translation engine and studying on the framework around the creation of a traditional contract
by strengthening the interdisciplinary collaboration.</p>
    </sec>
    <sec id="sec-8">
      <title>Acknowledgments</title>
      <p>This work was supported by the Vienna Science and Technology Fund (WWTF) grant
VRG18013, and the “rAIson data” Royal Society grant of Prof. Georg Gottlob.</p>
    </sec>
    <sec id="sec-9">
      <title>A. Programs</title>
      <sec id="sec-9-1">
        <title>A.1. ERC20 token</title>
        <p>In this section, we provide the full programs of our examples in DatalogMTL as given to our
translation engine, having some subtle diferences to the rules presented in the work, i.e., we
list the head first and use “:-” instead of →.</p>
        <p>In addition to the generated program in Figure 3 and the linked source code of the Solidity
version, we provide here the full version encoded in DatalogMTL.</p>
      </sec>
      <sec id="sec-9-2">
        <title>A.2. Running example</title>
        <p>
          In addition to the excerpt in Example 12 and the linked Solidity code of the presented pattern,
we provide here the full version in DatalogMTL as well as the generated version.
% I n i t r u l e , s e t b a l a n c e O f f o r c a l l e r
b a l a n c e O f ( C a l l e r , 2 0 0 0 ) : − msg ( C a l l e r ) .
% p a r t y i n i t i a t e s t r a n s f e r
t r a n ( C a l l e r , To , Value ) : − msg ( C a l l e r ) , t r a n s f e r ( To , Value ) .
% p a r t y a p p r o v e s t r a n s f e r i n f u t u r e
a l l o w a n c e s ( C a l l e r , Spender , Value ) : − msg ( C a l l e r ) , approve ( Spender , Value ) .
% Check whether b a l a n c e O f i s enough , then t r a n s f e r i s v e r i f i e d
vTran ( A , B , X ) : − t r a n ( A , B , X ) , b a l a n c e O f ( A , Y ) , X&lt;=Y .
% Apply t r a n s f e r
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] b a l a n c e O f ( A , NewBalance ) : − vTran ( A , B , X ) , b a l a n c e O f ( A , Y ) ,
        </p>
        <p>
          NewBalance=Y−X .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] b a l a n c e O f ( B , NewBalance ) : − vTran ( A , B , X ) , b a l a n c e O f ( B , Y ) ,
        </p>
        <p>
          NewBalance=Y+X .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] b a l a n c e O f ( B , X ) : − vTran ( A , B , X ) , not b a l a n c e O f ( B , _ ) .
% t h i r d p a r t y a p p l i e s t r a n s f e r
t r a n ( From , To , Value ) : − msg ( C a l l e r ) , t r a n s f e r F r o m ( From , To , Value ) ,
a l l o w a n c e s ( From , C a l l e r , ApprovedValue ) , ApprovedValue &gt;= Value .
% update approved v a l u e
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] a l l o w a n c e s ( From , C a l l e r , NewValue ) : − msg ( C a l l e r ) ,
t r a n s f e r F r o m ( From , To , Value ) , vTran ( From , To , Value ) ,
a l l o w a n c e s ( From , C a l l e r , ApprovedValue ) , NewValue= ApprovedValue − Value .
% Copy r u l e s
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] b a l a n c e O f ( A , Y ) : − b a l a n c e O f ( A , Y ) , not vTran ( A , _ , _ ) , not vTran ( _ , A , _ ) .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] a l l o w a n c e s ( A , B , Y ) : − a l l o w a n c e s ( A , B , Y ) , not vTran ( A , _ , _ ) .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] a l l o w a n c e s ( A , B , Y ) : − a l l o w a n c e s ( A , B , Y ) , not t r a n s f e r F r o m ( A , _ , _ ) .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] a l l o w a n c e s ( A , C a l l e r , Y ) : − a l l o w a n c e s ( A , C a l l e r , Y ) , not msg ( C a l l e r ) .
s t a g e ( " I n i t S t a t e " ) .
[ + ] ( 0 d , 1 0 d ) s t a g e ( " A c c e p t i n g B i d s " ) : − s t a g e ( " I n i t S t a t e " ) .
[ + ] [ 1 0 d , 1 0 d ] s t a g e ( " E x e c u t i o n S t a t e " ) : − s t a g e ( " I n i t S t a t e " ) .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] s t a g e ( " E x e c u t i o n S t a t e " ) : − s t a g e ( " E x e c u t i o n S t a t e " ) , not e x e c u t e .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] s t a g e ( " F i n i s h e d " ) : − s t a g e ( " E x e c u t i o n S t a t e " ) , e x e c u t e .
a c t i o n : − s t a g e ( " E x e c u t i o n S t a t e " ) , e x e c u t e .
i n B i d ( A ) : − b i d ( A ) , s t a g e ( " A c c e p t i n g B i d s " ) .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] h i g h e s t B i d ( C a l l e r , A ) : − msg ( C a l l e r ) , i n B i d ( A ) , h i g h e s t B i d ( _ , CA) ,A&gt;CA .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] h i g h e s t B i d ( S , CA) : − msg ( C a l l e r ) , i n B i d ( A ) , h i g h e s t B i d ( S , CA) ,A&lt;=CA .
[ + ] [
          <xref ref-type="bibr" rid="ref1 ref1">1 , 1</xref>
          ] h i g h e s t B i d ( S , CA) : − h i g h e s t B i d ( S , CA) , not i n B i d ( _ ) .
function bid(int a_) public __global {
require(compareStrings(_stage0, "AcceptingBids"), "invalid condition");
require(a_ &gt; _highestbid1, "invalid request");
_highestbid0 = msg.sender;
_highestbid1 = a_;
function execute() public __global {
require(compareStrings(_stage0, "ExecutionState"), "invalid condition");
_stage0 = "Finished";
function compareStrings(string memory a, string memory b) public pure returns (bool) {
        </p>
        <p>return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));</p>
      </sec>
    </sec>
  </body>
  <back>
    <ref-list>
      <ref id="ref1">
        <mixed-citation>
          [1]
          <string-name>
            <given-names>S.</given-names>
            <surname>Wang</surname>
          </string-name>
          ,
          <string-name>
            <given-names>D.</given-names>
            <surname>Li</surname>
          </string-name>
          ,
          <string-name>
            <given-names>Y.</given-names>
            <surname>Zhang</surname>
          </string-name>
          , J. Chen,
          <article-title>Smart contract-based product traceability system in the supply chain scenario</article-title>
          ,
          <source>IEEE Access 7</source>
          (
          <year>2019</year>
          )
          <fpage>115122</fpage>
          -
          <lpage>115133</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref2">
        <mixed-citation>
          [2]
          <string-name>
            <given-names>A.</given-names>
            <surname>Singh</surname>
          </string-name>
          ,
          <article-title>What is decentralized finance or defi explained</article-title>
          ,
          <year>2021</year>
          . URL: https://medium.com/ brandlitic/dc0ce376f7b2, accessed:
          <fpage>2021</fpage>
          -12-20.
        </mixed-citation>
      </ref>
      <ref id="ref3">
        <mixed-citation>
          [3]
          <string-name>
            <given-names>C.</given-names>
            <surname>Staf</surname>
          </string-name>
          ,
          <article-title>The use of smart contracts for legally binding agreements</article-title>
          ,
          <year>2021</year>
          . URL: https: //www.gemini.com/cryptopedia/smart-contracts
          <string-name>
            <surname>-</surname>
          </string-name>
          legally-binding, accessed:
          <fpage>2022</fpage>
          -06-09.
        </mixed-citation>
      </ref>
      <ref id="ref4">
        <mixed-citation>
          [4]
          <string-name>
            <given-names>F.</given-names>
            <surname>Idelberger</surname>
          </string-name>
          , G. Governatori,
          <string-name>
            <given-names>R.</given-names>
            <surname>Riveret</surname>
          </string-name>
          ,
          <string-name>
            <surname>G.</surname>
          </string-name>
          <article-title>Sartor, Evaluation of logic-based smart contracts for blockchain systems</article-title>
          , in: RuleML, volume
          <volume>9718</volume>
          of Lecture Notes in Computer Science,
          <year>2016</year>
          , pp.
          <fpage>167</fpage>
          -
          <lpage>183</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref5">
        <mixed-citation>
          [5]
          <string-name>
            <given-names>G.</given-names>
            <surname>Ciatto</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Mafi</surname>
          </string-name>
          ,
          <string-name>
            <given-names>S.</given-names>
            <surname>Mariani</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Omicini</surname>
          </string-name>
          ,
          <article-title>Smart contracts are more than objects: Proactiveness on the blockchain</article-title>
          ,
          <source>in: BLOCKCHAIN</source>
          , volume
          <volume>1010</volume>
          <source>of Advances in Intelligent Systems and Computing</source>
          ,
          <year>2019</year>
          , pp.
          <fpage>45</fpage>
          -
          <lpage>53</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref6">
        <mixed-citation>
          [6]
          <string-name>
            <given-names>S.</given-names>
            <surname>Team</surname>
          </string-name>
          , Solidity,
          <year>2022</year>
          . URL: https://soliditylang.org, accessed:
          <fpage>2022</fpage>
          -06-28.
        </mixed-citation>
      </ref>
      <ref id="ref7">
        <mixed-citation>
          [7]
          <string-name>
            <given-names>L.</given-names>
            <surname>Bellomarini</surname>
          </string-name>
          , G. Galano,
          <string-name>
            <given-names>M.</given-names>
            <surname>Nissl</surname>
          </string-name>
          , E. Sallinger,
          <article-title>Rule-based blockchain knowledge graphs: Declarative AI for solving industrial blockchain challenges, in: RuleML+RR (Supplement)</article-title>
          , volume
          <volume>2956</volume>
          <source>of CEUR Workshop Proceedings</source>
          ,
          <year>2021</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref8">
        <mixed-citation>
          [8]
          <string-name>
            <given-names>C.</given-names>
            <surname>Frantz</surname>
          </string-name>
          ,
          <string-name>
            <given-names>M.</given-names>
            <surname>Nowostawski</surname>
          </string-name>
          ,
          <article-title>From institutions to code: Towards automated generation of smart contracts</article-title>
          , in: FAS*W@SASO/ICCAC,
          <year>2016</year>
          , pp.
          <fpage>210</fpage>
          -
          <lpage>215</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref9">
        <mixed-citation>
          [9]
          <string-name>
            <given-names>D.</given-names>
            <surname>Suvorov</surname>
          </string-name>
          ,
          <string-name>
            <given-names>V.</given-names>
            <surname>Ulyantsev</surname>
          </string-name>
          ,
          <article-title>Smart contract design meets state machine synthesis: Case studies</article-title>
          , CoRR abs/
          <year>1906</year>
          .02906 (
          <year>2019</year>
          ).
        </mixed-citation>
      </ref>
      <ref id="ref10">
        <mixed-citation>
          [10]
          <string-name>
            <given-names>A.</given-names>
            <surname>Stancu</surname>
          </string-name>
          ,
          <string-name>
            <given-names>M.</given-names>
            <surname>Dragan</surname>
          </string-name>
          ,
          <article-title>Logic-based smart contracts</article-title>
          ,
          <source>in: WorldCIST (1)</source>
          , volume
          <volume>1159</volume>
          <source>of Advances in Intelligent Systems and Computing</source>
          ,
          <year>2020</year>
          , pp.
          <fpage>387</fpage>
          -
          <lpage>394</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref11">
        <mixed-citation>
          [11]
          <string-name>
            <given-names>J.</given-names>
            <surname>Hu</surname>
          </string-name>
          ,
          <string-name>
            <given-names>Y.</given-names>
            <surname>Zhong</surname>
          </string-name>
          ,
          <article-title>A method of logic-based smart contracts for blockchain system</article-title>
          ,
          <source>in: ICDPA</source>
          ,
          <year>2018</year>
          , pp.
          <fpage>58</fpage>
          -
          <lpage>61</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref12">
        <mixed-citation>
          [12]
          <string-name>
            <given-names>M.</given-names>
            <surname>Nissl</surname>
          </string-name>
          , E. Sallinger,
          <article-title>Modelling Smart Contracts with DatalogMTL</article-title>
          , in: EDBT/ICDT Workshops, volume
          <volume>3135</volume>
          <source>of CEUR Workshop Proceedings</source>
          ,
          <year>2022</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref13">
        <mixed-citation>
          [13]
          <string-name>
            <given-names>S.</given-names>
            <surname>Brandt</surname>
          </string-name>
          ,
          <string-name>
            <given-names>E. G.</given-names>
            <surname>Kalayci</surname>
          </string-name>
          ,
          <string-name>
            <given-names>V.</given-names>
            <surname>Ryzhikov</surname>
          </string-name>
          , G. Xiao,
          <string-name>
            <given-names>M.</given-names>
            <surname>Zakharyaschev</surname>
          </string-name>
          ,
          <article-title>Querying log data with metric temporal logic</article-title>
          ,
          <source>J. Artif. Intell. Res</source>
          .
          <volume>62</volume>
          (
          <year>2018</year>
          )
          <fpage>829</fpage>
          -
          <lpage>877</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref14">
        <mixed-citation>
          [14]
          <string-name>
            <given-names>P. A.</given-names>
            <surname>Walega</surname>
          </string-name>
          ,
          <string-name>
            <given-names>B. Cuenca</given-names>
            <surname>Grau</surname>
          </string-name>
          ,
          <string-name>
            <given-names>M.</given-names>
            <surname>Kaminski</surname>
          </string-name>
          ,
          <string-name>
            <given-names>E. V.</given-names>
            <surname>Kostylev</surname>
          </string-name>
          ,
          <article-title>Datalogmtl over the integer timeline</article-title>
          ,
          <source>in: KR</source>
          ,
          <year>2020</year>
          , pp.
          <fpage>768</fpage>
          -
          <lpage>777</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref15">
        <mixed-citation>
          [15]
          <string-name>
            <given-names>D. J. Tena</given-names>
            <surname>Cucala</surname>
          </string-name>
          ,
          <string-name>
            <given-names>P. A.</given-names>
            <surname>Walega</surname>
          </string-name>
          ,
          <string-name>
            <given-names>B. Cuenca</given-names>
            <surname>Grau</surname>
          </string-name>
          ,
          <string-name>
            <given-names>E. V.</given-names>
            <surname>Kostylev</surname>
          </string-name>
          ,
          <article-title>Stratified negation in datalog with metric temporal operators</article-title>
          ,
          <source>in: AAAI</source>
          ,
          <year>2021</year>
          , pp.
          <fpage>6488</fpage>
          -
          <lpage>6495</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref16">
        <mixed-citation>
          [16]
          <string-name>
            <given-names>A.</given-names>
            <surname>Pnueli</surname>
          </string-name>
          ,
          <article-title>The temporal logic of programs</article-title>
          , in: FOCS, IEEE Computer Society,
          <year>1977</year>
          , pp.
          <fpage>46</fpage>
          -
          <lpage>57</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref17">
        <mixed-citation>
          [17]
          <string-name>
            <given-names>C.</given-names>
            <surname>Zaniolo</surname>
          </string-name>
          ,
          <article-title>Logical foundations of continuous query languages for data streams</article-title>
          ,
          <source>in: Datalog</source>
          , volume
          <volume>7494</volume>
          of Lecture Notes in Computer Science,
          <year>2012</year>
          , pp.
          <fpage>177</fpage>
          -
          <lpage>189</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref18">
        <mixed-citation>
          [18]
          <string-name>
            <given-names>G.</given-names>
            <surname>Berger</surname>
          </string-name>
          ,
          <string-name>
            <given-names>G.</given-names>
            <surname>Gottlob</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Pieris</surname>
          </string-name>
          ,
          <string-name>
            <surname>E. Sallinger,</surname>
          </string-name>
          <article-title>The space-eficient core of vadalog</article-title>
          , in: PODS, ACM,
          <year>2019</year>
          , pp.
          <fpage>270</fpage>
          -
          <lpage>284</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref19">
        <mixed-citation>
          [19]
          <string-name>
            <surname>Ethereum</surname>
          </string-name>
          , Common patterns,
          <year>2022</year>
          . URL: https://docs.soliditylang.
          <source>org/en/v0.8</source>
          .15/ common-patterns.html, accessed:
          <fpage>2022</fpage>
          -06-28.
        </mixed-citation>
      </ref>
      <ref id="ref20">
        <mixed-citation>
          [20]
          <string-name>
            <surname>Ethereum</surname>
          </string-name>
          , Erc20 contract,
          <year>2018</year>
          . URL: https://github.com/ethereum/ethereum-org/blob/ master/solidity/token-erc20.sol, accessed:
          <fpage>2022</fpage>
          -06-05.
        </mixed-citation>
      </ref>
    </ref-list>
  </back>
</article>