Skip to main content

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:

Bash
sudo apt update
sudo apt install -y curl git ca-certificates

On 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:

Bash
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"' >> ~/.bashrc

The 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:

Bash
foundryup --install 1.9.0
forge --version

foundryup 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:

Bash
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.toml is 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:

Bash
cat > foundry.toml <<'TOML'
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc = "0.8.38"
TOML
cat foundry.toml

src, 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:

Bash
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;
    }
}
SOL

Line by line:

  • // SPDX-License-Identifier: MIT names 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.38 means 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. public makes the compiler write a free read function called greeting() for you.
  • constructor(string memory initialGreeting) runs exactly once, when the contract is deployed, and never again. memory is a data location: it says this text lives in temporary memory for the length of the call, unlike greeting, 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) public declares a function that changes the greeting. public means 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:

Bash
forge build
ls out/HelloWorld.sol
forge inspect HelloWorld abi

The 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:

Bash
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");
    }
}
SOL

What each part does:

  • The two import lines bring in forge-std's Test contract and your HelloWorld. forge knows forge-std/ means lib/forge-std/src/.
  • contract HelloWorldTest is Test makes the test contract inherit from Test, which gives it assertEq, makeAddr and vm.
  • 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 inside forge's memory.
  • test_InitialGreeting reads the greeting through the free greeting() function and checks it. view promises the test only reads state.
  • test_SetGreeting changes the greeting, in Swahili here, and checks the new value was stored.
  • test_AnyoneCanChangeTheGreeting proves the point about public. 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 the unicode prefix: 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:

Bash
forge test

Check 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:

Bash
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);
    }
}
SOL

The two new lines:

  • event GreetingChanged(address indexed changedBy, string newGreeting); declares the event and its fields. indexed lets apps search the logs by that field, for example "every change made by this address".
  • emit GreetingChanged(msg.sender, newGreeting); writes the event. msg.sender is 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:

Bash
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 -vvvv

vm.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:

Bash
forge test --gas-report

The 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.

Bash
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;
    }
}
SOL

Build again. This time the build fails:

Bash
forge build

The 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:

Bash
rm src/Broken.sol
forge build

Mistakes beginners hit most often:

  • A missing data location, as above. Text (string), bytes, arrays and structs passed into or returned from a function need memory or calldata.
  • Source file requires different compiler version: the pragma does not match the compiler. Check pragma solidity against the solc line in foundry.toml.
  • Invalid character in string: non-ASCII text in an ordinary string literal. Add the unicode prefix.
  • 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, so forge ignores it. Check that Ran ... tests shows 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:

Bash
cd ~
rm -rf ~/solidity-demo

Keep 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:

Bash
rm -rf ~/.foundry
rm -rf ~/.svm ~/.local/share/svm

Foundry 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.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.