A Solidity smart contract is mainly made of a pragma (version) line, the contract declaration, state variables, a constructor, functions, function modifiers, events, and user-defined types (structs, enums, mappings), plus error handling.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0; // 1. version pragma
contract Bank { // 2. contract
address public owner; // 3. state variables
mapping(address => uint) public balance; // mapping
struct Txn { address from; uint amount; } // 4. struct
enum Status { Active, Closed } // enum
Status public status;
event Deposited(address indexed who, uint amount); // 5. event
modifier onlyOwner() { // 6. modifier
require(msg.sender == owner, "Not owner");
_;
}
constructor() { // 7. constructor
owner = msg.sender;
status = Status.Active;
}
function deposit() public payable { // 8. functions
require(msg.value > 0, "Send ether"); // 9. error handling
balance[msg.sender] += msg.value;
emit Deposited(msg.sender, msg.value);
}
function close() public onlyOwner {
status = Status.Closed;
}
}
- Pragma: fixes the compiler version; the SPDX line states the licence.
- Contract: like a class; deployed at its own address on the blockchain.
- State variables: stored permanently in contract storage (costs gas), e.g.
owner,balance. - Data types: value types (
uint,bool,address), and reference/user-defined types:struct,enum, arrays,mapping(key–value store). - Events: logs emitted with
emit; front ends listen to them. - Modifiers: reusable checks run before a function body (
_marks where the body runs). - Constructor: runs once at deployment to initialise state.
- Functions: with visibility (
public,external,internal,private) and state mutability (view,pure,payable). Special functionsreceive()andfallback()handle plain ether transfers and unknown calls. - Error handling:
require,revert,assertand custom errors undo the transaction when a condition fails.
Contracts can also use inheritance (is), interfaces and libraries for reuse, and global variables such as msg.sender, msg.value and block.timestamp.