Skip to main content

04 - Smart Contracts for Legal Agreements: Solidity and Vyper

Smart contracts and legal agreements: Italian Article 8-ter and the Arizona statute, an escrow as a state machine, reentrancy and the legal wrapper.

What do you think about this article?

At a Glance

Smart contracts and legal agreements: Italian Article 8-ter and the Arizona statute, an escrow as a state machine, reentrancy and the legal wrapper.

A smart contract is not a contract: what code can do and what is left to the law

A smart contract is a program that runs on a blockchain and moves value when certain conditions occur. A contract is an agreement between people that the law recognises and enforces. The two sets overlap only in part: there can be a program that nobody ever "accepted" in the legal sense, and a valid agreement that no program can execute. If you work on real agreements, your task is to understand which piece of the agreement can be automated, and to link it to a legal text that states its value.

On this point rules exist and they differ from how the story is often told. In Italy, Article 8-ter of Decree-Law 135/2018 (decreto-legge, D.L.) defines a smart contract as "un programma per elaboratore che opera su tecnologie basate su registri distribuiti e la cui esecuzione vincola automaticamente due o più parti sulla base di effetti predefiniti dalle stesse" (a computer program that operates on technologies based on distributed ledgers and whose execution automatically binds two or more parties on the basis of effects predefined by them), and adds that it satisfies the requirement of written form following computer-based identification of the parties, through a process meeting the requirements set by the Agency for Digital Italy (AgID) in its own guidelines. I read the text on Normattiva (the official database of Italian legislation); I did not verify whether those guidelines were subsequently adopted, and the condition is decisive: it must be checked before relying on the provision.

In the United States the Arizona statute (A.R.S. 44-7061) is more cautious than is said: it establishes that smart contracts "may exist in commerce" and that a contract cannot be denied legal effect, validity or enforceability solely because it contains a smart contract term. It does not declare every program binding. The two provisions therefore say the same thing at bottom: code is not excluded from the law merely for being code, but the ordinary requirements of a contract still have to be met.

When automating makes sense, and when it does not

The useful criterion is verifiability: the blockchain sees only what happens on the blockchain. A payment received, a deadline that passes, the transfer of a token are facts the code establishes by itself. "The goods arrived in good condition" is not: someone will have to tell the contract, and that someone (a person, an arbitrator, an oracle) becomes the point where you shift trust, not an elimination of it.

  • Condition verifiable on-chain: automation removes the checking work.
  • Condition that depends on the real world: you need a person or an oracle, and the risk moves there.
  • Agreement to be interpreted or renegotiated: code is not the right tool.

The three items are not equal: the first is the only one where code brings an advantage without introducing a new point of trust. That is why the example that follows, an escrow deposit, is built with an arbitrator designated in advance: it accepts that the dispute over the real-world fact is settled by a person, and automates only what is verifiable, that is, who can do what and when.

The escrow as a state machine, run in a Python model

Before writing Solidity it pays to draw the states and the permitted transitions, because the most frequent flaw in a contract of this kind is a transition that nobody had foreseen. I do not have a Solidity compiler on this machine, so the model below is in Python: it reproduces the logic (who can call what, in which state) but it is not the contract and proves nothing about gas, storage or EVM security. The use of immutable data (frozen=True and replace) means that every transition produces a new state, and a rejected action leaves no effects, like a revert.

Python - escrow state machine (model, not Solidity)
from dataclasses import dataclass, replace
from enum import Enum


class Stato(Enum):
    CREATO = "created"
    FINANZIATO = "funded"
    IN_DISPUTA = "in dispute"
    PAGATO_VENDITORE = "paid to the seller"
    RIMBORSATO = "refunded"


class Rifiutato(Exception):
    """Equivalent to a revert: the transaction produces no effect."""


@dataclass(frozen=True)
class Escrow:
    compratore: str
    venditore: str
    arbitro: str
    scadenza: int            # instant after which the seller can collect if nobody has acted
    importo: int = 0
    stato: Stato = Stato.CREATO


def finanzia(e: Escrow, chi: str, importo: int) -> Escrow:
    if chi != e.compratore or e.stato is not Stato.CREATO or importo <= 0:
        raise Rifiutato("finanzia")
    return replace(e, importo=importo, stato=Stato.FINANZIATO)


def conferma_consegna(e: Escrow, chi: str) -> Escrow:
    if chi != e.compratore or e.stato is not Stato.FINANZIATO:
        raise Rifiutato("conferma_consegna")
    return replace(e, stato=Stato.PAGATO_VENDITORE)


def apri_disputa(e: Escrow, chi: str) -> Escrow:
    if chi not in (e.compratore, e.venditore) or e.stato is not Stato.FINANZIATO:
        raise Rifiutato("apri_disputa")
    return replace(e, stato=Stato.IN_DISPUTA)


def decide(e: Escrow, chi: str, a_favore_venditore: bool) -> Escrow:
    if chi != e.arbitro or e.stato is not Stato.IN_DISPUTA:
        raise Rifiutato("decide")
    return replace(e, stato=Stato.PAGATO_VENDITORE if a_favore_venditore else Stato.RIMBORSATO)


def incassa_dopo_scadenza(e: Escrow, chi: str, adesso: int) -> Escrow:
    if chi != e.venditore or e.stato is not Stato.FINANZIATO or adesso < e.scadenza:
        raise Rifiutato("incassa_dopo_scadenza")
    return replace(e, stato=Stato.PAGATO_VENDITORE)


def prova(nome, azione):
    try:
        print(f"{nome:<44} -> {azione().stato.value}")
    except Rifiutato as r:
        print(f"{nome:<44} -> REJECTED ({r})")


if __name__ == "__main__":
    base = Escrow("anna", "bruno", "carla", scadenza=1_000)
    f = finanzia(base, "anna", 500)
    prova("delivery confirmed by the buyer", lambda: conferma_consegna(f, "anna"))
    prova("delivery 'confirmed' by the seller", lambda: conferma_consegna(f, "bruno"))
    prova("dispute, then the arbitrator decides (refund)", lambda: decide(apri_disputa(f, "anna"), "carla", False))
    prova("arbitrator decides with no dispute open", lambda: decide(f, "carla", True))
    prova("seller collects before the deadline", lambda: incassa_dopo_scadenza(f, "bruno", 999))
    prova("seller collects after the deadline", lambda: incassa_dopo_scadenza(f, "bruno", 1_000))
    prova("confirm twice", lambda: conferma_consegna(conferma_consegna(f, "anna"), "anna"))

# Output (run):
# delivery confirmed by the buyer              -> paid to the seller
# delivery 'confirmed' by the seller           -> REJECTED (conferma_consegna)
# dispute, then the arbitrator decides (refund) -> refunded
# arbitrator decides with no dispute open      -> REJECTED (decide)
# seller collects before the deadline          -> REJECTED (incassa_dopo_scadenza)
# seller collects after the deadline           -> paid to the seller
# confirm twice                                -> REJECTED (conferma_consegna)

The output shows seven scenarios and three things. Only the buyer can confirm delivery, so the seller who tries to "confirm" their own payment is rejected. The arbitrator can decide only if a dispute has been opened, and for this reason cannot step in on their own initiative. And there is the incassa_dopo_scadenza function (collect after the deadline), which is missing from many examples in circulation: a contract that collects an "automatic release" deadline and then never uses it leaves the funds locked forever if the buyer disappears after delivery. The test of the two boundary cases (999 rejected, 1,000 accepted) is the kind of test that in a real project is written for every time boundary. A warning: time on the blockchain is that of the block, which whoever produces the block can shift slightly, so deadlines of a few seconds should not be considered precise.

The most expensive vulnerability: reentrancy

Sending funds to an address can execute the recipient's code. The Solidity security guide describes the problem and recommends the checks-effects-interactions pattern: first the checks, then the update of the state, only at the end the sending. The listing that follows simulates the difference with a model: a "bank" that holds 110 units (100 belonging to Anna and 10 to Mallory) and a malicious recipient that, on receiving the funds, immediately calls preleva (withdraw) again. In the wrong order Mallory's balance is still 10 on the second attempt, because it is zeroed only after the sending.

Python - reentrancy model
class Banca:
    """Model of a contract that holds funds. The sending calls the recipient's code
    BEFORE the calling function continues: this is what happens in an external call on the EVM."""

    def __init__(self, ordine_sicuro: bool):
        self.saldi = {"anna": 100, "mallory": 10}
        self.cassa = 110                      # funds actually held
        self.ordine_sicuro = ordine_sicuro

    def preleva(self, chi, ricevente):
        importo = self.saldi[chi]
        if importo == 0 or self.cassa < importo:
            return
        if self.ordine_sicuro:                # checks-effects-interactions: update the state first
            self.saldi[chi] = 0
        self.cassa -= importo
        ricevente(self)                       # external call: the recipient runs its own code
        if not self.ordine_sicuro:            # wrong order: the state is updated AFTER
            self.saldi[chi] = 0


def attacco(banca, profondita):
    if profondita[0] < 5:                     # re-enters as long as the till allows it
        profondita[0] += 1
        banca.preleva("mallory", lambda b: attacco(b, profondita))


for sicuro in (False, True):
    banca = Banca(ordine_sicuro=sicuro)
    attacco(banca, [0])
    print(f"state updated before sending = {sicuro!s:<5}: remaining till = {banca.cassa}, "
          f"anna's balance = {banca.saldi['anna']}")

# Output (run):
# state updated before sending = False: remaining till = 60, anna's balance = 100
# state updated before sending = True : remaining till = 100, anna's balance = 100

With the wrong order the till goes from 110 to 60: Mallory, who was entitled to 10, withdrew 50 by calling the function five times, and Anna's balance (100) is no longer covered by real funds. With the state zeroed before the sending, the second attempt finds a zero balance and stops: the till stays at 100. This is a model, not the EVM: the real behaviour depends on how the call is written. The Solidity fragment below applies the pattern, and I did not compile it: it must be compiled and tested (with Hardhat or Foundry) before any use.

Solidity - withdrawal with checks-effects-interactions (not compiled)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract PrelievoSicuro {
    mapping(address => uint256) public dovuto;

    function accredita(address a) external payable {
        dovuto[a] += msg.value;
    }

    function preleva() external {
        uint256 importo = dovuto[msg.sender];      // 1. checks
        require(importo > 0, "Nothing to withdraw");
        dovuto[msg.sender] = 0;                    // 2. effects: the state changes BEFORE the sending
        (bool ok, ) = msg.sender.call{value: importo}("");   // 3. interaction
        require(ok, "Transfer failed");
    }
}

# Not compiled or run: no Solidity compiler on this machine. Schema to adapt.

In the fragment the balance is zeroed at step 2 and the sending happens at step 3. The choice of call{value: ...} instead of transfer depends on the fact that transfer forwards a fixed "gas stipend" of 2,300 units, which the guide itself warns may change with future protocol modifications: the check of the result (require(ok)) is mandatory, because call does not raise an error by itself. Another point the fragment does not solve: whoever receives the funds must withdraw them themselves (the "pull" model), instead of having them sent by the contract during an arbitrator's decision, because a recipient that refuses the sending would otherwise block the whole operation.

What changes when you choose Vyper

Vyper is a language for the EVM with a Python-like syntax and with explicit choices of simplicity. The documentation lists what it does not offer, with the reasons: modifiers, class inheritance, inline assembly, function and operator overloading, recursive calls, infinite-length loops. The last two are explained by gas: without an upper limit you cannot prove how much a call will cost. The gain is readability for whoever audits (the checks are inside the function, like assert, not in a modifier defined elsewhere); the cost is an ecosystem of libraries and tools smaller than Solidity's. I do not show a Vyper listing because I could not compile it: the syntax of events and structures changes between versions, and is verified on the version you will use.

One thing Vyper does not do: it does not protect from design errors. A wrong state machine such as the one without an exit for the seller remains wrong in any language. In Solidity, on the other hand, since version 0.8 arithmetic operations revert on overflow or underflow (the earlier behaviour returns only with unchecked), as the notes on version 0.8 report.

The legal wrapper: where the code attaches to the text

An agreement that uses a smart contract as its execution mechanism needs a legal text that identifies the parties, says that address X is the instrument through which the agreement is executed, chooses the governing law and the forum, and establishes what happens if the code behaves in an unexpected way. A common way of linking the two worlds is to cite the fingerprint of the document in the text and, in the contract, the fingerprint of the attached text. The listing shows a trap: the same text saved with different line endings has different fingerprints.

Python - SHA-256 fingerprint of a text, with and without normalisation
import hashlib

clausola_lf = "The Supplier delivers within 30 days.\nThe Customer pays within 60 days.\n"
clausola_crlf = clausola_lf.replace("\n", "\r\n")      # the same text saved by another editor

for nome, testo in (("LF", clausola_lf), ("CRLF", clausola_crlf)):
    print(f"{nome:<5} sha256 = {hashlib.sha256(testo.encode('utf-8')).hexdigest()[:16]}...")

def impronta_normalizzata(testo: str) -> str:
    uniformato = "\n".join(riga.rstrip() for riga in testo.replace("\r\n", "\n").split("\n"))
    return hashlib.sha256(uniformato.encode("utf-8")).hexdigest()

print("normalised, equal:", impronta_normalizzata(clausola_lf) == impronta_normalizzata(clausola_crlf))

# Output (run):
# LF    sha256 = fe34e6cabe1bcb81...
# CRLF  sha256 = e6edf2dfd079b77d...
# normalised, equal: True

The output shows two different fingerprints for the same text, because the files differ by \n and \r\n; after normalisation they coincide. In a legal wrapper the normalisation rule is part of the agreement: you write down which one, otherwise a fingerprint that cannot be reproduced proves nothing. The same caution applies to the source code cited in the contract. For the related topics of identifying the parties and the validity of signatures, see the article on e-signatures and document authentication; for rules of compliance that can be automated, the one on compliance automation.

What you can do now

You can tell what a smart contract can execute from what is left to the law, citing the provisions that say so (with the condition of Article 8-ter that has to be verified), you can draw an escrow as a state machine with the right transitions and test the boundary cases, you know why the state must be updated before the sending, and you can link code and legal text with a reproducible fingerprint. What remains to be done is what I could not do here: compile and test the Solidity and have it checked by a security reviewer before putting money at stake. For the next step, the summarisation of legal documents, see summarisation with generative artificial intelligence. What is written here is not legal advice.

Frequently asked questions

Does a smart contract have legal value in Italy?

Article 8-ter of Decree-Law 135/2018 defines it and provides that it satisfies the written form following computer-based identification of the parties, through a process meeting the requirements set by AgID in guidelines. It must be verified whether the guidelines were adopted, and the ordinary requirements of a contract still have to be met.

Why is transfer not used to send funds in Solidity?

Because it forwards a fixed amount of gas (2,300) that the documentation warns may change with protocol modifications. call is preferred, with a check of the result, updating the state before the sending to avoid reentrancy.

Can a bug in a smart contract be fixed after release?

Published code cannot be modified. You can design an update mechanism (for example with a proxy) or an emergency stop, but these are design choices with their own risks, to be declared in the legal wrapper. That is why testing and security review come before release.

Sources

The three listings marked "Output (run)" are models in Python 3 with the standard library only and were run; they are not smart contracts and prove nothing about real execution on the EVM. The Solidity fragment was neither compiled nor run. No part of the article is legal advice.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects