Explain ethereum > smart contracts

Smart Contracts

Smart contracts are like computer programs stored on the blockchain.

They can store data (state) and execute functions when called through transactions. Each function call costs gas depending on its complexity.

Smart contracts are like vending machines: input leads to output based on predefined rules.

The language used to write smart contracts is called Solidity.

contract VendingMachine {
    mapping(string => uint) public inventory;
    mapping(string => uint) public prices;
    uint public totalSales;

    constructor() {
        inventory["chips"] = 10;
        inventory["candy"] = 10;

        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 (requires gas fee)

State

Chips Inventory:10
Candy Inventory:10
Total Sales:0 ETH