Your first contract
Every Solidity file begins with two lines. The SPDX comment states the license, and the pragma tells the compiler which versions can build the file. The caret in ^0.8.24 means any version from 0.8.24 up to, but not including, 0.9.0.
A contract is like a class in other languages. It bundles data, called state variables, with code, called functions. When you deploy a contract, the blockchain gives it a permanent address, and anyone can call its public functions from that address.
State variables live in the contract's storage, which is saved on every node in the network. Changing one is a transaction that costs gas and must be mined into a block. Reading a variable through a view function is free when you call it from outside the chain, because no state changes.
The public keyword on count makes the compiler generate a getter function automatically. That is why you can read count from Remix or a web app without writing any extra code. The contract below also adds decrement and reset functions to show how functions share the same state.
Notice that decrement uses require. In Solidity 0.8 and later, subtracting below zero would revert anyway, but a clear message helps whoever calls your contract understand what went wrong.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; contract Counter { uint256 public count; function increment() public { count += 1; } function decrement() public { require(count > 0, "Already zero"); count -= 1; } function reset() public { count = 0; } }
Try it yourself
Add a function setCount(uint256 newCount) that sets count to any value, then compile. Next, add a second contract to the same file and see how the compiler lists both. You will reuse setCount in the Testing module.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.