Smart contracts

How Smart Contracts Work

Follow a transaction from signing through execution, state changes and events, with a real contract to read along.

By the Kensaltensi team · Last updated 27 October 2026 · 7 min read

The phrase "smart contract" suggests something legalistic and intelligent. In reality a smart contract is much simpler: it is a small program, stored on a blockchain, together with its own persistent data. Anyone can call it, every validating node executes the call in the same deterministic way, and the result is recorded on the ledger. This guide explains each step using a deliberately small example, so you can see exactly what is happening when a user presses a button in a dApp.

Accounts, code and storage

On Ethereum and other EVM-compatible networks there are two kinds of account. An externally owned account (EOA) is controlled by a private key; this is what a wallet manages. A contract account has no private key. It has an address, some bytecode, and a key-value storage area. Contract code only runs when something triggers it: either a transaction signed by an EOA, or a call from another contract.

You write contracts in a high-level language such as Solidity or Vyper. A compiler turns that into EVM bytecode, which is what actually gets deployed, plus an ABI (application binary interface), a JSON description of the functions and events that front ends use to encode calls and decode results.

A worked example

Here is a small guest-book contract. It lets anyone sign with a message, keeps a count, remembers each address's latest message, and lets only the deployer reset the counter.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract GuestBook {
    address public owner;
    uint256 public entryCount;
    mapping(address => string) public lastMessage;

    event Signed(address indexed visitor, uint256 indexed entryId, string message);

    error EmptyMessage();
    error NotOwner();

    constructor() {
        owner = msg.sender;
    }

    function sign(string calldata message) external {
        if (bytes(message).length == 0) revert EmptyMessage();
        entryCount += 1;
        lastMessage[msg.sender] = message;
        emit Signed(msg.sender, entryCount, message);
    }

    function reset() external {
        if (msg.sender != owner) revert NotOwner();
        entryCount = 0;
    }
}

Even in under thirty lines there is a lot to notice:

  • owner, entryCount and lastMessage are storage variables. They persist between calls and are the contract's state. Writing to storage is the most expensive thing a contract does.
  • msg.sender is the address that called the function. This is how contracts know who is acting, and it is the foundation of access control.
  • calldata marks the argument as read-only data supplied by the caller, which is cheaper than copying it into memory.
  • The revert statements with custom errors cancel the whole call if a precondition fails. Custom errors are cheaper than string messages and can carry data.
  • emit Signed(...) writes an event to the transaction log. Events are not readable by other contracts, but they are cheap and are exactly what indexers and front ends listen to.
  • Solidity 0.8 and later checks arithmetic for overflow automatically, so entryCount += 1 cannot silently wrap.

What happens when a user calls sign()

  1. EncodingThe front end uses the ABI to encode the call. The first four bytes of the data are the function selector, taken from a hash of the signature sign(string). The arguments follow in ABI encoding.
  2. Transaction constructionThe wallet builds a transaction containing the target address, the encoded data, a nonce, and gas parameters.
  3. SignatureThe user approves, and the wallet signs the transaction with their private key. The network can now verify the sender without any password.
  4. Propagation and inclusionThe transaction spreads through the network. A validator picks it up and includes it in a block, ordering it among others.
  5. ExecutionEvery node runs the contract's bytecode with the supplied data. The EVM meters each operation, charging gas.
  6. State change and logsIf execution completes, the storage changes are committed and the Signed event is added to the receipt.
  7. ReceiptThe transaction receipt records status (success or failure), gas used and logs. Your front end and indexer read this.

A transaction object, simplified, looks like this:

{
  "chainId": 11155111,
  "nonce": 7,
  "to": "0x5FbDB2315678afecb367f032d93F642f64180aa3",
  "value": "0x0",
  "data": "0x...",                       // 4-byte selector + ABI-encoded arguments
  "gasLimit": "0x186a0",
  "maxFeePerGas": "0x2540be400",
  "maxPriorityFeePerGas": "0x3b9aca00"
}

Gas, in plain terms

Because every node repeats every computation, the network needs a way to stop infinite loops and to price scarce resources. Each EVM operation has a gas cost. The sender sets a gas limit (the most they are willing to consume) and, under the fee model used by Ethereum since EIP-1559, a max fee per gas and a priority fee (a tip to the validator). If execution runs out of gas, it reverts and the gas used is still paid. If it uses less than the limit, the remainder is refunded.

Two practical consequences follow. Storage writes dominate cost, so well-designed contracts store as little as possible and rely on events for historical data. And gas estimation is only an estimate: state can change between estimation and inclusion, which is a common source of failed transactions.

Reverts, errors and atomicity

Contract execution is atomic. If any step in a call reverts, every state change made during that call is undone, including changes made by other contracts it called. This is a powerful property: a multi-step operation, such as swapping two tokens, either happens completely or not at all.

What a revert does not undo is the fee. The user still pays for the computation consumed up to the failure. This is why good front ends simulate the call first (using eth_call or a dedicated simulation service) and show the reason for a predicted failure before asking the user to sign.

Contracts calling contracts

Contracts can call other contracts, which is how decentralised applications compose. When your contract calls an external one, control passes to code you do not own, and that code can call back into yours before your function has finished. This is the root cause of reentrancy vulnerabilities, discussed in our smart contract security checklist. The standard defence is the checks-effects-interactions pattern: validate inputs, update your own state, and only then make the external call.

Token standards make this composability practical. ERC-20 defines a common interface for fungible tokens, and ERC-721 and ERC-1155 for non-fungible and multi-token assets. Because every compliant token exposes the same functions (transfer, approve, balanceOf and so on), wallets and exchanges can support new tokens without custom code.

Immutability and upgrades

Once deployed, the bytecode at an address cannot be changed. That is the source of the "trustless" property, because users can inspect the code and know it will not be modified. It is also why a bug in a deployed contract can be permanent.

Teams that need to fix or extend behaviour typically use a proxy pattern: users interact with a stable proxy address that forwards calls, using delegatecall, to an implementation contract that can be swapped. This provides flexibility but changes the trust model, because whoever controls the upgrade key can change the rules. Mature projects mitigate this with multi-signature control, timelocks that delay upgrades so users can react, and clear public documentation of who holds the keys. Proxies also introduce their own pitfalls, such as storage layout collisions between versions and uninitialised implementation contracts.

How to read an unfamiliar contract

When you evaluate a contract, for example before integrating with it, a consistent reading order saves time:

  1. List the external functions. These are the entire attack and usage surface.
  2. Find the access control. Who can call each privileged function, and can that role be changed?
  3. Trace value flows. Where can ether or tokens enter and leave?
  4. Check external calls. Which other contracts does it trust, and in what order does it update state versus call out?
  5. Look at upgradeability. Is it a proxy? Who controls it? Is there a timelock?
  6. Read the events. They show what the authors consider important to record.
  7. Check the tests and audits. A contract with no tests and no review is a different risk from one with extensive coverage and public audit reports.

Key takeaways

  • A smart contract is code plus persistent storage at an address. It runs only when a transaction or another contract calls it.
  • Every state-changing call is a signed transaction that costs gas, and a revert undoes state changes but not the fee.
  • Events are the cheap, indexable record of what happened; use them for the data your front end and indexer need.
  • Deployed code is normally immutable. Upgradeability is possible but adds trust assumptions and its own class of bugs.
  • Read the function signature, the access control and the revert conditions first when reviewing any contract.

Related guides

Further reading

About this guide. Written by the Kensaltensi engineering and QA team for educational purposes. Examples are illustrative, and standards evolve, so check the primary sources above before relying on a detail in production. If you spot an error or an out-of-date statement, email hello@kensaltensi.org and we will review and correct it.