Learning Objectives – after this chapter you will be able to:
  • Explain what a contract is and how it compares with procedures and classes.
  • List the elements that a contract can contain.
  • Create one contract from another with new and interact with it.
  • Describe abstract contracts and libraries at an introductory level.
What are Contracts?

All Solidity code is written inside contracts. A contract is a collection of code (its functions) and data (its state) that lives at a specific address on the Ethereum blockchain. It is the fundamental building block of every Ethereum application.

POP vs OOP vs BOP

This course compares three programming styles. “BOP – Block Oriented Programming” is the name used in this course to describe contract-based programming on a blockchain.

Sr.No.TitleShortLanguageUnit of codeContains
1Procedure Oriented ProgrammingPOPCFunctions / proceduresFunctions operating on separate data
2Object Oriented ProgrammingOOPC++ / Java / C#ClassesState & methods, objects in memory
3Block Oriented Programming (course term)BOPSolidityContractsState & functions, stored permanently on the blockchain
What Can a Contract Contain?
Pragma (file level)Instructions to the compiler. Every file should start with a version pragma so it is not compiled by an incompatible future compiler.
contract keywordDeclares a contract and encloses all of its code.
State variablesValues stored permanently in contract storage on the blockchain.
FunctionsCode blocks that read or change state; declared with function, a name, parameters and a body.
Function modifiersReusable checks applied to functions (Chapter 22).
EventsLogs that front ends can listen to (Chapter 20).
Custom errorsNamed errors used with revert (Chapter 21).
Struct and enum typesUser-defined data types (Chapters 11 and 13).
ConstructorRuns once at deployment (Chapter 17).
Kinds of Contract-like Units
  • contract – a normal deployable contract.
  • abstract contract – has at least one function without implementation (or is marked abstract); it cannot be deployed and is used as a base for inheritance (Chapter 18).
  • interface – only function declarations, no implementation or state (Chapter 19).
  • library – reusable code with no state of its own, e.g. maths helpers; its functions are called by contracts.
Example : One Contract Creating Another
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Wallet {
    address public owner;
    string public label;

    constructor(address _owner, string memory _label) {
        owner = _owner;
        label = _label;
    }
}

contract WalletFactory {
    Wallet[] public wallets;                       // contract type as a variable type

    function createWallet(string calldata label) external returns (address) {
        Wallet w = new Wallet(msg.sender, label);  // deploys a new contract
        wallets.push(w);
        return address(w);                         // address of the new contract
    }

    function ownerOf(uint index) external view returns (address) {
        return wallets[index].owner();             // call a getter of another contract
    }

    function totalWallets() external view returns (uint) {
        return wallets.length;
    }
}
Key Takeaways
  • A contract = state + functions at a blockchain address, similar to a class whose objects live on-chain.
  • Contracts can contain state variables, functions, modifiers, events, errors, structs, enums and a constructor.
  • new deploys a contract from another contract; contract types can be stored and called.
Download | Print      E-Notes

The PDF E-Notes are the earlier printable version of this chapter. The notes on this page are the latest, revised version.

Video : Contracts in Solidity
Resource File
Question / Answer (15 questions)

Answer : A contract is a collection of code (functions) and data (state) that resides at a specific address on the blockchain. It is the fundamental building block of Ethereum applications.

Answer : POP (e.g. C) organises code into functions that act on separate data; OOP (e.g. C++, Java, C#) uses classes that combine state and methods; BOP (the course’s term for Solidity) uses contracts that combine state and functions stored permanently on the blockchain.

Answer : Pragma is generally the first line of code (after the SPDX line) in a Solidity file. The version pragma specifies which compiler versions may compile the file.

Answer : SPDX is an open standard (ISO/IEC 5962:2021) for communicating software licence and supply-chain information. In Solidity, the comment // SPDX-License-Identifier: MIT declares the file’s licence.

Answer : State variables, functions, function modifiers, events, custom errors, struct and enum types, and a constructor.

Answer : With the new keyword, e.g. Wallet w = new Wallet(msg.sender, label);. This deploys a new instance and returns a reference to it.

Answer : Convert the contract variable: address(w). Inside a contract, address(this) gives its own address.

Answer : A contract marked abstract, typically because at least one function has no implementation. It cannot be deployed and serves as a base contract for inheritance.

Answer : A library is a reusable unit of code without its own state, used to share functions (such as maths helpers) among contracts.

Answer : Through a variable of that contract’s type pointing to its address, e.g. wallets[index].owner(); this performs an external message call.

Answer : Yes. Variables, arrays and parameters can have contract types (e.g. Wallet[] wallets), and they can be converted to and from addresses.

Answer : Like a class it defines state and behaviour together, supports inheritance and has a constructor; a deployed contract instance is similar to an object, except that it lives permanently on the blockchain.

Answer : The runtime bytecode is stored at the contract’s address and cannot be changed. State can change only through the contract’s own functions.

Answer : The account that called createWallet, because msg.sender is passed to the Wallet constructor.

Answer : No. A contract executes only when a transaction or another contract calls one of its functions.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. A contract in Solidity is a combination of:

Show Answer

Correct Answer : A. Functions and state at an address
Contracts bundle code and data at an address.

Q2. Which keyword deploys a contract from another contract?

Show Answer

Correct Answer : C. new
new ContractName(args) deploys a new instance.

Q3. An abstract contract:

Show Answer

Correct Answer : B. Cannot be deployed directly
Abstract contracts are bases for inheritance only.

Q4. Which unit has NO state of its own and provides reusable functions?

Show Answer

Correct Answer : D. Library
Libraries hold reusable code without state.

Q5. In this course, BOP stands for:

Show Answer

Correct Answer : A. Block Oriented Programming
The course uses BOP for contract-based blockchain programming.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Solidity Team. (n.d.). Contracts (creating contracts, visibility and getters, function modifiers, constant and immutable, functions, events, custom errors, inheritance, abstract contracts, interfaces, libraries). Solidity Documentation. https://docs.soliditylang.org/en/latest/contracts.html
  2. Solidity Team. (n.d.). Structure of a Contract. Solidity Documentation. https://docs.soliditylang.org/en/latest/structure-of-a-contract.html
  3. Solidity Team. (n.d.). Layout of a Solidity Source File (SPDX, pragmas, imports, comments). Solidity Documentation. https://docs.soliditylang.org/en/latest/layout-of-source-files.html
  4. The Linux Foundation. (n.d.). About SPDX (ISO/IEC 5962:2021). https://spdx.dev/about/
  5. OpenZeppelin. (n.d.). OpenZeppelin Contracts Documentation. https://docs.openzeppelin.com/contracts/
  6. Modi, R. (2018). Solidity Programming Essentials: A beginner’s guide to build smart contracts for Ethereum and blockchain. Packt Publishing. ISBN 978-1-78883-138-3.