Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 47 ยท Working With Contracts From Outside

Deploying to Testnet and Mainnet

Deploy a Solidity contract to a testnet and mainnet: networks, faucets, constructor arguments, source verification on explorers and key safety, with a stand-in script.

Deploying a contract means sending a special transaction whose payload is the contract's creation bytecode. The network runs that code once, stores whatever it returns as the contract's permanent code, and gives the new contract an address. After that moment the code cannot be edited. A mistake that would be a quick redeploy on your laptop becomes a permanent fact on a public chain, and it can cost real money.

That is why deployment has its own routine: rehearse on a local node, repeat on a testnet with free coins, verify the source so anyone can read it, and only then touch mainnet. This lesson walks through that routine, explains constructor arguments and verification, and covers the key-handling habits that keep your funds safe. The real tools cannot run on this website, so their commands are read-only text, followed by JavaScript stand-ins that show how the pieces fit together.

The path to mainnet

Local node Instant blocks, fake money.
Testnet A public chain with free coins.
Verify Publish source on the explorer.
Mainnet Real money, permanent code.

Every step is a cheaper place to find the same mistake.

1 / 2

Networks, RPC endpoints and chain IDs

Every Ethereum-style network has a chain ID, a number that is signed into each transaction so that a transaction made for one network cannot be replayed on another. Mainnet is chain 1. Testnets have their own IDs. Test networks are retired from time to time and replaced by new ones, so check the current recommendation in the documentation of your tools before picking one. Sepolia has been the long-running choice for application developers.

You reach a network through an RPC endpoint, a URL of a node that accepts JSON-RPC requests. You can run your own node, but most developers use a hosted provider and keep the URL (which often contains an API key) in an environment variable. Your tools use the RPC URL to read the chain and to submit signed transactions. Talking to a node from JavaScript is covered in Talking to Contracts with JavaScript.

Test coins and faucets

A testnet needs gas just like mainnet, but the coins are worthless, and you get them from a faucet, a website or service that sends a small amount of test ether to your address. Faucets limit how much you can claim per day, and some ask for a login or proof of work so bots cannot drain them. Never pay for test coins. Use a dedicated development account on testnets, never the account that holds your real funds.

A deployment script

Here is the shape of a deployment in the two most common toolchains. These blocks are read-only, because they need a node, a key and a compiler.

JavaScript
// Hardhat: scripts/deploy.js (ethers v6 style)
const { ethers } = require("hardhat");

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying with", deployer.address);

  const Voting = await ethers.getContractFactory("Voting");
  const voting = await Voting.deploy(["Red", "Blue"], 3600); // constructor args
  await voting.waitForDeployment();

  console.log("Voting at", await voting.getAddress());
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});
Terminal
# Hardhat: run the script against a network named in hardhat.config
npx hardhat run scripts/deploy.js --network sepolia

# Foundry: run a Solidity deployment script, signing with a stored keystore account
forge script script/Deploy.s.sol --rpc-url sepolia --account deployer --broadcast

The network name (sepolia) comes from a configuration file that holds the RPC URL and, for Hardhat, a reference to the key. A typical configuration reads both from environment variables so that nothing secret lives in the source file.

JavaScript
// hardhat.config.js (excerpt)
module.exports = {
  solidity: "0.8.28",
  networks: {
    sepolia: {
      url: process.env.SEPOLIA_RPC_URL,
      accounts: process.env.DEPLOYER_KEY ? [process.env.DEPLOYER_KEY] : [],
    },
  },
};

Constructor arguments

A constructor runs once, during deployment, and its arguments are not stored anywhere as such. The deployment transaction's data is the creation bytecode followed by the ABI-encoded arguments, and the constructor reads them from the end of that data. This matters later, because to verify a contract you must supply the very same arguments again. Record every argument you deploy with. A deployment script that prints the arguments, or writes them to a JSON file, saves you a painful hunt later.

The address of a new contract is not chosen by you: with a normal deployment it is computed from the deployer's address and the deployer's nonce (the number of transactions it has sent). Deploying the same code twice gives two different addresses because the nonce changed. The CREATE2 deployment method instead derives the address from the deployer, a salt and the hash of the code, which lets you know an address before deploying.

The first stand-in ties these ideas together. Be clear about what is real and what is not: the chain ID guard, the nonce-based address and the "bytecode plus encoded arguments" payload are real ideas. The hash is a tiny toy function and not keccak-256, there is no RLP encoding, and the "chain" is an object in memory.

JS A deployment script against pretend networks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same sender and the same code give a different address each time on the same network, because the nonce moved from 0 to 1. The fourth call shows why scripts for mainnet should check the chain ID: the guard stops a script that was written for one network from running on another by accident.

Verifying source code

After deployment, the explorer (Etherscan and similar sites) sees only bytecode. To let people read and trust your contract, you verify it by uploading the source and the exact compiler settings. The explorer recompiles your source, compares the result with the code on chain, and if they match it publishes the source next to the contract with a verified mark. Verified contracts also let the explorer show a readable interface for calling functions.

Verification only works if everything matches: the compiler version, the optimizer on or off and its number of runs, the EVM version, any libraries linked, and the constructor arguments. Change a single setting and the bytecode differs. Toolchains can do it for you.

Terminal
# Hardhat (with the verify plugin and an explorer API key in the config)
npx hardhat verify --network sepolia 0xYourContractAddress "arg1" "arg2"

# Foundry
forge verify-contract 0xYourContractAddress src/Voting.sol:Voting \
  --chain sepolia --constructor-args $(cast abi-encode "constructor(string[],uint256)" '["Red","Blue"]' 3600)

Command flags change between versions of these tools, so treat the lines above as the shape of the call and check the current help output before relying on them.

The second stand-in imitates what an explorer does. The compile function stands in for a compiler: it turns source and settings into a "bytecode" string. The checker recompiles and compares, so you can see which kinds of mismatch fail.

JS What an explorer does when it verifies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the idea of recompiling and comparing, and the fact that compiler version, optimizer settings and constructor arguments all matter. Stand-in: the real compiler also embeds a metadata hash at the end of the bytecode and explorers handle it with extra care. A "partial match" can happen when only that metadata differs.

Keeping your keys safe

A private key controls everything its account owns, and a leaked key cannot be rotated: the funds are simply gone. These habits cover most of the risk.

  • Never commit a key. Put keys and API URLs in environment variables or a .env file that is listed in .gitignore. Bots scan public repositories for keys within seconds of a push.
  • Use separate accounts. One throwaway account for testnets and a different, carefully guarded one for mainnet. Never reuse a key that ever touched a testnet script on a shared machine.
  • Prefer an encrypted keystore or a hardware wallet to a raw key in plain text. Most toolchains can sign through either.
  • Hand over control after launch. If your contract has an owner, transfer ownership to a multisig wallet (Project: A Multisig Wallet) instead of leaving it with the laptop that deployed it. See Modifiers and Access Control for the two-step transfer.
  • Rehearse. Run the deployment on a local node and a testnet, and where your tool supports it, against a fork of mainnet, before the real run.

Do not paste a private key or seed phrase into a chat, an issue, a screenshot or a website. Anyone who sees it can empty the account, and no support team can undo it.

A last checklist before pressing the button on mainnet: tests pass, an audit or at least a careful review is done (Audits, Tools and Best Practices), constructor arguments are double checked, the gas price is sensible, the chain ID is right, and you have written down how you will respond if something goes wrong.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a deployment script for mainnet check the chain ID?

    The chain ID identifies the network. Checking it first stops a script written for a testnet from spending real money on mainnet, or the reverse.
  2. 2. How are constructor arguments delivered during deployment?

    The deployment data is the creation bytecode followed by the encoded arguments. Because they are not stored by name afterwards, you must record them to verify the contract later.
  3. 3. Which of these can make source verification fail even though the source file is unchanged?

    Compiler version, optimizer settings, EVM version, linked libraries and constructor arguments all change the bytecode. The explorer compares bytecode, so every setting must match the deployment.
  4. 4. What is the safest place for a deployer's private key?

    Keys must never reach version control. Environment variables kept out of the repository, an encrypted keystore or a hardware wallet keep the secret out of files that get shared or published.

Summary

  • Rehearse on a local node, then a testnet funded by a faucet, and only then deploy to mainnet.
  • Each network has a chain ID and an RPC endpoint. Check the chain ID in your script before sending anything.
  • Constructor arguments are ABI-encoded after the creation bytecode. Record them, because verification needs them.
  • A contract address comes from the deployer and its nonce (or from a salt and the code hash with CREATE2).
  • Verification recompiles your source and compares bytecode, so compiler version, optimizer and arguments must match.
  • Keep keys out of source control, use separate accounts, and move ownership to a multisig after launch.

Next: Oracles, Randomness and Off-Chain Data.