← Back to the blog
Lesson 7: Testnet Deployment and Verification

X ArticleWeb3

Lesson 7: Testnet Deployment and Verification

Source: https://x.com/i/status/2110719292945977524

Learning goals: complete a testnet deployment, source-code verification, ABI export, and frontend integration.

Previous lesson

Lesson outline

Configure environment variables

🧪 First add the tests

🚀 Write a deployment script

🌐 Deploy to Sepolia

✅ Verify the source on Etherscan

🧾 Export the ABI for the frontend

⚛️ React frontend integration: use wagmi + viem

🔌 Configure wagmi

🔗 Connect a wallet

📖 Read on-chain data

✍️ Write on-chain: call increment

🧰 Use cast for on-chain troubleshooting

🐛 Common pitfalls, filled in one by one

🧼 A few best practices for the testnet stage

📦 A more convenient “graduation” directory structure

🧭 Acceptance criteria for this lesson

Configure environment variables

Create a .env in the project root:

Don’t commit .env to Git.

Check whether .gitignore includes:

Enable environment variables and the verifier in foundry.toml

Open foundry.toml and change it to this:

A few things here:

rpc_endpoints lets you later write --rpc-url sepolia directly

etherscan lets forge verify-contract and --verify work directly

solc_version is best aligned with your contract’s pragma, to hit fewer pitfalls

🧪 First add the tests

You can deploy without writing tests. But once you are really on-chain, changing things means spending more gas. A testnet doesn’t cost real money, but don’t get into the habit of deploying with no tests.

Create test/Counter.t.sol:

Run the tests:

See all green before you continue. Tests aren’t window dressing; this step can catch many elementary mistakes early.

🚀 Write a deployment script

Foundry deployment scripts usually go in the script/ directory.

Create script/DeployCounter.s.sol:

The core here is just two steps:

vm.envUint("PRIVATE_KEY") reads the private key from .env

Operations after vm.startBroadcast(...) will actually send transactions to the chain

🌐 Deploy to Sepolia

First run a simulated execution and see whether the script has problems:

This step usually does not actually broadcast; it is only a local simulation. If the output looks normal, then send it for real.

Broadcast the deployment for real

If everything is normal, you will see in the output:

The deployment transaction hash

The new contract address

An execution record under the broadcast directory

Where to look at the broadcast record

Foundry will generate a directory something like this:

11155111 is Sepolia’s chain id.

This file is very useful. Inside it you can usually see:

The actually deployed contract address

Transaction information

The sender address

The nonce

Don’t copy the address by hand every time; it is easy to copy it wrong. Later, when the frontend integrates, take it directly from here.

✅ Verify the source on Etherscan

After a successful deployment, the next step is verification. It will still work if you don’t verify, but when others open the contract address they will only see bytecode, which is a poor experience. You will also have a hard time when debugging the frontend.

Method 1: verify along with the deployment

Foundry supports doing it in one go:

If this is your first run, the suggestion is to deploy only first, then verify manually. Because when verification fails, the logs are rather messy, and beginners can easily get confused.

Method 2: verify manually

Suppose your contract address is:

Run:

If the constructor has parameters, you have to encode the parameters and include them.

Our constructor is:

What was passed at deployment was 0, so when verifying you need to add the constructor arguments.

First encode them:

You will get a hex result, for example:

Then verify:

Waiting for the verification result

After submitting, you can check the status:

Sometimes Foundry will output the verification result directly. Sometimes it only gives you a GUID, in which case you use that to look it up.

🧾 Export the ABI for the frontend

For the frontend to interact with the contract, you need at least two things:

The contract address

The ABI

Where is the ABI

After compilation, the ABI will be at:

Open this file, and there is a lot of content inside. What the frontend commonly uses is the abi field.

You can also extract it directly with a command:

Or copy the abi section by hand.

Create a frontend config file

Suppose you have a React project. In the frontend, create:

And write:

⚛️ React frontend integration: use wagmi + viem

This combination is very common in Web3 frontends now:

wagmi: a React hooks wrapper

viem: the underlying library for chain interaction

MetaMask: the wallet entry point

It is more convenient than the old ethers + a pile of self-written state management.

Install the dependencies

In the frontend project, run:

If you need to add a wallet connector, also install:

In many scaffolded projects React Query is already there; if not, add it.

🔌 Configure wagmi

Create src/web3/config.ts:

Then wrap a Provider layer in the entry file.

src/main.tsx or src/index.tsx:

🔗 Connect a wallet

First make the most basic connect button.

In src/App.tsx, first write a version:

Pitfalls that are easy to hit at this step

The browser doesn’t have MetaMask installed

MetaMask is not switched to Sepolia

The wallet doesn’t have test networks shown

In some versions of wagmi the way connectors are written differs

If injected() reports a type problem, first look at the docs for the wagmi version you installed; don’t copy old code rigidly.

📖 Read on-chain data

Next, read number.

Refactor src/App.tsx:

If you can’t read a value here, check these first:

Whether the address is the one that was deployed

Whether the ABI is correct

Whether the current chain is Sepolia

Whether the contract was in fact deployed successfully

✍️ Write on-chain: call increment

Once reads work, then write.

Continue adding to src/App.tsx:

What this code does

useWriteContract sends the transaction

The user will confirm in MetaMask

useWaitForTransactionReceipt waits for the transaction to land on-chain

After success you can refetch() once, to pull the latest value back

To make it a bit more convenient, you can refresh automatically after the transaction is confirmed:

Then add:

🧰 Use cast for on-chain troubleshooting

When the frontend goes red, don’t only stare at the browser console. cast is a very useful command-line troubleshooting tool, and is often faster than opening a page and clicking around for a long time.

Look up the current number

Look up the owner

Look up the details of a transaction

Check whether there is code at the deployed address

If it returns 0x, there is no contract at this address. Either you copied the address wrong, or the deployment never succeeded at all.

🐛 Common pitfalls, filled in one by one

This part is important. A lot of people don’t fail because they can’t write; they get tripped repeatedly by these small pitfalls.

  1. insufficient funds for gas * price + value

There is no test ETH in the wallet.

What to do:

Go to a faucet and claim Sepolia ETH

Confirm that what you claimed is for the current deployment wallet address

Confirm that the wallet is switched to Sepolia, not some other network

2. EvmError: Revert

This means execution on-chain rolled back.

The order of investigation:

Whether the constructor was passed the wrong arguments

Whether there is a require in the contract function

Whether the current calling account has permission

Whether the types of the frontend arguments are wrong

If the function signature is uint256, and the frontend passes a string, an empty value, or a negative number, things can go wrong.

3. Etherscan verification failed

The most common reasons:

The compiler version is inconsistent

The optimizer configuration is inconsistent

The constructor arguments were omitted

The contract path was written wrong

You changed the code but did not redeploy

Whatever configuration you used for deployment, verification has to be exactly the same. The most annoying point here is that “close enough” is not enough; it has to be completely consistent.

4. The frontend can’t read the contract

Focus on checking four items:

The contract address

The ABI

The chain ID

The RPC network status

Especially the ABI. As soon as you change a contract function and don’t update the ABI, the frontend starts acting up.

5. The wallet is connected, but nothing happens when you click the button

Common causes:

writeContract was not triggered

You are stuck on the button’s disabled state

The wallet popup was blocked by the browser

The current chain is not Sepolia

The MetaMask account was not switched correctly

The dumbest but most effective way to investigate this kind of problem:

Open the browser console

Log before and after the click

See whether a hash was generated

See whether MetaMask popped a confirmation

  1. Private key must be 32 bytes

The private-key format in .env is wrong.

In general, watch for:

Some tools require a leading 0x

Some reads will not accept odd whitespace

Don’t also copy the quotes in

A common Foundry practice is to put the hex private key in directly, with a cleaner format.

🧼 A few best practices for the testnet stage

This part is not required, but it can help you do less rework.

Keep a dedicated test wallet separate

Don’t cut corners. A test wallet is a test wallet; isolate it from the main wallet.

Don’t hard-code the contract address everywhere

Put it in a single config file on the frontend. This is especially important with multiple environments; otherwise, when an address changes later, you will be searching the whole project for a long time.

You can structure it like this:

Keep a record of deployment parameters

Today you deployed with 0; next week you may deploy with 100. Don’t rely on your memory; write the parameters into the script, or into a deployment-record file.

After every deployment, immediately do three things

Write down the contract address

Verify the source

Use cast call to read the key state once

Once these three actions are done, frontend integration later will save you a lot of trouble.

📦 A more convenient “graduation” directory structure

If you plan to keep building this project, the directories can be organized like this:

That way, finding things is not a chore.

🧭 Acceptance criteria for this lesson

Only when you have done the following do you count as having graduated; “close enough” is not enough.

The on-chain part

forge build succeeds

forge test succeeds

forge script ... --broadcast succeeds

You can get a clear contract address

Etherscan can show the verified source

The frontend part

MetaMask can connect

The page can read number

Clicking the button can submit increment

After the transaction is confirmed, the value on the page can refresh

The block explorer can look up this transaction

Troubleshooting ability

You can at least use these commands:

Once this set of things is working end to end, you are no longer someone who “can write a Solidity demo to play with locally”; you can already throw a minimal DApp onto a testnet and have it run.

If you continue from here, it is usually:

Add access control

Hook up event listening

Do multi-contract deployment

Add ERC-20 / NFTs

Hook up signature login

Make the frontend wallet state and transaction state complete

First fill this lesson out. Once you have passed the gate of testnet deployment and verification, the work that follows can be considered the real subject.

Code snippets from the article

The following code comes from code blocks in the original X Article, arranged in the order they appeared.

export const COUNTER_ADDRESS = "0xYourContractAddress";

export const COUNTER_ABI = [
  {
    "type": "constructor",
    "inputs": [
      {
        "name": "_initialNumber",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "type": "event",
    "name": "NumberChanged",
    "inputs": [
      {
        "name": "newNumber",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "type": "function",
    "name": "increment",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "type": "function",
    "name": "number",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "type": "function",
    "name": "owner",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "address"
      }
    ],
    "stateMutability": "view"
  },
  {
    "type": "function",
    "name": "setNumber",
    "inputs": [
      {
        "name": "_number",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  }
] as const;
forge verify-contract \
  0xYourContractAddress \
  src/Counter.sol:Counter \
  --chain sepolia
cast call 0xYourContractAddress "number()(uint256)" --rpc-url sepolia
import {
  useAccount,
  useConnect,
  useDisconnect,
  useReadContract,
  useWriteContract,
  useWaitForTransactionReceipt,
} from "wagmi";
import { injected } from "wagmi/connectors";
import { COUNTER_ABI, COUNTER_ADDRESS } from "./contracts/counter";

function App() {
  const { address, isConnected } = useAccount();
  const { connect } = useConnect();
  const { disconnect } = useDisconnect();

  const { data, isLoading, refetch } = useReadContract({
    address: COUNTER_ADDRESS,
    abi: COUNTER_ABI,
    functionName: "number",
  });

  const { data: hash, writeContract, isPending } = useWriteContract();

  const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({
    hash,
  });

  return (
    <div style={{ padding: 24 }}>
      <h1>Counter DApp</h1>

      {isConnected ? (
        <>
          <p>Connected address: {address}</p>
          <button onClick={() => disconnect()}>Disconnect wallet</button>
        </>
      ) : (
        <button onClick={() => connect({ connector: injected() })}>
          Connect MetaMask
        </button>
      )}

      <hr />

      <h2>Current number</h2>
      {isLoading ? <p>Reading...</p> : <p>{String(data)}</p>}

      <button onClick={() => refetch()}>Refresh manually</button>

      <hr />

      <button
        disabled={!isConnected || isPending || isConfirming}
        onClick={() =>
          writeContract({
            address: COUNTER_ADDRESS,
            abi: COUNTER_ABI,
            functionName: "increment",
          })
        }
      >
        {isPending ? "Waiting for wallet confirmation..." : isConfirming ? "Confirming on-chain..." : "Add 1"}
      </button>

      {hash && <p>Transaction hash: {hash}</p>}
      {isSuccess && <p>The transaction is on-chain</p>}
    </div>
  );
}

export default App;
forge build
forge test
forge script
forge verify-contract
cast call
cast tx
cast code
PRIVATE_KEY=your_test_wallet_private_key
SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/your_key
ETHERSCAN_API_KEY=your_etherscan_api_key
src/contracts/counter.ts
0xYourContractAddress
import { useAccount, useConnect, useDisconnect } from "wagmi";
import { injected } from "wagmi/connectors";

function App() {
  const { address, isConnected } = useAccount();
  const { connect } = useConnect();
  const { disconnect } = useDisconnect();

  return (
    <div style={{ padding: 24 }}>
      <h1>Counter DApp</h1>

      {isConnected ? (
        <>
          <p>Connected address: {address}</p>
          <button onClick={() => disconnect()}>Disconnect wallet</button>
        </>
      ) : (
        <button onClick={() => connect({ connector: injected() })}>
          Connect MetaMask
        </button>
      )}
    </div>
  );
}

export default App;
0x0000000000000000000000000000000000000000000000000000000000000000
cast call 0xYourContractAddress "owner()(address)" --rpc-url sepolia
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Script} from "forge-std/Script.sol";
import {Counter} from "../src/Counter.sol";

contract DeployCounter is Script {
    function run() external returns (Counter) {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");

        vm.startBroadcast(deployerPrivateKey);
        Counter counter = new Counter(0);
        vm.stopBroadcast();

        return counter;
    }
}
constructor(uint256 _initialNumber)
.env
cache
out
broadcast
import { useAccount, useConnect, useDisconnect, useReadContract } from "wagmi";
import { injected } from "wagmi/connectors";
import { COUNTER_ABI, COUNTER_ADDRESS } from "./contracts/counter";

function App() {
  const { address, isConnected } = useAccount();
  const { connect } = useConnect();
  const { disconnect } = useDisconnect();

  const { data, isLoading, refetch } = useReadContract({
    address: COUNTER_ADDRESS,
    abi: COUNTER_ABI,
    functionName: "number",
  });

  return (
    <div style={{ padding: 24 }}>
      <h1>Counter DApp</h1>

      {isConnected ? (
        <>
          <p>Connected address: {address}</p>
          <button onClick={() => disconnect()}>Disconnect wallet</button>
        </>
      ) : (
        <button onClick={() => connect({ connector: injected() })}>
          Connect MetaMask
        </button>
      )}

      <hr />

      <h2>Current number</h2>
      {isLoading ? <p>Reading...</p> : <p>{String(data)}</p>}

      <button onClick={() => refetch()}>Refresh manually</button>
    </div>
  );
}

export default App;
npm install wagmi viem @tanstack/react-query
forge test
cat out/Counter.sol/Counter.json
forge script script/DeployCounter.s.sol:DeployCounter \
  --rpc-url sepolia \
  --broadcast \
  --verify
export const CONTRACTS = {
  sepolia: {
    counter: "0xYourContractAddress",
  },
};
npm install @wagmi/core
cast abi-encode "constructor(uint256)" 0
forge verify-check <GUID> --chain sepolia
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.24"
optimizer = true
optimizer_runs = 200

[rpc_endpoints]
sepolia = "${SEPOLIA_RPC_URL}"

[etherscan]
sepolia = { key = "${ETHERSCAN_API_KEY}" }
cast tx 0xTransactionHash --rpc-url sepolia
useEffect(() => {
  if (isSuccess) {
    refetch();
  }
}, [isSuccess, refetch]);
import React from "react";
import ReactDOM from "react-dom/client";
import { WagmiProvider } from "wagmi";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { config } from "./web3/config";
import App from "./App";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <App />
      </QueryClientProvider>
    </WagmiProvider>
  </React.StrictMode>
);
out/Counter.sol/Counter.json
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

contract CounterTest is Test {
    Counter counter;

    function setUp() public {
        counter = new Counter(10);
    }

    function test_InitialNumber() public {
        assertEq(counter.number(), 10);
    }

    function test_SetNumber() public {
        counter.setNumber(42);
        assertEq(counter.number(), 42);
    }

    function test_Increment() public {
        counter.increment();
        assertEq(counter.number(), 11);
    }
}
forge script script/DeployCounter.s.sol:DeployCounter --rpc-url sepolia
cast code 0xYourContractAddress --rpc-url sepolia
forge verify-contract \
  0xYourContractAddress \
  src/Counter.sol:Counter \
  --chain sepolia \
  --constructor-args 0x0000000000000000000000000000000000000000000000000000000000000000
broadcast/DeployCounter.s.sol/11155111/run-latest.json
import { useEffect } from "react";
import { http, createConfig } from "wagmi";
import { sepolia } from "wagmi/chains";

export const config = createConfig({
  chains: [sepolia],
  transports: {
    [sepolia.id]: http(),
  },
});
foundry-counter/
├── src/
│   └── Counter.sol
├── script/
│   └── DeployCounter.s.sol
├── test/
│   └── Counter.t.sol
├── out/
├── broadcast/
├── .env
├── foundry.toml
└── frontend/
    └── src/
        ├── contracts/
        │   └── counter.ts
        ├── web3/
        │   └── config.ts
        └── App.tsx
forge script script/DeployCounter.s.sol:DeployCounter \
  --rpc-url sepolia \
  --broadcast

This article was imported from an X Article. Original: https://x.com/i/status/2110719292945977524