Introduction to Smart Contracts
Smart contracts are self-executing contracts with the terms of the agreement directly written into code. They automatically enforce and execute contractual terms when predefined conditions are met, eliminating the need for intermediaries.
Simple Smart Contract Example
Let's start with a basic example that sets a variable's value and exposes it for other contracts to access. Don't worry if some concepts aren't immediately clear—we'll explore them in detail later.
Storage Contract Demonstration
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}Key Components Explained:
- SPDX License Identifier: Indicates open-source licensing (GPL-3.0).
- Pragma Directive: Specifies compatible Solidity compiler versions (0.4.16 to <0.9.0).
- State Variable:
storedDataholds a 256-bit unsigned integer. Functions:
set()modifies the variable.get()retrieves the variable's value.
👉 Learn more about Solidity pragmas
This contract allows anyone to store and retrieve a single number on the blockchain. While simple, it highlights how data persistence and access control can be managed programmatically.
Subcurrency Implementation Example
Below is a minimal cryptocurrency contract demonstrating token creation and transfers:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Coin {
address public minter;
mapping(address => uint) public balances;
event Sent(address from, address to, uint amount);
constructor() {
minter = msg.sender;
}
function mint(address receiver, uint amount) public {
require(msg.sender == minter);
balances[receiver] += amount;
}
error InsufficientBalance(uint requested, uint available);
function send(address receiver, uint amount) public {
if (amount > balances[msg.sender])
revert InsufficientBalance({
requested: amount,
available: balances[msg.sender]
});
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}Core Features:
- Minting Tokens: Only the contract creator can issue new coins.
- Transfer Mechanism: Users can send tokens securely with balance checks.
- Events: Log transfers for external monitoring.
- Error Handling: Custom errors provide clear failure reasons.
👉 Explore Ethereum development tools
Blockchain Fundamentals
Transactions
- Immutable Ledger: Transactions are cryptographically secured and irreversible once confirmed.
- Atomicity: Transactions either fully execute or revert entirely.
Blocks
- Chronological Order: Blocks form a linear chain, ensuring consensus on transaction history.
- Finality: Deeper block confirmations reduce reorganization risks.
Ethereum Virtual Machine (EVM)
Key Concepts
- Accounts: External (user-controlled) and contract (code-controlled) types.
- Gas: Computational work measured in gas units, paid by transaction senders.
Storage vs. Memory:
- Storage: Persistent but expensive (key-value store).
- Memory: Temporary and cheaper (byte-addressable).
Execution Environment
- Stack-Based: 1024-element depth limit with 256-bit words.
- Precompiled Contracts: Optimized low-level operations at fixed addresses.
Frequently Asked Questions (FAQ)
Q1: Can smart contracts be modified after deployment?
A: No. Contract code is immutable, but you can design upgradeability patterns using proxy contracts.
Q2: How is gas cost determined?
A: Gas depends on operation complexity. Simple computations cost less than storage updates.
Q3: What happens if a transaction runs out of gas?
A: The transaction reverts, and spent gas is not refunded.
Q4: Are deleted contracts completely removed from the blockchain?
A: No. Their historical data remains, but future interactions are disabled.
Q5: How can I monitor contract events?
A: Use web3.js or ethers.js to listen for emitted events like Sent in the Coin example.
This guide covers foundational concepts for understanding and writing smart contracts. For deeper exploration, refer to Solidity’s official documentation or interactive platforms like Remix IDE.