SolidityIn

Zero to Mainnet: A Step-by-Step Guide to Writing Your First Smart Contract

October 29, 2026 · admin · Uncategorized

Taking the leap from Web2 to Web3 can feel daunting. Smart contracts deal with immutable code and real financial value—meaning there are no “undo” buttons. This comprehensive guide walks you through the entire lifecycle: from setting up your development environment and writing secure Solidity code to testing locally, deploying to a testnet, and finally launching safely on Ethereum Mainnet.


Prerequisites and Core Concepts

Before writing code, let’s clarify the fundamentals. A smart contract is a self-executing program stored on a blockchain that runs automatically when predetermined conditions are met. Mainnet is the primary production network where transactions carry real economic value and cost real gas fees.

To follow this tutorial, you will need:

  • Node.js (v18+) and npm installed on your machine.
  • A non-custodial crypto wallet (such as MetaMask or Rabby).
  • A code editor, preferably Visual Studio Code.
  • Testnet ETH (via a public Sepolia faucet) and a small amount of real ETH on Mainnet (or an L2 like Arbitrum, Base, or Optimism to save fees).

Step 1: Set Up the Professional Development Environment

While online tools like Remix IDE are great for quick prototyping, real-world development relies on frameworks like Hardhat or Foundry. In this guide, we use Hardhat due to its rich ecosystem and approachable JavaScript/TypeScript tooling.

Open your terminal and initialize your project:

<pre><code class="language-bash">mkdir my-first-contract

cd my-first-contract
npm init -y
npm install –save-dev hardhat dotenv @nomicfoundation/hardhat-toolbox

<p>Initialize a Hardhat project:</p>
<pre><code class="language-bash">npx hardhat init</code></pre>
<p>Select <strong>"Create a JavaScript project"</strong> (or TypeScript if you prefer) and accept the defaults.</p>

Step 2: Write Your First Smart Contract

We will build a clean, secure, and practical contract: a TipJar. Users can send tips along with a message, and the owner can withdraw the collected funds.

Delete the sample contract in contracts/ and create a new file named TipJar.sol:

<pre><code class="language-solidity">// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**

  • @title TipJar

  • @dev A simple smart contract that accepts ETH tips with a message.
    */
    contract TipJar {
    struct Tip {
    address sender;
    string message;
    uint256 amount;
    uint256 timestamp;
    }

    address payable public immutable owner;
    Tip[] private tips;

    event NewTip(address indexed sender, string message, uint256 amount, uint256 timestamp);
    event FundsWithdrawn(uint256 amount);

    error OnlyOwner();
    error TransferFailed();
    error ZeroAmount();

    modifier onlyOwner() {
    if (msg.sender != owner) revert OnlyOwner();
    _;
    }

    constructor() {
    owner = payable(msg.sender);
    }

    /**

    • @dev Tip the contract owner with a message.

    • @param _message A short memo from the tipper.
      */
      function sendTip(string calldata _message) external payable {
      if (msg.value == 0) revert ZeroAmount();

      tips.push(Tip({
      sender: msg.sender,
      message: _message,
      amount: msg.value,
      timestamp: block.timestamp
      }));

      emit NewTip(msg.sender, _message, msg.value, block.timestamp);
      }

    /**

    • @dev Withdraw all funds collected in the contract to the owner.
      */
      function withdraw() external onlyOwner {
      uint256 balance = address(this).balance;
      if (balance == 0) revert ZeroAmount();

      (bool success, ) = owner.call{value: balance}(“”);
      if (!success) revert TransferFailed();

      emit FundsWithdrawn(balance);
      }

    /**

    • @dev Returns all tips sent to the contract.
      */
      function getAllTips() external view returns (Tip[] memory) {
      return tips;
      }
      }

Step 3: Compile and Test Locally

Testing is mandatory in smart contract development. If your contract has a bug, you cannot easily patch it once deployed.

Compile the contract to ensure there are no syntax errors:

npx hardhat compile

<p>Next, write automated tests in <code>test/TipJar.test.js</code>:</p>
<pre><code class="language-javascript">const { expect } = require("chai");

const { ethers } = require(“hardhat”);

describe(“TipJar Contract”, function () {
let TipJar, tipJar, owner, tipper;

beforeEach(async function () {
[owner, tipper] = await ethers.getSigners();
TipJar = await ethers.getContractFactory(“TipJar”);
tipJar = await TipJar.deploy();
});

it(“Should set the correct deployer as owner”, async function () {
expect(await tipJar.owner()).to.equal(owner.address);
});

it(“Should accept tips and emit an event”, async function () {
const tipAmount = ethers.parseEther(“0.1”);

await expect(
tipJar.connect(tipper).sendTip("Keep up the great work!", { value: tipAmount })
)
.to.emit(tipJar, "NewTip")
.withArgs(tipper.address, "Keep up the great work!", tipAmount, (val) => val > 0);
const tips = await tipJar.getAllTips();
expect(tips.length).to.equal(1);
expect(tips[0].amount).to.equal(tipAmount);

});

it(“Should prevent non-owners from withdrawing funds”, async function () {
await expect(tipJar.connect(tipper).withdraw()).to.be.revertedWithCustomError(
tipJar,
“OnlyOwner”
);
});
});

<p>Run your tests locally:</p>
<pre><code class="language-bash">npx hardhat test</code></pre>

Step 4: Secure Network Configuration

Never expose your private keys. Store sensitive values in an environment file that is excluded from version control.

<p>Create a <code>.env</code> file:</p>
<pre><code class="language-text">PRIVATE_KEY=your_wallet_private_key_without_0x

SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_API_KEY
MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY
ETHERSCAN_API_KEY=YOUR_ETHERSCAN_API_KEY

<p>Ensure your <code>.gitignore</code> explicitly contains:</p>
<pre><code class="language-text">.env

node_modules/
cache/
artifacts/

<p>Update your <code>hardhat.config.js</code>:</p>
<pre><code class="language-javascript">require("@nomicfoundation/hardhat-toolbox");

require(“dotenv”).config();

const { PRIVATE_KEY, SEPOLIA_RPC_URL, MAINNET_RPC_URL, ETHERSCAN_API_KEY } = process.env;

module.exports = {
solidity: “0.8.20”,
networks: {
sepolia: {
url: SEPOLIA_RPC_URL || “”,
accounts: PRIVATE_KEY ? [PRIVATE_KEY] : [],
},
mainnet: {
url: MAINNET_RPC_URL || “”,
accounts: PRIVATE_KEY ? [PRIVATE_KEY] : [],
},
},
etherscan: {
apiKey: ETHERSCAN_API_KEY,
},
};

Step 5: Staging Deployment on Sepolia Testnet

Before deploying to Mainnet, test in an identical environment where failure carries zero financial penalty. Sepolia is the recommended testnet for Ethereum applications.

<p>Create a deployment script at <code>scripts/deploy.js</code>:</p>
<pre><code class="language-javascript">const { ethers } = require("hardhat");

async function main() {
const [deployer] = await ethers.getSigners();
console.log(“Deploying contract with account:”, deployer.address);

const TipJar = await ethers.getContractFactory(“TipJar”);
const tipJar = await TipJar.deploy();

await tipJar.waitForDeployment();

const address = await tipJar.getAddress();
console.log(“TipJar successfully deployed to:”, address);
}

main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

<p>Deploy to the Sepolia testnet:</p>
<pre><code class="language-bash">npx hardhat run scripts/deploy.js --network sepolia</code></pre>
<p>Verify your contract source code on Sepolia Etherscan so users can read and interact with it:</p>
<pre><code class="language-bash">npx hardhat verify --network sepolia YOUR_CONTRACT_ADDRESS</code></pre>

Step 6: The Final Frontier — Deploying to Mainnet

Once you have tested all functions on Sepolia, you are ready for Mainnet.

<h3>Pre-Launch Checklist</h3>
<ol>
<li><strong>Gas Check:</strong> Check the current base fee on <a href="https://etherscan.io/gastracker" target="_blank" rel="noopener noreferrer">Etherscan Gas Tracker</a>. Deploying during low-traffic periods (weekends or early UTC mornings) can save significant capital.</li>
<li><strong>Separate Deployment Wallet:</strong> Use a fresh wallet containing only the ETH needed for deployment to minimize blast radius in case of compromised local keys.</li>
<li><strong>Verified Balance:</strong> Ensure your deployment wallet holds sufficient native currency to cover creation gas limits.</li>
</ol>
<p>Run the deployment command targeting Mainnet (or an L2 network like Arbitrum or Base for lower gas costs):</p>
<pre><code class="language-bash">npx hardhat run scripts/deploy.js --network mainnet</code></pre>
<p>Finally, verify the contract on Mainnet Etherscan:</p>
<pre><code class="language-bash">npx hardhat verify --network mainnet YOUR_MAINNET_CONTRACT_ADDRESS</code></pre>

Post-Deployment & Security Best Practices

  • Consider Multi-Sig Ownership: For serious projects, transfer the ownership of your contract to a multi-signature wallet like Safe (formerly Gnosis Safe) instead of a single private key.
  • Immutable Metadata: If your contract involves images, tokens, or external references, store metadata on decentralized storage solutions like IPFS or Arweave.
  • Auditing: Even straightforward contracts benefit from peer reviews or automated static analysis tools like Slither and Aderyn before taking on serious TVL (Total Value Locked).

Conclusion

Congratulations! You have taken a smart contract from concept to automated testing, through testnet staging, and finally onto Ethereum Mainnet. Smart contract engineering requires caution and disciplined verification, but mastering this pipeline unlocks the ability to build censorship-resistant, unstoppable applications on the open web.

Tags: , , ,