Chapter 4
Requirements, Modeling and Contract Design
Diploma in Blockchain
Smart Contracts
•
Diploma
Requirements, Modeling and Contract Design
Introduction
A smart contract is not merely a piece of blockchain software. It is an executable agreement whose behaviour is constrained by business rules, blockchain data structures, transaction semantics, and the limits of the surrounding system. Poorly stated requirements often produce contracts that are technically functional but economically unsafe, legally unclear, or incapable of representing the intended business process.
Smart-contract design therefore begins before programming. The designer must translate a business problem into a precise specification involving actors, assets, states, events, functions, permissions, invariants, and failure conditions. The specification must also identify which responsibilities belong on-chain and which should remain off-chain. This separation is essential because blockchains provide strong integrity and shared execution, but they do not automatically provide accurate real-world information, privacy, scalability, or legal interpretation.
This chapter presents a practical method for moving from business requirements to a contract design that can be reviewed, tested, audited, and implemented.
Learning Objectives
By the end of this chapter, you should be able to:
Identify actors, assets, goals, assumptions, and constraints in a smart-contract problem.
Convert business requirements into functions, events, states, access rules, and invariants.
Model contract behaviour using state machines and process models.
Distinguish safety properties from liveness properties.
Separate on-chain responsibilities from off-chain responsibilities.
Select suitable architectural patterns and recognize their limitations.
Evaluate a contract specification for ambiguity, abuse, privacy, governance, and operational risk.
Produce a concise contract design specification suitable for implementation and audit.
1. From Business Requirement to Contract Specification
A business requirement describes a desired outcome in human language. For example: “A buyer should receive a refund if the supplier fails to deliver within seven days.” This statement is useful but incomplete. A contract designer must ask:
Who is the buyer and how is the identity represented?
What event proves delivery or non-delivery?
When does the seven-day period begin?
Which time source is used?
Who may initiate a refund?
Is the refund automatic, discretionary, or subject to arbitration?
What happens if the buyer and supplier disagree?
Which asset is refunded, and who pays transaction costs?
A contract specification transforms informal intentions into observable and enforceable rules. A useful requirement template is:
When [trigger or condition] occurs, actor [authorized actor] may or must perform action, causing state change, provided that preconditions hold; the contract emits event, and postconditions or invariants remain true.
For example:
When a funded order reaches its delivery deadline without an accepted delivery record, the buyer may request a refund, provided that the order is in the Funded state and no dispute is active. The order changes to Refunding, and the refundable amount is transferred according to the refund policy.
This formulation exposes missing decisions and makes the requirement testable.
1.1 Functional and Non-functional Requirements
Functional requirements state what the contract does. Examples include creating an order, depositing funds, confirming delivery, opening a dispute, releasing payment, and recording a result.
Non-functional requirements state qualities or constraints. Important examples include:
Requirement type
Typical question
Security
Can an unauthorized account change the order or withdraw funds?
Availability
Can users continue if an oracle or administrator is unavailable?
Privacy
Are commercial terms or participant identities confidential?
Performance
How many transactions and users must be supported?
Cost
Is the transaction cost acceptable for the business process?
Recoverability
What happens after a paused contract or operational failure?
Interoperability
Must the contract interact with tokens, bridges, or other contracts?
Compliance
Are record keeping, sanctions, consumer-protection, or reporting duties relevant?
A common error is to treat non-functional requirements as secondary. In blockchain systems, gas cost, key management, upgradeability, and privacy can determine whether a design is usable at all.
2. The Contract Domain Model
Before defining functions, identify the domain objects represented by the contract. A domain model normally contains actors, resources, records, relationships, and lifecycle states.
Actors
An actor is an account or external system that can initiate an action or supply information. Typical actors include a buyer, seller, lender, borrower, arbitrator, administrator, oracle, relayer, token contract, and governance body.
An actor is not necessarily a human. A decentralized application may act through a wallet, while an automated service may submit a transaction on behalf of a user. The specification should distinguish an actor’s real-world role from its blockchain address and should state how authority is assigned, transferred, revoked, or recovered.
Assets
Assets include native cryptocurrency, fungible tokens, non-fungible tokens, claims, licenses, deposits, or digitally represented rights. For each asset, specify:
its unit and precision;
its owner or custodian;
whether it is held by the contract or merely referenced;
whether transfer can fail or invoke external code;
whether the asset is refundable, divisible, or time-locked.
State Variables
State variables are persistent facts stored by the contract. Examples include order status, buyer address, seller address, deposited amount, deadline, dispute identifier, and release flag. Each state variable should have a clear type, purpose, valid range, and update authority.
Events
Events are externally visible records emitted when significant state changes occur. They support user interfaces, indexing services, monitoring, audit trails, and operational investigation. Events should describe completed facts rather than intentions. For example, PaymentReleased is preferable to ReleaseAttempted if the event is emitted only after a successful release.
Events are not a substitute for contract state. Applications cannot safely rely on an event that was never emitted, and historical event data may not be sufficient to reconstruct every current state unless the design explicitly supports that purpose.
3. Contract Functions and Access Rules
A function specification should identify its caller, inputs, preconditions, state changes, external calls, emitted events, and failure behaviour.
A compact function table is useful during design:
Function
Caller
Preconditions
Main effect
Event
createOrder
Buyer
Valid seller and positive amount
Creates an order in Created state
OrderCreated
fundOrder
Buyer
Order is Created; exact payment supplied
Locks funds; changes state to Funded
OrderFunded
confirmDelivery
Buyer
Order is Funded; no dispute
Marks delivery accepted
DeliveryConfirmed
releasePayment
Buyer or authorised process
Delivery accepted; not already released
Transfers seller amount
PaymentReleased
openDispute
Buyer or seller
Order is Funded; dispute window open
Changes state to Disputed
DisputeOpened
resolveDispute
Arbitrator
Order is Disputed
Applies resolution and closes order
DisputeResolved
Access-Control Models
Access control should be explicit. Common models include:
Ownable control: one administrator has privileged functions. It is simple but creates concentration and key-compromise risk.
Role-based access control: separate roles such as pauser, arbitrator, oracle, and treasury manager receive different permissions.
Multi-signature control: an action requires approval from several designated signers.
Token- or governance-based control: voting power or membership determines authority.
Capability-based control: a narrowly scoped permission or signed authorization allows a specific action.
Open participation: any account may call a function if objective conditions are satisfied.
The specification should state whether an administrator can alter parameters, upgrade code, seize funds, add arbitrators, pause operations, or change fees. “Admin” is not a sufficient requirement because it conceals the extent of power.
A permission matrix helps identify excessive privilege:
Action
Buyer
Seller
Arbitrator
Administrator
Public
Create order
Yes
No
No
No
No
Confirm delivery
Yes
No
No
No
No
Open dispute
Yes
Yes
No
No
No
Resolve dispute
No
No
Yes
No
No
Pause contract
No
No
No
Yes
No
Read public order data
Yes
Yes
Yes
Yes
Yes
4. Preconditions, Postconditions and Invariants
A precondition must hold before a function executes. A postcondition describes what should be true after successful execution. An invariant must remain true throughout the contract’s valid operation, including after every permitted state transition.
For an escrow contract, possible invariants include:
An order cannot be released twice.
The recorded order status must be one of the permitted statuses.
The sum of liabilities owed to users must not exceed assets held by the contract, subject to explicitly defined fees or external settlement arrangements.
A disputed order cannot be released by an ordinary payment function.
Only the designated arbitrator can resolve a dispute.
A completed order cannot return to an active state.
The conservation relationship for a simple escrow can be expressed as:
Bcontract = Σ Li + R
Here, Bcontract is the contract’s balance of the escrow asset, Li is the outstanding liability for order i, and R is the amount retained for explicitly defined reserves or fees. The relationship applies only when all relevant liabilities and balances are denominated in the same asset and when no unrecorded external obligations exist. If tokens can charge transfer fees, rebase balances, or behave maliciously, the accounting model must be expanded.
A stronger invariant for a fully collateralized escrow is:
Bcontract ≥ Σ Li
This inequality assumes the contract is intended to hold enough of the relevant asset to satisfy every recorded liability. It does not prove that funds can be withdrawn successfully, nor does it account for blockchain insolvency, token failure, or a compromised privileged key.
Safety and Liveness
A safety property states that something bad never happens. Examples are “funds cannot be released twice” and “an unauthorized account cannot change the arbitrator.”
A liveness property states that something good eventually happens. Examples are “a valid refund can eventually be claimed” and “a paused order can eventually be resolved.” Liveness is often neglected because a contract may be safe against theft but still lock funds permanently. Every terminal or exceptional state should therefore have a defined exit path, timeout, or governance procedure.
5. State Machines and Process Models
A state machine represents an entity as a set of states and permitted transitions. It is particularly effective for contracts with lifecycle-dependent rules.
An illustrative escrow lifecycle is:
Escrow state machine showing order lifecycle
Figure: Escrow state machine showing order lifecycle
Figure: A simplified escrow state machine. Each arrow represents a permitted transition subject to stated conditions.
For every transition, specify: current state, triggering function or event, authorized caller, conditions, new state, asset movement, and emitted event. A state machine also exposes invalid transitions. For example, a completed order should not accept a second delivery confirmation or a new dispute.
A process model is broader than a state machine. It includes human actions, external systems, documents, oracle observations, and exception handling. Use a process model when the contract depends on activities that cannot be performed by code alone.
6. On-chain and Off-chain Responsibilities
The blockchain should be assigned responsibilities for which shared, tamper-evident execution is valuable. These commonly include ownership records, payment custody, authorization checks, commitment storage, final state transitions, and public audit events.
Off-chain systems are usually better for large documents, personal data, complex computation, user interfaces, identity verification, physical inspection, communication, analytics, and confidential negotiation. A hash or content identifier can be stored on-chain while the underlying document remains elsewhere. However, a hash proves consistency with a supplied document; it does not prove that the document is truthful.
Responsibility
Usually on-chain
Usually off-chain
Payment custody
Yes
No, unless a trusted custodian is used
Large invoice document
No
Yes
Hash of invoice
Yes
No
Physical delivery verification
No
Yes, with oracle input
Final escrow transition
Yes
No
Personal identity evidence
Limited reference
Yes, subject to legal controls
User notifications
Event trigger
Yes
Complex risk scoring
Usually no
Yes, with governance for its use
Oracles and External Facts
A contract cannot directly observe a shipment, market price, temperature, or legal decision. An oracle supplies external information. Oracle requirements should address source selection, update frequency, authorization, aggregation, stale data, conflicting reports, and failure recovery.
An oracle does not eliminate trust; it relocates trust to the data source, reporting mechanism, and governance process. If an oracle can unilaterally determine a valuable outcome, it is a powerful actor and should be modelled accordingly.
7. Architectural Patterns
Escrow Pattern
Funds are held until a condition is met. The specification must define deposit, release, refund, dispute, timeout, and emergency procedures. Escrow contracts should avoid a design in which one inactive party can lock funds indefinitely.
Pull-Payment Pattern
Instead of sending funds to many recipients during a state-changing operation, the contract records a credit and allows each recipient to withdraw it. This can reduce failure coupling and mitigate certain reentrancy risks. The withdrawal function must still follow checks-effects-interactions discipline and protect against repeated claims.
Factory Pattern
A factory deploys or registers many related contracts. It can standardize configuration and simplify discovery, but factory privileges and implementation changes must be governed carefully.
Registry Pattern
A registry maps identifiers to addresses, documents, credentials, or contract versions. It requires rules for updates, revocation, key rotation, and conflicting entries.
Timelock and Commit–Reveal Patterns
A timelock delays execution to provide an observation or cancellation period. A commit–reveal process first records a cryptographic commitment and later reveals the underlying choice. In a simplified form, a commitment may be computed as:
c = H(x ∥ s)
Here, x is the hidden choice, s is a sufficiently unpredictable secret (salt), ∥ denotes concatenation, and H is a cryptographic hash function. The reveal is valid only if recomputing H(x ∥ s) produces c. Security depends on a collision-resistant hash, correct encoding, adequate secrecy of s, and a defined reveal deadline. This pattern reduces premature disclosure but does not by itself force a participant to reveal.
Upgradeable Contracts
Upgradeability can correct defects and adapt to changing requirements, but it introduces governance and trust risk. A specification must identify who upgrades, how upgrades are approved, whether users receive notice, how storage compatibility is maintained, and whether users can exit before an upgrade. Immutability is not automatically safer; it can preserve an irreversible defect. The appropriate choice depends on risk, governance, and the value of flexibility.
8. Worked Design Example: Agricultural Produce Escrow
The following is an illustrative case, not a legal or production-ready specification.
Background and Problem
A cooperative buys produce from independent farms. Payment should be locked at order creation, released after an inspector confirms acceptable delivery, and returned or divided if quality is disputed. The parties want an auditable process without placing invoices, identity documents, or inspection photographs directly on-chain.
Analysis
Actors are the cooperative, farm, accredited inspector, arbitrator, token contract, and contract administrator. The principal asset is a stable-value token. The order must represent quantity, price, delivery deadline, inspection deadline, document hashes, and current status.
The key risks are false inspection reports, expired deadlines, duplicate payment, token-transfer failure, inactive arbitrators, and exposure of commercially sensitive information. The contract cannot determine physical quality independently, so inspection is an oracle-like external input.
Approach and Contract Specification
The lifecycle is Created → Funded → Delivered or Disputed → Completed. The cooperative funds the order. The inspector submits a signed report containing an order identifier, quality result, timestamp, and document hash. The contract verifies that the inspector is authorised and that the report is within the inspection window.
A successful acceptance transition requires:
current state is Funded;
caller is an authorised inspector or a recognised reporting mechanism;
order identifier and report signature are valid;
report is not stale or already used;
the delivery deadline and inspection rules permit acceptance.
On acceptance, the state becomes Delivered. The cooperative may release payment during a defined release window. If the report fails quality requirements, either party may open a dispute. The arbitrator may award the buyer a refund, the farm the payment, or a defined split. The contract records the decision and prevents a second resolution.
The documents remain in approved off-chain storage. Their hashes and content identifiers are recorded on-chain. Identity verification is performed by an authorised service, while the contract stores only the minimum identifier or attestation needed for its rules.
Outcome
This design provides shared payment custody and an auditable lifecycle while acknowledging that quality assessment remains dependent on an external institution. It does not make the inspector truthful, guarantee token liquidity, or resolve legal questions about defective goods.
Learning Points
The most important design decision was not a function name but the allocation of responsibility between code, inspector, arbitrator, and storage service.
A dispute path was required for both safety and liveness.
Storing hashes reduced data exposure but did not remove privacy or availability obligations.
The inspector was modelled as a privileged actor and therefore required governance and revocation rules.
The state machine prevented payment functions from operating in inappropriate lifecycle states.
9. Validation, Testing and Review of a Specification
A specification should be reviewed before implementation. Useful techniques include:
Scenario analysis: describe normal, exceptional, malicious, and recovery scenarios.
Boundary analysis: examine zero values, maximum values, deadline equality, duplicate calls, and empty data.
Role review: test every function with authorised and unauthorised callers.
Transition coverage: ensure every state has an intended entry and exit path.
Invariant review: identify which properties must hold after every transaction.
Threat modelling: consider stolen keys, oracle manipulation, front-running, reentrancy, denial of service, griefing, and upgrade abuse.
Economic review: assess incentives, fees, collateral, penalties, and whether rational actors can profit by violating assumptions.
Traceability: map each business requirement to a state variable, function, event, test, and acceptance criterion.
A requirement is not complete merely because it has a function. It is complete when its meaning, authority, conditions, effects, exceptions, and verification method are clear.
10. Governance, Ethics and Regulation
Smart-contract design can distribute authority, but it can also conceal power in administrator keys, oracle operators, upgrade managers, or front-end providers. Governance should disclose who can act, under what conditions, with what notice, and subject to which checks.
Privacy requires special care because public ledgers can make transaction histories permanently visible. Data minimisation, pseudonymisation, selective disclosure, encryption outside the chain, and lawful retention policies may be necessary. Personal data should not be placed on-chain merely because storage is technically possible.
Legal enforceability depends on jurisdiction, contract formation, consumer protection, financial regulation, asset classification, and the relationship between code and legal text. “Code is law” is a technical slogan, not a universal legal conclusion. Where a legal agreement accompanies code, the parties should define which document governs in the event of conflict and how correction or dispute resolution operates.
AI may assist with requirements extraction, model checking, code review, or test generation, but generated output requires expert verification. AI systems can omit edge cases, reproduce insecure patterns, or misinterpret legal obligations. They should support—not replace—formal review, testing, and accountable decision-making.
11. Best Practices and Common Failure Modes
Best practices include:
begin with actors, goals, assets, and assumptions rather than code;
write requirements as observable, testable statements;
model states explicitly and reject invalid transitions;
distinguish permissions from business conditions;
define timeout, cancellation, dispute, and recovery paths;
minimize on-chain data and never assume a hash proves truth;
treat oracles, administrators, and upgrade mechanisms as security-critical;
document units, token decimals, rounding, and fee treatment;
emit events only for meaningful completed actions;
design for failed external calls and inactive participants;
maintain traceability from requirement to test and audit evidence.
Common failures include ambiguous deadlines, administrator powers that are never documented, events that do not match state changes, funds that can be locked forever, reliance on a single unaccountable oracle, and assuming that a technically valid transaction is economically or legally correct.
Chapter Summary
Smart-contract design is a requirements-engineering activity as much as a programming activity. A robust specification identifies actors, assets, state variables, functions, events, permissions, preconditions, postconditions, invariants, and failure paths. State machines clarify lifecycle rules, while process models show how code interacts with people, documents, oracles, and external systems.
On-chain execution is appropriate for shared custody, authorization, commitments, and final state transitions. Off-chain systems are generally more suitable for large or private information, complex computation, identity evidence, physical inspection, and user interaction. Oracles connect the two environments but introduce explicit trust and governance risks.
Architectural patterns such as escrow, pull payments, registries, factories, timelocks, commit–reveal, and upgradeable contracts offer reusable solutions, but each creates assumptions that must be documented. Professional design requires security, economic, privacy, ethical, legal, and operational review. The final specification should be precise enough to implement and test, yet honest about what the blockchain cannot know or guarantee.
Key Terms
Actor: An account, person, organisation, contract, or external system that participates in a process.
Asset: A token, currency, claim, right, or other resource represented or controlled by a contract.
Event: A blockchain record emitted to communicate a significant contract occurrence.
Function: An executable contract operation that may read or change state.
Precondition: A condition that must hold before an operation can execute.
Postcondition: A condition expected to hold after successful execution.
Invariant: A property that must remain true throughout valid operation.
State variable: Persistent data stored by a contract.
State machine: A model consisting of states and permitted transitions.
Process model: A representation of activities, actors, systems, and information flows.
Access control: Rules determining which actors may perform particular actions.
Oracle: A mechanism that supplies external information to a blockchain contract.
Escrow: A custody arrangement in which assets are released when specified conditions are met.
Liveness: The property that an intended valid outcome can eventually occur.
Safety: The property that prohibited outcomes do not occur.
Commit–reveal: A two-stage process that hides a choice before later verification.
Timelock: A rule that delays execution until a specified time or block condition.
Upgradeability: The ability to change contract logic or configuration after deployment.
On-chain responsibility: A responsibility implemented or verified by blockchain execution.
Off-chain responsibility: A responsibility performed by people, services, or systems outside the blockchain.
Review Questions
Short Answer Questions
What is the purpose of converting a business requirement into a contract specification?
Distinguish a precondition from an invariant.
Why should events not be treated as a substitute for contract state?
What is the principal function of an oracle?
State one advantage and one risk of an upgradeable contract.
Long Answer Questions
Explain how actors, assets, states, functions, events, and access rules combine to form a contract domain model.
Describe how a state machine can prevent invalid transitions in an escrow contract.
Compare on-chain and off-chain responsibilities, including privacy, cost, and trust considerations.
Discuss safety and liveness properties and explain why both are necessary in contract design.
Evaluate the governance and security implications of administrator-controlled upgrades.
Analytical / Application Questions
Design a state machine for a token-based rental agreement. Identify at least five states, permitted transitions, actors, and one invariant.
A contract records a shipment as delivered when a single oracle submits a signed message. Analyse the trust, security, and governance risks and propose a stronger design.
For a dispute-resolution contract, produce a permission matrix and identify two possible ways funds could become permanently locked. Propose mitigations for each.
Multiple Choice Questions with Answers
Question 1
Which item states what must be true before a contract function executes?
A. Event
B. Precondition
C. Invariant
D. Postcondition
Correct Answer: B. Precondition
Question 2
Which responsibility is generally most suitable for on-chain implementation?
A. Storing large inspection photographs
B. Performing confidential identity verification
C. Enforcing payment custody and authorization checks
D. Determining the physical quality of goods
Correct Answer: C. Enforcing payment custody and authorization checks
Question 3
What does a state machine primarily describe?
A. The legal jurisdiction of a contract
B. Permitted states and transitions in a lifecycle
C. The market price of a token
D. The programming language used for deployment
Correct Answer: B. Permitted states and transitions in a lifecycle
Question 4
Which is a safety property?
A. A valid refund can eventually be claimed
B. An arbitrator eventually responds
C. Funds cannot be released twice
D. A user eventually receives a notification
Correct Answer: C. Funds cannot be released twice
Question 5
What does an oracle introduce into a smart-contract system?
A. A guarantee that external information is truthful
B. A mechanism and trust relationship for supplying external information
C. Automatic legal enforcement in every jurisdiction
D. Removal of all governance requirements
Correct Answer: B. A mechanism and trust relationship for supplying external information
Question 6
In the commitment formula c = H(x ∥ s), what is s?
A. The contract balance
B. The state transition
C. A secret salt or additional hidden value
D. The event identifier
Correct Answer: C. A secret salt or additional hidden value
Question 7
Which access-control model requires approval from several designated signers?
A. Open participation
B. Multi-signature control
C. Single-owner control
D. Public read access
Correct Answer: B. Multi-signature control
Question 8
Why is a pull-payment pattern often used?
A. It eliminates the need for authorization
B. It lets recipients withdraw recorded credits and reduces transfer coupling
C. It makes all payments private
D. It guarantees that external tokens cannot fail
Correct Answer: B. It lets recipients withdraw recorded credits and reduces transfer coupling
Question 9
Which statement about storing a document hash on-chain is correct?
A. It proves the document is factually true
B. It proves that a supplied document matches the committed digest
C. It makes the document automatically private
D. It removes the need for document availability
Correct Answer: B. It proves that a supplied document matches the committed digest
Question 10
Which design feature most directly helps prevent an order from being resolved twice?
A. An explicit terminal state and a transition check
B. A larger user interface
C. A longer document hash
D. Off-chain email notification
Correct Answer: A. An explicit terminal state and a transition check