What Are Smart Contracts?
Smart contracts are self-executing programs stored on a blockchain that automatically enforce predefined rules when specific conditions are met. These digital agreements contain:
- Balance: Current ETH holdings
- Nonce: Transaction count
- Code: Compiled contract logic
- Storage: State data (organized in Merkle Patricia Trees)
Smart Contract Architecture in Solidity
Solidity, Ethereum's primary programming language, features:
contract Auction {
// State variables
address public beneficiary;
uint public auctionEnd;
// Events
event HighestBidIncreased(address bidder, uint amount);
event Pay2Beneficiary(address winner, uint amount);
// Mappings
mapping(address => uint) public bids;
address[] public bidders;
// Constructor
constructor(uint _biddingTime, address _beneficiary) {
beneficiary = _beneficiary;
auctionEnd = block.timestamp + _biddingTime;
}
// Functions
function bid() public payable {...}
function withdraw() public {...}
}Key Solidity Features:
- Mappings: Hash tables (non-iterable by default)
- Arrays: Fixed-size or dynamically-sized
- Constructors: Defined via
constructor()or legacy class-name method - Visibility:
publicfunctions are externally callable
๐ Discover how smart contracts revolutionize digital agreements
Contract Interaction Methods
1. External Account Calls
Transactions to contract addresses include:
value: ETH transferred (0 for pure function calls)data: Function selector + encoded parametersgasLimit: Maximum gas willing to spend
2. Cross-Contract Calls
| Method | Behavior | Error Handling |
|---|---|---|
| Direct Call | Full state rollback on failure | Atomic transaction |
address.call() | Returns false on failure | Isolated failure |
delegatecall() | Executes in caller's context | No state switching |
Critical Smart Contract Concepts
Payable Functions
function deposit() public payable {}- Required for ETH-accepting functions
- Non-payable functions reject incoming ETH
Fallback Function
receive() external payable {}Executes when:
- No function specified in call
- Called function doesn't exist
- Must be
payableto accept ETH
Gas Mechanics
- GasLimit: Maximum units willing to consume
- GasPrice: ETH per gas unit
- Opcode Costs: Vary by operation complexity
- 2300 Gas: Default sent with plain transfers
Error Handling Mechanisms
Failure Modes
- Gas Exhaustion: Partial execution โ full rollback
Assert/Require:
require(now <= auctionEnd, "Auction expired"); assert(bids[msg.sender] > 0);- Revert: Unconditional rollback
๐ Explore advanced smart contract techniques
Smart Contract Security Patterns
Auction Contract Vulnerabilities
Reentrancy Attack
Malicious fallback recursion:
function withdraw() public { uint amount = bids[msg.sender]; (bool success,) = msg.sender.call{value: amount}(""); bids[msg.sender] = 0; }Solution: Checks-Effects-Interactions pattern
DoS via Failed Transfer
- Contract accounts without fallback
Solution: Pull-over-push payments
- Contract accounts without fallback
Best Practices Checklist
- State Changes Before Interactions
- Gas Limit Considerations
- Reentrancy Guards
- Pull Payment Patterns
- Secure Visibility Settings
- Comprehensive Event Logging
FAQ: Smart Contracts Explained
Q: Can smart contracts be modified after deployment?
A: No. Ethereum smart contracts are immutable by design. All code must be thoroughly tested before deployment.
Q: How do contracts access real-world data?
A: Through oracle services like Chainlink that feed external data to the blockchain.
Q: What happens if a contract runs out of gas?
A: The transaction reverts but gas spent isn't refunded. Gas limits should be carefully estimated.
Q: Can contracts delete themselves?
A: Yes, via the selfdestruct opcode, sending remaining ETH to a designated address.
Q: How are contracts uniquely identified?
A: By their deployment address, generated from creator's address and nonce.
Q: What's the difference between call() and transfer()?
A: transfer() has fixed 2300 gas and throws, while call() forwards all gas and returns bool.
Conclusion
Ethereum smart contracts represent a paradigm shift in programmable trust, enabling decentralized applications with enforceable logic. While powerful, they require meticulous design to avoid vulnerabilities like reentrancy and gas-related failures. By understanding Solidity's execution model, gas economics, and security patterns, developers can build robust decentralized systems.