# How to Write, Test and Deploy Your First Smart Contract on an Ethereum Testnet

Published 2026-10-23 · Crypto.world Team · Crypto.world

> A step-by-step Foundry walkthrough: install the toolchain, write and test a small Solidity contract, keep the deployer key in an encrypted keystore, get Sepolia test ether, deploy, verify the source, and what changes before mainnet.

## What You Will Build, and Which Toolchain to Use

The steps below take a reader who can program, but has never shipped a smart contract, from an empty folder to a contract running on a public Ethereum testnet with its source code verified on a block explorer. The contract is deliberately small: a noticeboard whose text only its deployer can change. Every command was checked on 23 October 2026 against the official documentation of Foundry, Solidity and ethereum.org, and run end to end on a local node.

:::callout-info **In one minute:** Install Foundry with foundryup, write the contract in src/ and its tests in test/, run forge test. Deploy to Sepolia, which ethereum.org calls the default testnet for application development. Keep the deployer key in Foundry's encrypted keystore, never in the repository or a .env file. Verify the source with forge, then check the explorer shows it as verified. :::

Two toolchains dominate Ethereum contract work. Foundry is a set of command-line tools written in Rust: its docs describe `forge` (build, test, deploy, verify), `cast` (talk to a chain), `anvil` (a local node) and `chisel` (a Solidity REPL). Tests are written in Solidity itself. Hardhat is a Node.js environment; its 3.x line, at version 3.21.0 on npm as of 22 October 2026, needs Node.js v22.13.0 or later, starts with `npx hardhat --init`, and runs both Solidity and TypeScript tests.

The steps here use Foundry, because a beginner then has one language to learn instead of two. Hardhat users can follow the same sequence: its Configuration Variables and the hardhat-keystore plugin play the role that Foundry's keystore plays below.

## Install Foundry and Pin the Compiler

Foundry's installation page lists one official installer, foundryup. On Windows it needs Git Bash or WSL; PowerShell and Command Prompt are not supported.

1. **Install foundryup.** The command below downloads and runs the installer script. If you prefer to read a script before it runs, save it with `curl -L https://foundry.paradigm.xyz -o install.sh`, open it, then run it with `bash install.sh`.

```
curl -L https://foundry.paradigm.xyz | bash
```

1. **Reload your shell.** Open a new terminal, or run `source ~/.bashrc` (or `source ~/.zshrc`).
2. **Install the tools.** `foundryup` installs the latest stable forge, cast, anvil and chisel, and the docs say it checks the SHA-256 hash of each download against the release's GitHub attestation.

```
foundryup
forge --version
```

As of 23 October 2026 the current stable release is v1.8.6, dated 21 October 2026 in Foundry's changelog. Your version will be newer later; run `foundryup` again to update.

1. **Create the project.** `forge init` makes a git repository with `src/`, `test/` and `script/` folders, installs the forge-std library, and adds example Counter files you can delete.

```
forge init noticeboard
cd noticeboard
rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol
```

1. **Pin the compiler.** Foundry auto-detects a Solidity version from your files unless you pin one. As of 23 October 2026, Solidity 0.8.38 is the newest release: the Solidity team announced it on 22 October 2026, and docs.soliditylang.org serves a v0.8.38 edition. Before you start, check the release list on soliditylang.org/blog and pick the version it shows. Add one line to `foundry.toml`:

```
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.38"
```

The Solidity docs explain that a pragma such as `^0.5.2` accepts any later compiler up to the next breaking release, so "bugfix releases are still possible". For a contract you will deploy and verify, an exact pragma plus `solc_version` means the bytecode you tested, deployed and verified comes from one compiler.

## Write the Contract

Create `src/Noticeboard.sol`:

```
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

/// @notice A one-line public notice that only the deployer can change.
contract Noticeboard {
address public immutable owner;
string public notice;

event NoticeChanged(address indexed by, string newNotice);

error NotOwner();

constructor() {
owner = msg.sender;
}

function setNotice(string calldata newNotice) external {
if (msg.sender != owner) revert NotOwner();
notice = newNotice;
emit NoticeChanged(msg.sender, newNotice);
}
}
```

The constructor runs once, at deployment, and records whoever sent the deploying transaction as `owner`; `immutable` means that value is fixed into the deployed code and can never change. Declaring `owner` and `notice` as `public` makes the compiler generate getter functions, so anyone can read them. `setNotice` is the only function that writes, and it reverts with the custom error `NotOwner` when anyone else calls it.

That check is the simplest form of what ethereum.org's security guide calls access control, the first item in its list of guidelines. The event gives explorers and apps a log entry to show each time the notice changes. Build it once to confirm the compiler downloads and compiles:

```
forge build
```

## Test the Contract Locally

Foundry's testing docs set the conventions: test files end in `.t.sol`, test contracts inherit from forge-std's `Test`, test functions start with `test`, and `setUp()` runs before each test. Create `test/Noticeboard.t.sol`:

```
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {Test} from "forge-std/Test.sol";
import {Noticeboard} from "../src/Noticeboard.sol";

contract NoticeboardTest is Test {
Noticeboard board;
address stranger = makeAddr("stranger");

function setUp() public {
board = new Noticeboard();
}

function test_DeployerIsOwner() public view {
assertEq(board.owner(), address(this));
}

function test_OwnerCanSetNotice() public {
board.setNotice("hello, testnet");
assertEq(board.notice(), "hello, testnet");
}

function test_RevertWhen_CallerIsNotOwner() public {
vm.prank(stranger);
vm.expectRevert(Noticeboard.NotOwner.selector);
board.setNotice("not yours");
}

function test_EmitsNoticeChanged() public {
vm.expectEmit(address(board));
emit Noticeboard.NoticeChanged(address(this), "hello");
board.setNotice("hello");
}

function testFuzz_OwnerCanSetAnyNotice(string calldata text) public {
board.setNotice(text);
assertEq(board.notice(), text);
}
}
```

`vm.prank` makes the next call come from another address, which is how the test proves a stranger is refused. `vm.expectRevert` passes only if the next call reverts with the named error. A test function that takes parameters is fuzzed: Forge feeds it random inputs, 256 runs by default. Run the suite:

```
forge test
```

On Foundry 1.8.6 with solc 0.8.38 all five tests pass. When one fails, `forge test -vvv` prints a trace of the failing call. Foundry's best-practices page also suggests running `forge lint` and `forge fmt --check` before you ship anything.

## Create a Deployer Key That Never Touches the Repo

A deployment is a transaction, so it needs a funded account and a private key to sign with. Make a fresh one for testnets only. ethereum.org's page on networks says that "for security considerations, it's not recommended to reuse mainnet accounts on testnets or vice versa."

Foundry's best-practices page says where that key should live: "Store keys encrypted, not as plaintext environment variables". Its keystore saves the key encrypted under `~/.foundry/keystores`, outside your project.

1. **Generate the key straight into the keystore.** You are asked for a password, and the key is never printed. The command prints the new address.

```
cast wallet new deployer
cast wallet list
```

If you already have a testnet-only key, `cast wallet import deployer --interactive` prompts for it instead of taking it on the command line, where it would land in your shell history.

1. **Read the address back when you need it.** The command asks for the keystore password.

```
cast wallet address --account deployer
```

1. **Put only the non-key settings in `.env`.** You need two values: an RPC endpoint for Sepolia (from a node provider account, or a public endpoint; Foundry's deploy guide uses `https://sepolia.drpc.org` in its example) and an Etherscan API key. Etherscan's docs say a free key, created at etherscan.io/myapikey after registering, works across all its supported chains.

```
# .env (never commit this file)
SEPOLIA_RPC_URL=https://sepolia.drpc.org
ETHERSCAN_API_KEY=your_key_here
```

1. **Check git ignores it.** The `.gitignore` that `forge init` writes already lists `.env`, `cache/` and `out/`; the command below should print the matching rule. Commit a `.env.example` with empty values so others know which variables to set.

```
git check-ignore -v .env
```

Do not copy the private key that `anvil` prints into any of this. Foundry's docs warn: "Never use Anvil's default keys on public networks. They are publicly known."

## Choose Sepolia and Get Test Ether Without Giving Away Data

ethereum.org names two public testnets that client developers currently maintain, Sepolia and Hoodi, and gives them different jobs. Sepolia is "the recommended default testnet for application development"; Hoodi is for testing validating, staking and protocol upgrades. Holesky, an older testnet, is marked deprecated since September 2025. A contract developer should therefore deploy to Sepolia, chain ID 11155111.

Test ether has no value, but you still need some to pay for gas. ethereum.org's Sepolia section lists a set of faucets, and their conditions differ. Before using one, read what it asks for:

1. **Give an address, nothing else.** A faucet needs only your public address. Any page asking for a private key, a seed phrase, or a wallet signature that approves spending is not a faucet you should use.
2. **Watch for mainnet-balance checks.** Alchemy's Sepolia faucet page, checked on 23 October 2026, requires at least 0.001 ETH and some activity on Ethereum Mainnet at the receiving address. Meeting that would link your testnet address to a mainnet one, which the reuse advice above argues against.
3. **Prefer faucets that ask only for work or a wait.** The PoW faucet at sepolia-faucet.pk910.de, linked from ethereum.org, asks you to enter an address and let your browser do some mining in exchange for test ether.
4. **Confirm it arrived.**

```
set -a; source .env; set +a
cast balance $(cast wallet address --account deployer) --ether --rpc-url "$SEPOLIA_RPC_URL"
```

`set -a` exports every variable the file defines, so forge and cast can read `ETHERSCAN_API_KEY` from the environment, as their docs say they do.

## Simulate, Deploy to Sepolia and Call the Contract

Create the deployment script `script/Deploy.s.sol`. Scripts end in `.s.sol` and inherit from forge-std's `Script`; calls at the current call depth between `vm.startBroadcast()` and `vm.stopBroadcast()`, excluding cheatcode calls, create transactions that can later be signed and sent onchain.

```
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {Script, console} from "forge-std/Script.sol";
import {Noticeboard} from "../src/Noticeboard.sol";

contract DeployScript is Script {
function run() public {
vm.startBroadcast();
Noticeboard board = new Noticeboard();
vm.stopBroadcast();
console.log("Noticeboard deployed at:", address(board));
console.log("Chain ID:", block.chainid);
}
}
```

1. **Simulate against Sepolia.** Without `--broadcast`, forge runs the script against the live chain state and sends nothing. It prints the predicted address and the gas estimate, then ends with "SIMULATION COMPLETE. To broadcast these transactions, add --broadcast and wallet configuration(s) to the previous command."

```
forge script script/Deploy.s.sol --account deployer --rpc-url "$SEPOLIA_RPC_URL"
```

1. **Deploy and verify in one run.** Adding `--broadcast` sends the transaction, signed with the keystore after you type its password; `--verify` submits the source to Etherscan once the deployment is confirmed.

```
forge script script/Deploy.s.sol --account deployer --rpc-url "$SEPOLIA_RPC_URL" --broadcast --verify
```

1. **Find the record.** The address is in the log, and the transactions are saved in `broadcast/Deploy.s.sol/11155111/run-latest.json`. The template's `.gitignore` keeps local (chain 31337) and dry-run logs out of git but not testnet ones, so that file will be committed; it holds public data only. The RPC URL goes to a separate "sensitive values" file under `cache/`, which git ignores.
2. **Call the contract.** Replace the address with yours.

```
cast call 0xYourContract "owner()(address)" --rpc-url "$SEPOLIA_RPC_URL"
cast send 0xYourContract "setNotice(string)" "hello, testnet" --account deployer --rpc-url "$SEPOLIA_RPC_URL"
cast call 0xYourContract "notice()(string)" --rpc-url "$SEPOLIA_RPC_URL"
```

The first call should return your deployer address. If you want a rehearsal with no faucet at all, run `anvil` in a second terminal, send the deployer some of Anvil's local test ether, and point the same commands at `http://127.0.0.1:8545`.

## Verify the Source on a Block Explorer

ethereum.org defines source code verification as comparing a contract's source code with "the compiled bytecode used during the contract creation". Until it is done, an explorer shows only bytecode, which is harder to understand than source code.

If `--verify` failed or you skipped it, verify the deployed address on its own. The first form uses Etherscan and needs `ETHERSCAN_API_KEY` in the environment; `--watch` waits for the result. The second uses Sourcify, which needs no key.

```
forge verify-contract 0xYourContract src/Noticeboard.sol:Noticeboard --chain sepolia --watch
forge verify-contract 0xYourContract src/Noticeboard.sol:Noticeboard --chain sepolia --verifier sourcify
```

Then open sepolia.etherscan.io from a bookmark or by typing it, search the address, and check the Contract tab shows your source. The two services do not check the same thing. ethereum.org explains that Etherscan does not compare the metadata hash at the end of the bytecode, so its matches are "partial matches", while a "full match" also confirms that the compilation metadata matches.

The usual failure is a mismatch: Etherscan's docs say both "source code and compiler settings" must "exactly match the deployment conditions". Pinning the compiler earlier avoids most of these. A contract with constructor arguments also needs them ABI-encoded with `--constructor-args`, which Noticeboard avoids by taking none.

## What Changes Before Mainnet

On a testnet a bug costs a redeploy and some free test ether. On mainnet the deployed code keeps running as written, and ethereum.org's security guide states the consequence:

> Deployed contract code usually cannot be changed to patch security flaws, while assets stolen from smart contracts are extremely difficult to track and mostly irrecoverable due to immutability. — ethereum.org, Smart contract security

Upgrade patterns such as proxies exist, but ethereum.org notes that they may take time to implement and often require approval from different parties, which "only gives attackers more time to cause more damage." Before any mainnet deployment of a contract that will hold value, work through the review that the official guides describe:

1. **Independent review.** ethereum.org suggests commissioning an audit and, separately, a bug bounty, while warning against treating audits as "a silver bullet" because they will not catch every bug.
2. **The development checklist.** From the same guide: code in version control, every change through a pull request with at least one independent reviewer, static analysis tools run before merging, and a build with no compiler errors or warnings.
3. **Tests beyond unit tests.** ethereum.org recommends combining unit tests with property-based testing such as fuzzing; Foundry's best practices add running `forge test -vvvv` at least once and testing access control and edge cases.
4. **Compiler bugs.** The Solidity docs warn that even bug-free code can be hit by a compiler bug, and keep a list of known bugs. Check it, and the Solidity blog's security alerts, for the version you pinned.
5. **Limit what is at stake.** The Solidity docs recommend restricting the amount of ether a contract holds, so that a bug in the code, the compiler or the platform loses less.
6. **Keys.** Foundry's docs map local development to Anvil's keys, testnets to an encrypted keystore, and mainnet to a hardware wallet, used with `--ledger` in place of `--account`.
7. **Exact settings.** Verify mainnet deployments with the same compiler version and settings you tested with, as Foundry's pre-ship list says.

Whatever the network, finish each deployment with the same check: run `cast code 0xYourContract --rpc-url "$SEPOLIA_RPC_URL"` and confirm it returns bytecode rather than `0x`, then open the address on the explorer and confirm the Contract tab shows your verified source.

## Sources

1. [Foundry docs: Installation](https://www.getfoundry.sh/introduction/installation) getfoundry.sh
2. [Foundry docs: Testing](https://www.getfoundry.sh/forge/testing) getfoundry.sh
3. [Foundry docs: Deploying Contracts](https://www.getfoundry.sh/guides/deploying-contracts) getfoundry.sh
4. [Foundry docs: Best Practices](https://www.getfoundry.sh/best-practices) getfoundry.sh
5. [Foundry reference: forge verify-contract](https://www.getfoundry.sh/reference/forge/verify-contract) getfoundry.sh
6. [Foundry reference: cast wallet new](https://www.getfoundry.sh/reference/cast/wallet/new) getfoundry.sh
7. [Foundry changelog (v1.8.6, 21 October 2026)](https://www.getfoundry.sh/changelog) getfoundry.sh
8. [Solidity blog: Solidity 0.8.38 Release Announcement](https://www.soliditylang.org/blog/2026/10/22/solidity-0.8.38-release-announcement/) soliditylang.org
9. [Solidity docs v0.8.38: Layout of a Solidity Source File (version pragma)](https://docs.soliditylang.org/en/v0.8.38/layout-of-source-files.html) docs.soliditylang.org
10. [Solidity docs v0.8.38: Security Considerations](https://docs.soliditylang.org/en/v0.8.38/security-considerations.html) docs.soliditylang.org
11. [ethereum.org: Networks (testnets, faucets)](https://ethereum.org/developers/docs/networks/) ethereum.org
12. [ethereum.org: Smart contract security](https://ethereum.org/developers/docs/smart-contracts/security/) ethereum.org
13. [ethereum.org: Verifying smart contracts](https://ethereum.org/developers/docs/smart-contracts/verifying/) ethereum.org
14. [Etherscan docs: Set Up Your API Key](https://docs.etherscan.io/set-up-your-api-key) docs.etherscan.io
15. [Etherscan docs: Common Verification Errors](https://docs.etherscan.io/contract-verification/common-verification-errors) docs.etherscan.io
16. [Sourcify docs: Verify via Foundry](https://docs.sourcify.dev/docs/verify-via-foundry) docs.sourcify.dev
17. [Hardhat docs: Getting started (Hardhat 3)](https://hardhat.org/docs/getting-started) hardhat.org
18. [Alchemy Sepolia faucet page (eligibility requirements)](https://www.alchemy.com/faucets/ethereum-sepolia) alchemy.com
19. [Sepolia PoW Faucet (linked from ethereum.org)](https://sepolia-faucet.pk910.de/) sepolia-faucet.pk910.de
20. [Sepolia Resources (chain ID 11155111)](https://sepolia.dev/) sepolia.dev

## Related stories

- [How to Run a Bitcoin Full Node at Home](https://crypto.world/implementation/how-to-run-a-bitcoin-full-node-at-home)
- [How to Check and Revoke Token Approvals on Ethereum and EVM Chains](https://crypto.world/implementation/how-to-check-and-revoke-token-approvals-ethereum-evm)
- [How to Check Whether a Crypto Company Is MiCA-Authorised](https://crypto.world/implementation/check-crypto-company-mica-authorisation)

## Explore

[More articles](https://crypto.world/implementation)

---

Canonical: https://crypto.world/implementation/how-to-write-test-deploy-first-smart-contract-ethereum-testnet
