Hello World (first programs) · Beginner · 16 min
Hello World in Solidity with Foundry: write, compile and test a contract locally
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Foundry 1.9.0 (forge) · Solidity 0.8.38
You will install Foundry 1.9 with foundryup, write a HelloWorld contract in Solidity 0.8.38, compile it with forge build and prove it works with forge tests that run on a local in-process EVM, with no network, wallet or money involved.
On this page
Solidity is the main language for smart contracts: programs that run on Ethereum and on the many other blockchains that use the same virtual machine, the EVM (Ethereum Virtual Machine). A contract is closer to a tiny shared database with rules than to an ordinary program. It has stored values, called state, and functions that anyone on the network can call to read or change that state.
Three things make Solidity different from the languages you may know. Once a contract is deployed to a real network, its code is public and cannot be edited: fixing a bug means deploying a new contract. Every operation costs gas, a fee paid in the network's currency, so writing data costs real money. And every source file starts with a pragma line that says which compiler versions may build it, because a contract is compiled once and then lives for years.
Because mistakes are permanent and paid for, Solidity developers test everything locally first. In this tutorial you use Foundry, a Solidity toolkit whose forge command compiles contracts and runs tests written in Solidity itself. The tests run on an EVM inside the forge process on your computer. This tutorial deploys nowhere. It needs no wallet, no account, no private key and no money, and nothing you do here touches a real blockchain.
Step 1 · Install Foundry with foundryup
A safety rule before you install anything: never paste a private key or a wallet recovery phrase into a terminal, a file or a chat, whatever a tutorial, script or person asks. Anyone who sees it controls the funds. Nothing in this tutorial asks for one.
Foundry is installed by foundryup, its official installer and version manager. Install curl, which the installer uses to download, and Git, which forge uses to fetch libraries:
sudo apt update
sudo apt install -y curl git ca-certificatesOn macOS, curl is already there and xcode-select --install gives you Git. On Windows, Foundry's installer needs Git Bash or WSL (Windows Subsystem for Linux); it does not run in PowerShell or Command Prompt. With WSL and Ubuntu, follow this tutorial as written.
Now run the official installer. It puts a single program, foundryup, in ~/.foundry/bin, inside your home folder, so you never need sudo for Foundry:
curl -L https://foundry.paradigm.xyz | bash
export PATH="$HOME/.foundry/bin:$PATH"
grep -qxF 'export PATH="$HOME/.foundry/bin:$PATH"' ~/.bashrc || echo 'export PATH="$HOME/.foundry/bin:$PATH"' >> ~/.bashrcThe export line lets the current shell find the new programs. The last line adds the same line to ~/.bashrc, so new terminals find them too, and does nothing if the line is already there.
Ask foundryup for Foundry 1.9.0 by its exact version, so you get the same tools this tutorial was written with:
foundryup --install 1.9.0
forge --versionfoundryup checks each download against the release's published attestation before installing it. It installs four tools: forge (compile and test), cast (talk to a chain from the command line), anvil (a local test chain) and chisel (a Solidity prompt for trying one line at a time). You only need forge today. To move to a newer Foundry later, run foundryup with no arguments.
If you pay for data by the bundle, the downloads happen once: this step, forge init fetching a test library, and the first build fetching the Solidity compiler. After that, building and testing work offline.
Check it worked
The installer prints foundryup was installed successfully!, followed by a hint to add ~/.foundry/bin to your PATH and then run foundryup. You do not need to paste that hint: the export and ~/.bashrc lines above already did it, and the next command runs foundryup. forge --version prints a version line containing 1.9.0, followed by a commit hash and a build date.
Troubleshooting
forge: command not found in a new terminal means ~/.foundry/bin is not on your path. Run the export PATH=... line again, or open a fresh terminal after the ~/.bashrc line is in place.
Step 2 · Create a project with forge init
Make a throwaway folder and create an empty Foundry project called hello-world inside it:
mkdir -p ~/solidity-demo
cd ~/solidity-demo
forge init hello-world --empty
cd hello-world
ls--empty skips the example Counter contract, so every file you work with is one you wrote. forge init still creates the folders and installs forge-std, Foundry's standard test library, into lib/forge-std as a Git submodule. It also runs git init, so the project is ready to commit when you want to.
src/holds your contracts.test/holds tests, which are Solidity contracts too.script/holds deployment scripts. You will not use it here.lib/holds libraries, such as forge-std.foundry.tomlis the project's settings file.
Replace foundry.toml with a version that pins the compiler. Without the solc line, forge picks a compiler that matches your pragma, which can change when new releases come out:
cat > foundry.toml <<'TOML'
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc = "0.8.38"
TOML
cat foundry.tomlsrc, out and libs name the folders for source, compiled output and libraries. solc = "0.8.38" tells forge to build with exactly Solidity 0.8.38, downloading it the first time.
Check it worked
ls shows README.md, foundry.toml, lib, script, src and test. ls lib/forge-std/src lists Test.sol among many other files.
Step 3 · Write the HelloWorld contract
Create the contract. It stores a greeting, sets it when the contract is created, and lets anyone change it:
cat > src/HelloWorld.sol <<'SOL'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;
contract HelloWorld {
string public greeting;
constructor(string memory initialGreeting) {
greeting = initialGreeting;
}
function setGreeting(string memory newGreeting) public {
greeting = newGreeting;
}
}
SOLLine by line:
// SPDX-License-Identifier: MITnames the licence of the source code. Contract source is usually published so anyone can check it, and the compiler warns if this line is missing.pragma solidity ^0.8.38;says which compilers may build this file.^0.8.38means 0.8.38 or any later 0.8 release, but not 0.9, where the language may change. An older compiler refuses the file instead of building it with different rules.contract HelloWorld { ... }declares a contract, much like a class in other languages. Everything inside belongs to it.string public greeting;declares a state variable. State is stored permanently on the chain, in the contract's own storage, and survives between calls.publicmakes the compiler write a free read function calledgreeting()for you.constructor(string memory initialGreeting)runs exactly once, when the contract is deployed, and never again.memoryis a data location: it says this text lives in temporary memory for the length of the call, unlikegreeting, which lives in permanent storage. Solidity makes you write the location for text, arrays and structs.greeting = initialGreeting;copies the text from memory into storage.function setGreeting(string memory newGreeting) publicdeclares a function that changes the greeting.publicmeans anyone can call it: any account on the network, not only the person who deployed the contract. On a real chain, every call that changes state is a transaction that costs the caller gas.
There is no main and nothing prints. A contract does nothing until someone calls it, which is why the next steps compile it and then call it from tests.
Check it worked
cat src/HelloWorld.sol prints the 14-line contract above, starting with the SPDX-License-Identifier line.
Step 4 · Compile it with forge build
Compile every contract in the project:
forge build
ls out/HelloWorld.sol
forge inspect HelloWorld abiThe first forge build downloads Solidity 0.8.38, then prints something like Compiling 1 files with Solc 0.8.38 and Compiler run successful!. Compiling turns your source into two things, both saved as JSON in out/HelloWorld.sol/HelloWorld.json:
- Bytecode: the low-level instructions the EVM runs. This is what gets deployed.
- The ABI (Application Binary Interface): a description of the contract's public functions, their inputs and outputs. Wallets, websites and tests use it to know how to call the contract.
forge inspect HelloWorld abi prints the ABI. You will see the constructor, setGreeting and a greeting function you never wrote: that is the read function public created for you.
out/ and cache/ are build output. The .gitignore that forge init wrote already keeps them out of Git.
Check it worked
forge build ends with Compiler run successful! (a warning line or two is fine, an Error is not). ls prints HelloWorld.json, and the ABI output mentions constructor, greeting and setGreeting.
Step 5 · Test it with forge test
In Foundry, tests are Solidity contracts. Each function whose name starts with test is one test, and forge test deploys your contract to its in-process EVM and calls it, fresh for every test. Create the test file:
cat > test/HelloWorld.t.sol <<'SOL'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;
import {Test} from "forge-std/Test.sol";
import {HelloWorld} from "../src/HelloWorld.sol";
contract HelloWorldTest is Test {
HelloWorld hello;
function setUp() public {
hello = new HelloWorld("Hello, world");
}
function test_InitialGreeting() public view {
assertEq(hello.greeting(), "Hello, world");
}
function test_SetGreeting() public {
hello.setGreeting("Habari, dunia");
assertEq(hello.greeting(), "Habari, dunia");
}
function test_AnyoneCanChangeTheGreeting() public {
address stranger = makeAddr("stranger");
vm.prank(stranger);
hello.setGreeting(unicode"Ndewo, ụwa");
assertEq(hello.greeting(), unicode"Ndewo, ụwa");
}
}
SOLWhat each part does:
- The two
importlines bring in forge-std'sTestcontract and yourHelloWorld.forgeknowsforge-std/meanslib/forge-std/src/. contract HelloWorldTest is Testmakes the test contract inherit fromTest, which gives itassertEq,makeAddrandvm.setUp()runs before every test.new HelloWorld("Hello, world")deploys a fresh copy of your contract on the local EVM and runs its constructor. This is a deployment, but only insideforge's memory.test_InitialGreetingreads the greeting through the freegreeting()function and checks it.viewpromises the test only reads state.test_SetGreetingchanges the greeting, in Swahili here, and checks the new value was stored.test_AnyoneCanChangeTheGreetingproves the point aboutpublic.makeAddr("stranger")makes up a new account address.vm.prank(stranger)is a Foundry cheatcode: the next call appears to come from that address. The stranger changes the greeting, and nothing stops them.unicode"Ndewo, ụwa"is Igbo for "hello, world". To type letters such asụ,ẹoré, or emoji, directly inside a string, you need theunicodeprefix: ordinary string literals accept only ASCII characters (plus escapes such as\u1EE5). Without the prefix, the compiler rejects the line. Keep this in mind if your app will greet people in Yoruba, Igbo, Amharic or French.
Run the tests:
forge testCheck it worked
The output has Ran 3 tests for test/HelloWorld.t.sol:HelloWorldTest, three lines starting [PASS], each with a gas figure, and a summary line starting Suite result: ok. 3 passed; 0 failed; 0 skipped. To see a failure, change "Habari, dunia" in the assertEq line to something else, run forge test again, and forge reports [FAIL] with the two values that did not match. Change it back afterwards.
Step 6 · Emit an event and test it
A contract cannot print. To tell the outside world that something happened, it emits an event: a record written into the transaction's log. Websites and apps watch for these logs to update their screens. Writing a log entry costs less gas than storing the same data, but contracts themselves cannot read logs back.
Rewrite the contract with an event that says who changed the greeting and to what:
cat > src/HelloWorld.sol <<'SOL'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;
contract HelloWorld {
string public greeting;
event GreetingChanged(address indexed changedBy, string newGreeting);
constructor(string memory initialGreeting) {
greeting = initialGreeting;
}
function setGreeting(string memory newGreeting) public {
greeting = newGreeting;
emit GreetingChanged(msg.sender, newGreeting);
}
}
SOLThe two new lines:
event GreetingChanged(address indexed changedBy, string newGreeting);declares the event and its fields.indexedlets apps search the logs by that field, for example "every change made by this address".emit GreetingChanged(msg.sender, newGreeting);writes the event.msg.senderis the address that called the function. Solidity fills it in for every call; it cannot be faked by the caller.
Add a second test file that checks the event:
cat > test/HelloWorldEvents.t.sol <<'SOL'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;
import {Test} from "forge-std/Test.sol";
import {HelloWorld} from "../src/HelloWorld.sol";
contract HelloWorldEventsTest is Test {
HelloWorld hello;
function setUp() public {
hello = new HelloWorld("Hello, world");
}
function test_SetGreetingEmitsEvent() public {
vm.expectEmit(address(hello));
emit HelloWorld.GreetingChanged(address(this), "Sannu, duniya");
hello.setGreeting("Sannu, duniya");
}
}
SOL
forge test
forge test --match-test test_SetGreetingEmitsEvent -vvvvvm.expectEmit(address(hello)) tells forge that the next event must come from your contract. The emit HelloWorld.GreetingChanged(...) line inside the test is not a real event; it is the event you expect, field by field. address(this) is the test contract's own address, which is the caller, so it is what msg.sender will be. Then the real call happens, and the test fails unless the contract emits a matching event.
--match-test runs only the tests whose names match, and -vvvv (four vs) prints a trace of every call, including the emitted event with its field names.
Check it worked
forge test now runs two suites: 3 passed for HelloWorldTest and 1 passed for HelloWorldEventsTest, and the old tests still pass. The -vvvv trace shows a line starting emit GreetingChanged( with changedBy: and newGreeting: "Sannu, duniya".
Step 7 · See what it costs in gas
On a real chain, every transaction pays for the work it makes the EVM do, measured in gas. Ask forge for a gas report:
forge test --gas-reportThe report has a table for HelloWorld: a deployment cost and size, then the minimum, average and maximum gas for greeting and setGreeting. Two things to notice. setGreeting costs far more than reading greeting, because writing to permanent storage is one of the most expensive things the EVM does. And a longer greeting costs more to store than a shorter one. The numbers are gas units, not money: the price of a unit changes from minute to minute on a real network. On Foundry's local EVM, none of it costs anything.
Check it worked
The table lists setGreeting with gas figures noticeably larger than those for greeting, and a Deployment Cost row for HelloWorld.
Step 8 · Read a compiler error
The Solidity compiler catches many mistakes before anything runs. Make one on purpose: a function that takes text but leaves out the data location.
cat > src/Broken.sol <<'SOL'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.38;
contract Broken {
function shout(string text) public pure returns (string memory) {
return text;
}
}
SOLBuild again. This time the build fails:
forge buildThe error names the file, the line and column, and the problem: the data location must be memory or calldata, and none was given. Delete the broken file and confirm the project builds again:
rm src/Broken.sol
forge buildMistakes beginners hit most often:
- A missing data location, as above. Text (
string),bytes, arrays and structs passed into or returned from a function needmemoryorcalldata. Source file requires different compiler version: the pragma does not match the compiler. Checkpragma solidityagainst thesolcline infoundry.toml.Invalid character in string: non-ASCII text in an ordinary string literal. Add theunicodeprefix.- A forgotten semicolon: the error points at the next line, so look one line up.
- A test function that is never run: its name does not start with
test, soforgeignores it. Check thatRan ... testsshows the number you expect.
Check it worked
The failed build mentions Broken.sol and Data location must be "memory" or "calldata". After rm, forge build finishes without errors.
Step 9 · Clean up
Delete the practice project when you are finished with it:
cd ~
rm -rf ~/solidity-demoKeep Foundry installed if you want to carry on with Solidity. To remove it completely, delete its folder and the Solidity compilers it downloaded, then open ~/.bashrc in your editor and delete the export PATH="$HOME/.foundry/bin:$PATH" line:
rm -rf ~/.foundry
rm -rf ~/.svm ~/.local/share/svmFoundry keeps compilers in ~/.svm if that folder already existed, and otherwise in your user data folder, which is ~/.local/share/svm on Linux. The second line removes whichever one you have. On macOS, the second location is ~/Library/Application Support/svm instead.
Check it worked
ls ~/solidity-demo reports No such file or directory. If you removed Foundry, forge --version in a new terminal reports command not found, and ls ~/.svm ~/.local/share/svm reports No such file or directory for both.
Next steps
Solidity is used for Ethereum smart contracts and for contracts on other EVM chains: tokens, on-chain voting, escrow and the other building blocks of decentralised apps. Before you deploy anything to a real network, even a test network, learn how wallets and keys work, keep keys out of your code and shell history, and expect every contract you publish to be read by people looking for bugs.
- Compare a language that also runs where its code is public and sandboxed: Hello World in JavaScript.
- See another strict compiler that catches mistakes before your code runs: Hello World in Rust.
- Most websites that call contracts are written in TypeScript: Hello World in TypeScript.
Related tutorials
- Hello World in JavaScript: run it in the browser and in Node.jsYou will run JavaScript in a browser console and in a web page, install Node.js 26 LTS, write and run hello.js, greet a name passed on the command line, and turn the folder into an npm project with a start script.
- Hello World in Rust: rustup, Cargo and your first crateYou will install Rust 1.100 with rustup, create and run a Cargo project, compare debug and release builds, and read a number from the keyboard with proper error handling.
- Hello World in TypeScript: catch a type error before it runsYou will install TypeScript 7 in a throwaway folder, compile and run a typed Hello World on Node.js 26, watch the compiler reject a wrong argument, and run the same file directly with Node's built-in type stripping.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials