1. Write your first clean contract
5 min
One clean idea
A smart contract is code plus data at an Ethereum address. Your first goal is not to add many features. Your goal is to make the state and the allowed changes obvious.
A recruiter or hackathon judge should understand your contract in one minute, before reading your tests.
What to include
A Solidity contract can contain state variables, functions, modifiers, events, errors, structs, enums, and inheritance. In this first lesson, keep it smaller: state, constructor, function, event, and custom error.
Use Solidity 0.8.x. Do not add pragma experimental ABIEncoderV2. It is an old pattern because ABI coder v2 is already the default in Solidity 0.8.x.
First contract
This example stores one project profile. It is like a mini on-chain record for a HackIndia submission. It has one owner, one public title, and a way to update the title.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.37;
contract ProjectProfile {
address public immutable owner;
string public title;
error NotOwner(address caller);
error EmptyTitle();
event TitleUpdated(string oldTitle, string newTitle);
constructor(string memory initialTitle) {
if (bytes(initialTitle).length == 0) {
revert EmptyTitle();
}
owner = msg.sender;
title = initialTitle;
}
function updateTitle(string calldata newTitle) external {
if (msg.sender != owner) {
revert NotOwner(msg.sender);
}
if (bytes(newTitle).length == 0) {
revert EmptyTitle();
}
string memory oldTitle = title;
title = newTitle;
emit TitleUpdated(oldTitle, newTitle);
}
}