How to Create Smart Contracts with Web3

·

Smart contracts are self-executing agreements that run on the blockchain, forming the backbone of decentralized applications (dApps) in the Web3 ecosystem. Web3 represents the next evolution of the internet—where users reclaim control over their data, digital identity, and assets, interacting peer-to-peer without centralized intermediaries.

In this comprehensive guide, we’ll walk you through how to create smart contracts using JavaScript and Solidity, the two most widely used languages in Web3 development. You’ll also learn how to deploy and interact with your smart contracts using essential tools like Ganache, web3.js, and Remix IDE—all while gaining practical, hands-on experience.

Core Tools You’ll Need

To begin building smart contracts, ensure you have the following development tools installed:

You can install most of these tools via package managers like npm or directly from their official websites.

👉 Get started with Web3 development tools and environments today.


Writing Your First Smart Contract in Solidity

A smart contract defines the rules and logic of an agreement between parties—automatically executing when conditions are met. Let’s create a simple purchase order contract between a buyer and a seller.

Our PurchaseOrder contract will:

Here’s the Solidity code:

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract PurchaseOrder {
    address public buyer;
    address public seller;
    string public item;
    uint256 public price;

    event Purchased(address buyer, address seller, string item);

    constructor(address _buyer, address _seller, string memory _item, uint256 _price) {
        buyer = _buyer;
        seller = _seller;
        item = _item;
        price = _price;
    }

    function buy() public payable {
        require(msg.sender == buyer, "Only buyer can buy");
        require(msg.value == price, "Value must equal price");
        payable(seller).transfer(msg.value);
        emit Purchased(buyer, seller, item);
    }
}

This contract ensures secure, trustless transactions—only the designated buyer can trigger the purchase, and payment must exactly match the set price.


Deploying the Smart Contract Using Remix IDE

To deploy your contract, you need two key outputs:

Step-by-Step Deployment:

  1. Open Remix IDE in your browser.
  2. Create a new file named PurchaseOrder.sol.
  3. Paste the Solidity code above.
  4. Navigate to the Solidity Compiler tab and select version ^0.8.0.
  5. Click Compile PurchaseOrder.sol.
  6. Under Compilation Details, copy:

    • The ABI into PurchaseOrderABI.json
    • The bytecode into PurchaseOrderBytecode.txt

Now connect to Ganache:

  1. Launch Ganache and select Quickstart Workspace.
  2. In Remix, go to the Deploy & Run Transactions tab.
  3. Set environment to Web3 Provider and connect to http://localhost:8545.
  4. Deploy the contract.
  5. Copy the deployed contract address into PurchaseOrderAddress.txt.

Your smart contract is now live on a local blockchain.


Interacting with the Smart Contract Using web3.js

Now that your contract is deployed, let’s interact with it using JavaScript and web3.js.

Create a file named PurchaseOrder.js:

const Web3 = require("web3");
const fs = require("fs");

const abi = JSON.parse(fs.readFileSync("PurchaseOrderABI.json"));
const address = fs.readFileSync("PurchaseOrderAddress.txt", "utf8");

const web3 = new Web3("http://localhost:8545");
const contract = new web3.eth.Contract(abi, address);

web3.eth.getAccounts().then(accounts => {
    const buyer = accounts[0];
    const seller = accounts[1];

    console.log("Purchase Order Details:");
    console.log("Buyer:", buyer);
    console.log("Seller:", seller);
    console.log("Item: Smartphone");
    console.log("Price: 1000000000000000000 wei (1 ETH)");

    contract.methods.buy().send({ from: buyer, value: "1000000000000000000" })
        .on('transactionHash', hash => {
            console.log("Transaction Hash:", hash);
        })
        .on('receipt', receipt => {
            console.log("Transaction successful:", receipt);
        })
        .catch(err => {
            console.error("Transaction failed:", err.message);
        });
});

Run it using node PurchaseOrder.js. If successful, you’ll see transaction details and event logs in your console.


Listening to Smart Contract Events

Smart contracts can emit events to notify external applications of state changes. Our Purchased event logs every successful transaction.

Use these web3.js methods to listen:

Example:

contract.events.Purchased({}, (error, event) => {
    if (!error) console.log("Event caught:", event.returnValues);
});

// Get all past events
contract.getPastEvents('Purchased', { fromBlock: 0 }, (err, events) => {
    if (!err) console.log("Past events:", events);
});

👉 Discover how real-time event monitoring enhances dApp functionality.


Frequently Asked Questions (FAQ)

What is a smart contract?

A smart contract is a self-executing program on a blockchain that automatically enforces agreement terms between parties without intermediaries.

Can I test smart contracts without spending real money?

Yes—tools like Ganache simulate a local Ethereum blockchain, giving you test Ether and accounts for safe development.

Is Solidity hard to learn?

Solidity is approachable if you know JavaScript or C++. Its syntax is similar, but it includes blockchain-specific concepts like gas and state mutability.

What’s the difference between web3.js and ethers.js?

Both are libraries for interacting with Ethereum. web3.js is older and more feature-rich; ethers.js is modern, lightweight, and easier for beginners.

How do I secure my smart contract?

Always validate inputs, use require() statements, avoid known vulnerabilities (e.g., reentrancy), and test thoroughly using tools like Slither or Hardhat.

Can smart contracts be updated after deployment?

No—blockchain immutability prevents direct updates. Use proxy patterns or upgradeable contracts for flexibility.


Final Thoughts

Creating smart contracts with Web3 opens doors to decentralized finance (DeFi), NFTs, DAOs, and more. By mastering Solidity and web3.js, you gain the power to build trustless, transparent applications that operate without central control.

As Web3 continues to evolve, early adopters who understand smart contract development will lead innovation across industries—from finance to gaming to digital identity.

Whether you're building your first dApp or exploring blockchain’s potential, now is the time to dive in.

👉 Start building your first Web3 project with confidence and expert tools.