What Is a Smart Contract?
A smart contract is a program that runs automatically on a blockchain when specific conditions are met. No intermediary is needed — code is law.
Analogy: A vending machine. Insert money, select a product, the machine dispenses it without a cashier. Smart contracts work the same way for any agreement.
## Solidity: The Smart Contract Language
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private storedValue;
function store(uint256 _value) public {
storedValue = _value;
}
function retrieve() public view returns (uint256) {
return storedValue;
}
}
```
## Practical Example: Escrow Contract
```solidity
contract Escrow {
address public buyer;
address public seller;
uint256 public amount;
bool public released;
constructor(address _seller) payable {
buyer = msg.sender;
seller = _seller;
amount = msg.value;
}
function release() public {
require(msg.sender == buyer, 'Only buyer');
require(!released, 'Already released');
released = true;
payable(seller).transfer(amount);
}
}
```
This contract holds ETH from the buyer and only releases it to the seller when the buyer calls release(). No bank, no notary.
## Key Solidity Components
- State variables: Data stored permanently on the blockchain.
- Functions: Operations callable from outside.
- Modifiers: Conditions that must be met before a function runs.
- Events: Logs recorded on the blockchain for tracking.