This guide explores a Solidity smart contract project named "Assessment," designed to manage Ether deposits, withdrawals, and transfers. It also covers the accompanying React-based decentralized application (DApp) that provides a user interface for interacting with the contract.
Core Project Overview
The project consists of two main components:
- A Solidity smart contract for managing Ether on the blockchain.
- A React front-end DApp that allows users to interact with the contract via a web interface.
The contract enforces an onlyOwner modifier, ensuring that only the account that deployed it can execute its key functions. This setup is ideal for learning core Web3 development concepts.
Understanding the Smart Contract
The Assessment.sol smart contract is written in Solidity and handles the logic for fund management on the Ethereum Virtual Machine (EVM).
Key State Variables
owner: A public address variable storing the Ethereum address of the account that deployed the contract. This address has exclusive rights to execute protected functions.balance: A public unsigned integer (uint256) that tracks the total amount of Ether (in wei) currently held by the contract.
Core Functions and Modifiers
The contract's functionality is exposed through several key functions, each protected by the onlyOwner modifier.
The onlyOwner Modifier
This security feature restricts access to critical functions. It checks if the address calling the function (msg.sender) matches the stored owner address. If not, the transaction is reverted, preventing unauthorized access.
Deposit Function
The deposit function allows the owner to add Ether to the contract. It takes one parameter, _amount, and increases the contract's balance by that value. A Deposit event is emitted to log the action on the blockchain.
Withdraw Function
The withdraw function enables the owner to retrieve Ether. It first checks if the contract's current balance is sufficient for the requested _withdrawAmount. If successful, it deducts the amount and sends it to the owner, emitting a Withdraw event.
Transfer Function
This function allows the owner to send Ether directly from the contract's balance to any other address. It requires two parameters: the recipient's address (_to) and the _amount to send. It includes a balance check and emits a Transfer event upon success.
Get Balance Function
A simple, read-only function (getBalance) that returns the contract's current balance without requiring any transaction fees (gas). It can be called by any user.
Event Logging
Events are crucial for off-chain applications to track on-chain activity. This contract emits three events:
Deposit(uint256 amount): Logs the amount deposited.Withdraw(uint256 amount): Logs the amount withdrawn.Transfer(address indexed to, uint256 amount): Logs the recipient's address and the amount transferred.
The React DApp Front-End
The front-end is a React application that creates a bridge between the user and the blockchain-based smart contract.
Wallet Connection Setup
The DApp uses the ethers.js library to interact with Ethereum. Key functions include:
getWallet: Checks for the presence of the MetaMask browser extension.connectAccount: Requests the user to connect their MetaMask wallet, which grants the DApp access to their Ethereum account address.
Smart Contract Interaction
Once a wallet is connected, the DApp creates an instance of the contract using its Application Binary Interface (ABI) and address.
getATMContract: Initializes the contract object for interaction.getBalance: Calls the contract'sgetBalancefunction and updates the UI.deposit,withdraw,transferFunds: These functions build transactions that call the corresponding contract methods. They require the user to sign the transaction with MetaMask and pay gas fees.
User Interface Dynamics
The initUser function controls what is displayed based on the user's connection status. Once connected, the UI shows:
- The connected account address.
- The current contract balance.
- Input fields and buttons for depositing, withdrawing, and transferring funds.
- An "Exit" button to reset the connection state.
The interface includes CSS styling for a clean and modern user experience. 👉 Explore more Web3 development strategies
How to Set Up and Run the Project Locally
To test this project on a local development blockchain, follow these steps:
- Install Dependencies: Navigate to the project root directory in your terminal and run
npm installto install all required Node.js packages. - Start a Local Blockchain: Open a second terminal and run
npx hardhat node. This command starts a local Ethereum network node on your machine, complete with test accounts and private keys. - Deploy the Contract: Open a third terminal and run
npx hardhat run --network localhost scripts/deploy.js. This command compiles the smart contract and deploys it to your local Hardhat network. - Launch the Front-End: Return to your first terminal and run
npm run dev. This will start the React development server, typically making the DApp available athttp://localhost:3000.
Connecting MetaMask to the Local Network
For the DApp to work, your MetaMask wallet must be connected to your local Hardhat network:
- Get the RPC URL provided by Hardhat (usually
http://localhost:8545). - In MetaMask, add a new custom network using this RPC URL.
- Set the Chain ID to
31337(the default for Hardhat) and the currency symbol toETH. - Import one of the test accounts provided by Hardhat using its private key. This account will be the contract
ownerand have funds for testing.
Frequently Asked Questions
What is the purpose of the onlyOwner modifier?
The onlyOwner modifier is a fundamental access control mechanism. It ensures that only the address that deployed the smart contract can execute sensitive functions like withdrawing or transferring funds, protecting the contract's assets from unauthorized access.
Do I need real ETH to test this project?
No, you do not need real Ether. The local setup uses a simulated blockchain (Hardhat Network) with test ETH that has no real-world value. This allows you to experiment and learn without any financial cost.
Why do transactions like depositing require me to pay gas?
Interacting with the blockchain that changes its state (like updating a balance) requires computation. Gas fees are the payments made to the network validators for this computation. Read-only calls, like checking a balance, do not require gas.
What is an event in a smart contract?
Events are Solidity's way of allowing smart contracts to emit log messages. These messages are stored on the blockchain and can be efficiently retrieved by off-chain applications, like your DApp, to track specific contract activities without constantly polling the chain.
Can I deploy this contract to a public testnet?
Yes, absolutely. Once you are comfortable with the local setup, you can configure Hardhat to deploy to a testnet like Goerli or Sepolia. You would need testnet ETH from a faucet to pay for deployment and transaction gas fees on these public networks.
How can I extend this project's functionality?
This project serves as an excellent foundation. You can extend it by adding features like multiple user roles, transaction history tracking, support for ERC-20 tokens, or more complex financial logic. 👉 Get advanced methods for smart contract development