Fintech & Banking
Ethereum Smart Contracts: EVM, Solidity, Standards and Security
Advanced9 min readUpdated
A smart contract is a small program on a public computer that anyone can call, that holds real value, and that you can rarely patch. This guide covers the execution model, a contract read line by line, the token standards, the toolchain, backend integration and the vulnerability classes that account for most losses.
What you will learn
- Explain externally owned versus contract accounts, transactions, gas and storage costs
- Read and reason about a Solidity contract including events, modifiers and visibility
- Implement and consume the ERC-20 and ERC-721 interfaces correctly
- Call contracts from a backend service and handle reorganisations and nonces
- Recognise and mitigate reentrancy, access-control, oracle and ordering vulnerabilities
Writing a smart contract is unlike almost anything else in software. The program runs on a machine you do not administer, its bytecode is public, anyone in the world can call any function you exposed, the state it holds is often worth money, and once deployed you usually cannot patch it. The result is a discipline closer to writing avionics firmware than a web service: small, explicit, exhaustively tested, and paranoid about every external call.
This guide assumes the ledger mechanics from blockchain fundamentals and moves to the programmable layer: how Ethereum executes code, what Solidity actually compiles to, which standards you must implement to be interoperable, how a normal backend talks to a chain, and the vulnerability classes responsible for most of the money lost so far.
Accounts, transactions and gas
Ethereum has two account types sharing one address space. An externally owned account is controlled by a private key, has a balance and a nonce, and is the only thing that can start a transaction. A contract account holds code and storage and acts only when called. The address of a deployed contract is derived deterministically from the deployer and the nonce, which is why deployment addresses can be predicted.
A transaction carries a sender, recipient, value, calldata, nonce, gas limit and fee parameters. The nonce is a strictly increasing per-sender counter that prevents replay and forces ordering: a transaction with nonce 8 cannot execute before nonce 7, and a stuck nonce blocks everything behind it — a fact any backend that submits transactions will eventually discover at an inconvenient moment.
Execution happens in the Ethereum Virtual Machine, a stack machine with 256-bit words. Every opcode has a gas cost, and the sender pays for what executes. Gas serves two purposes: it prices the network's scarce resources, and it bounds execution so that an infinite loop simply runs out rather than halting the chain. Fees are split into a protocol-set base fee that is burned and a priority tip to the block proposer, with the sender declaring a maximum they will pay.
Approximate relative costs (EVM, order-of-magnitude guidance)
arithmetic / comparison ~3 gas cheap, ignore it
memory expansion grows quadratically past a point
keccak256 hashing ~30 + 6 per word
reading a cold storage slot ~2,100 gas
writing a new non-zero slot ~20,000 gas <- dominates everything
updating an existing slot ~5,000 gas
emitting an event (per topic) ~375 gas <- cheap history
external call ~2,600 gas + whatever it does
Rule of thumb: storage is permanent obligation for every node,
so it is priced accordingly. Compute is nearly free by comparison.
Three consequences follow immediately. Keep persistent state minimal and pack related small values into single slots. Use events rather than storage arrays to record history that only off-chain readers need. And treat any unbounded loop over a growing array as a future denial of service, because a function that eventually exceeds the block gas limit becomes permanently uncallable.
If a transaction reverts, all state changes roll back but the gas consumed is still paid. Atomicity comes free; the fee does not.
A contract, line by line
Solidity is a statically typed, contract-oriented language. The snippets below use JavaScript highlighting since Solidity shares its curly-brace shape.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// A minimal escrow: a payer locks funds for a payee, released by an arbiter.
contract Escrow {
address public immutable payer;
address public immutable payee;
address public immutable arbiter;
uint256 public immutable deadline;
bool private released;
event Funded(address indexed from, uint256 amount);
event Released(address indexed to, uint256 amount);
event Refunded(address indexed to, uint256 amount);
error NotAuthorised();
error AlreadySettled();
error TooEarly(uint256 deadlineAt);
modifier onlyArbiter() {
if (msg.sender != arbiter) revert NotAuthorised();
_;
}
constructor(address _payee, address _arbiter, uint256 lockSeconds) payable {
payer = msg.sender;
payee = _payee;
arbiter = _arbiter;
deadline = block.timestamp + lockSeconds;
emit Funded(msg.sender, msg.value);
}
function release() external onlyArbiter {
if (released) revert AlreadySettled();
released = true; // effects before interaction
uint256 amount = address(this).balance;
emit Released(payee, amount);
(bool ok, ) = payee.call{value: amount}("");
require(ok, "transfer failed");
}
function refund() external {
if (msg.sender != payer) revert NotAuthorised();
if (released) revert AlreadySettled();
if (block.timestamp < deadline) revert TooEarly(deadline);
released = true;
uint256 amount = address(this).balance;
emit Refunded(payer, amount);
(bool ok, ) = payer.call{value: amount}("");
require(ok, "transfer failed");
}
}
Reading it in order: the pragma pins a compiler range, and pinning it exactly is better practice than a caret in production. immutable variables are fixed at construction and stored in code rather than storage, so reading them is cheap. public on a state variable generates a getter; nothing else about public implies safety, since all chain state is readable regardless of visibility keywords — there are no secrets in a contract.
event declarations define the log entries indexers consume; indexed parameters become searchable topics, and you get three of them. Custom error types are both cheaper than revert strings and far easier to handle programmatically. The modifier factors out an authorisation check, with _; marking where the function body runs.
msg.sender is the immediate caller and msg.value the ether attached. The most important line in the file is released = true; placed before the outbound call — the checks-effects-interactions ordering discussed below. Note also that payee.call{value: amount}("") is the current way to send ether, because older helpers forwarded a fixed gas stipend that breaks against contract recipients, and that its boolean result must be checked: a failed low-level call does not revert automatically.
Token standards
Interoperability on Ethereum comes from a small set of application-level interfaces published as ERCs. Two dominate.
ERC-20 describes fungible tokens: balances, transfers and a delegated-spending allowance.
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
The allowance pattern is why every decentralised application asks you to "approve" before it can move your tokens: the contract calls transferFrom against the allowance you granted. Two long-standing traps live here. Unlimited approvals mean a later bug in the approved contract can drain the balance, so prefer exact amounts or permit-style signed approvals. And decimals is metadata, not a protocol rule — tokens exist with 6, 8 or 18 decimals, so any code that hardcodes 18 will eventually mis-scale an amount by a factor of a trillion.
ERC-721 describes non-fungible tokens, where each identifier is unique and owned individually, with ownerOf, safeTransferFrom and a tokenURI pointing at metadata. The safe variants call a receiver hook on contract recipients so tokens are not sent to a contract that cannot handle them — a hook that is itself an external call, and therefore a reentrancy surface. ERC-1155 combines both models for multi-token contracts.
Use audited reference implementations for these interfaces rather than writing your own. A token contract is a solved problem, and the solved version has been reviewed by more people than your team can afford.
Toolchain and workflow
The modern development loop looks like this.
Choose a framework
Foundry runs tests written in Solidity itself, which keeps the test and the contract in one mental model and makes fuzzing and invariant testing first-class. Hardhat is JavaScript- or TypeScript-based and integrates naturally with a Node.js codebase. Many teams use both.Write tests before the contract
Property-based and invariant tests suit this domain unusually well: assert that total supply always equals the sum of balances, that no path lets a caller withdraw more than deposited, and let the fuzzer look for the counter-example. The discipline described in test-driven development transfers directly.Run static analysis and coverage in CI
Linters, a Slither-style analyser and gas snapshots should run on every pull request, exactly like any other continuous integration pipeline. Fail the build on new findings, not on the historical backlog.Deploy to a testnet
Test networks mirror mainnet mechanics with valueless ether from a faucet. Deploy the real script, not a simplified one, so the deployment itself is tested.Verify the source
Publishing source and compiler settings to a block explorer lets anyone reproduce the bytecode. An unverified contract holding user funds should be treated as untrustworthy by default.Audit before value arrives
External review is proportional to the value at risk. Ship the code, then a bug bounty, then the money — in that order.
Talking to a chain from a backend
Most real products are ordinary services that happen to read and write a chain through JSON-RPC, using a library such as ethers.js, viem or web3j.
import { JsonRpcProvider, Contract, Wallet } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const signer = new Wallet(process.env.SIGNER_KEY, provider); // use a KMS/HSM signer in production
const token = new Contract(TOKEN_ADDRESS, IERC20_ABI, signer);
// Read: free, served by the node, no transaction.
const balance = await token.balanceOf(userAddress);
// Write: costs gas, returns once mined, may still be reorganised.
const tx = await token.transfer(recipient, 1_000_000n, { gasLimit: 120_000n });
const receipt = await tx.wait(5); // wait for 5 confirmations
if (receipt.status !== 1) throw new Error("transaction reverted");
Operating this in production means respecting a handful of realities. Nonce management must be centralised: two workers signing with the same key will collide, so serialise submissions per key and implement replacement-by-fee for stuck transactions. Never hold a private key in application memory or an environment variable if you can avoid it — use a hardware module or managed signing service, with spend limits and separate keys per environment. Estimate gas but cap it, since an estimate taken against a stale state can be wildly wrong. Treat the RPC endpoint as unreliable: run at least two providers and compare block heights. And index events with a persisted cursor, waiting a confirmation margin and keying handlers on transaction hash plus log index so replays are harmless.
Upgradeability
Deployed bytecode cannot change, so upgradeable systems put a proxy in front of it. The proxy holds the storage and the address of an implementation contract, and forwards every call with delegatecall, executing the implementation's code against the proxy's storage. Swapping the implementation address changes behaviour while keeping state and address.
The discipline this demands is unforgiving. Storage layout must be append-only across versions, because the implementation reads slots positionally; inserting a variable in the middle silently corrupts everything after it. Constructors do not run for the implementation, so initialisation moves to an initialize function guarded against being called twice. Function selectors must not clash between proxy and implementation. And the upgrade key becomes the most valuable secret in the system, which is why credible projects place it behind a multi-signature wallet and a timelock so users can see a change coming and exit first.
Upgradeability also weakens the core promise: a contract that can be replaced is only as trustworthy as its administrators. Some protocols therefore deploy immutable contracts and handle change by migration — new contracts, and users move. That is more honest and considerably more work.
The vulnerability classes that matter
Most losses cluster into a handful of patterns.
Reentrancy. An external call hands control to another contract, which calls back into yours before the first invocation finished updating state — so a withdrawal function that sends ether and then zeroes the balance can be drained in a loop. The fix is structural: checks, effects, interactions — validate inputs, update your state, and only then call out. A reentrancy guard adds defence in depth, and note that ERC-721 receiver hooks and token transfer callbacks are external calls even when they do not look like one.
Access control. Missing or wrong authorisation on privileged functions, initialisers left callable, tx.origin used for authentication (it identifies the transaction's original sender, so any contract the user calls can impersonate them). Use msg.sender with an explicit role check, and enumerate every privileged entry point in review.
Arithmetic and casting. Overflow reverts by default since Solidity 0.8, but explicit unchecked blocks and downcasts such as uint256 to uint128 still truncate silently. Integer division always truncates, so ordering matters: multiply before dividing, and be deliberate about which side of a rounding error the protocol sits on.
Oracle manipulation. A contract that reads a price from an on-chain pool can be attacked by moving that pool within a single transaction, frequently funded by a flash loan. Use time-weighted averages or a decentralised oracle network with multiple independent reporters, and never trust a spot price from a shallow pool.
Transaction ordering and front-running. Pending transactions are public before inclusion, and proposers order them for profit. A trade with no slippage bound can be sandwiched; a commitment revealed too early can be copied. Mitigations include commit-reveal schemes, explicit slippage and deadline parameters, and private submission channels.
Denial of service by external dependency. Pushing funds to a list of recipients fails entirely if one recipient reverts. Prefer a pull-payments pattern where each party withdraws their own balance.
Signature handling. Replay across chains or contracts when the domain separator is omitted, malleable signatures, and missing nonces. Follow the typed-structured-data standard and include a chain id, a contract address and a nonce in everything you sign.
The broad security thinking in application security architecture still applies — least privilege, defence in depth, explicit trust boundaries — with the difference that here the attacker is funded, automated, and reading your source code before you finish deploying it.
Key takeaways
- Only key-controlled accounts start transactions; contracts react, and every operation is metered in gas with storage priced far above computation.
- Read Solidity with the trust boundary in mind: all state is public, external calls hand over control, and low-level calls do not revert on failure.
- Implement ERC-20 and ERC-721 from audited references, and never assume 18 decimals or grant unlimited allowances by default.
- Test with fuzzing and invariants, analyse statically in CI, verify published source, and audit before the contract holds real value.
- Backends need centralised nonce management, hardware-backed signing, redundant RPC providers and idempotent event indexing with a confirmation margin.
- Proxy upgradeability requires append-only storage layouts and moves trust to whoever holds the upgrade key — a timelock and multi-signature are the minimum.
- Reentrancy, broken access control, silent casts, manipulable oracles and transaction ordering account for most exploits; checks-effects-interactions and pull payments prevent a large share of them.
Sources and further reading
Frequently asked questions
- Can a deployed contract be changed?
- Not directly — deployed bytecode is immutable. Teams that need changeability deploy a proxy holding the state and delegating execution to an implementation address that can be swapped. That buys upgradeability at the cost of a governance mechanism, storage-layout discipline and an added trust assumption, since whoever controls the upgrade effectively controls the funds.
- Why is storage so expensive compared with computation?
- Every storage slot must be kept by every node forever, so its cost reflects a permanent obligation on the whole network rather than a one-off computation. Writing a new non-zero slot costs far more than arithmetic or memory, refunds are given for clearing slots, and the standard optimisations are packing variables, using events for history and keeping bulk data off-chain.
- Do I still need SafeMath in modern Solidity?
- No. Since version 0.8.0 arithmetic reverts on overflow and underflow by default, so the library is redundant. Where you have proven a bound and want the gas saving, an explicit unchecked block documents the decision. Casting between integer widths still truncates silently, so downcasts remain a place to look carefully.
- How should a backend service track on-chain events reliably?
- Poll or subscribe for logs, but persist a cursor of the last processed block and wait a safety margin of confirmations before acting, because recent blocks can be reorganised. Make handlers idempotent using the transaction hash and log index as a key, and reconcile periodically by re-reading a window of blocks rather than trusting a live stream alone.