Smart contracts for dummies
Source: Dev.to
Introduction
Learning blockchain concepts can be challenging, but understanding smart contracts doesn’t have to be. This guide introduces the basics of smart contracts and walks through a simple “bank vault” contract written in Solidity.
Key Concepts
- State machine – The blockchain functions like a state machine (similar to Redux or Context API) that tracks and updates state.
- View – A read‑only operation that lets you see the current state, such as a contract’s balance.
- State – Data stored on the blockchain (e.g., balances, records).
- Contract – A piece of code that governs how state can be read or modified, analogous to a set of rules.
- Public – Functions or variables marked
publiccan be accessed by anyone on the network. - Remix – An online IDE for writing, testing, and deploying Solidity contracts.
- Returns – Specifies the output type of a function, typically used in view functions.
Example: Vault Contract
Below is a minimal Solidity contract that acts as a simple vault where users can deposit and withdraw Ether.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Vault {
uint public initialBalance;
uint public balance;
constructor(uint _balance) {
initialBalance = _balance;
balance = _balance;
}
function checkBalance() public view returns (uint) {
return balance;
}
function deposit(uint amount) public {
balance += amount;
}
function withdraw(uint amount) public {
require(balance >= amount, "Not enough balance");
balance -= amount;
}
}
Contract Overview
-
State variables
initialBalance– Stores the balance set at deployment.balance– Tracks the current vault balance.
-
Constructor
Initializes bothinitialBalanceandbalancewith the value passed during deployment. -
Functions
checkBalance()– Aviewfunction that returns the current balance.deposit(uint amount)– Increasesbalanceby the specifiedamount.withdraw(uint amount)– Decreasesbalanceafter verifying sufficient funds usingrequire.
Important Details
- Parameter names prefixed with an underscore (e.g.,
_balance) avoid naming conflicts with state variables. - The
requirestatement acts like anifcheck; if the condition fails, the transaction reverts with the provided error message. - All functions are marked
public, making them callable by any external account.
Conclusion
The Vault contract demonstrates core Solidity concepts: state variables, constructors, view functions, state‑changing functions, and basic error handling. By experimenting with this example in Remix, you can gain a solid foundation for building more complex smart contracts.