Smart contracts are like computer programs stored on the blockchain.
They can store their own state, like balances, settings, or inventory numbers. Contracts execute functions when called by transactions or other contracts. Changing contract state costs gas; read-only calls can run locally without paying gas.
Smart contracts are like vending machines: input leads to output based on predefined rules.
The language used to write smart contracts is called Solidity .
Smart contracts are also Ethereum accounts with their own addresses and ETH balances. Contract accounts cannot initiate transactions on their own, but they can make internal calls during execution.
contract VendingMachine {
mapping(string => uint) public inventory;
mapping(string => uint) public prices;
uint public totalSales;
constructor() {
inventory["cola"] = 10;
inventory["chips"] = 10;
inventory["candy"] = 10;
prices["cola"] = 2;
prices["chips"] = 3;
prices["candy"] = 1;
}
function purchase(string memory item) public payable {
require(inventory[item] > 0, "Out of stock");
require(msg.value >= prices[item], "Insufficient payment");
inventory[item] -= 1;
totalSales += prices[item];
}
}Transaction (writes state; requires gas fee)
State