Erste Schritte
Contract-Grundlagen
Solidity ist die Hauptsprache für Ethereum-Smart-Contracts. pragma setzt die Compiler-Version. Ein Contract ist wie eine Klasse. Funktionen können public, private, view (nur lesend) oder payable sein.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 storedData;
function set(uint256 x) public {
storedData = x;
}
function get() public view returns (uint256) {
return storedData;
}
}Pragma & Compiler-Version
pragma spezifiziert die Compiler-Version. ^0.8.0 erlaubt jeden 0.8.x-Patch. Für Produktion die Version exakt festnageln (0.8.19), um Überraschungen zu vermeiden. Das pragma immer am Anfang jeder .sol-Datei einschließen.
// Lock to a single version
pragma solidity 0.8.19;
// Allow patches (^0.8.0 means >=0.8.0 <0.9.0)
pragma solidity ^0.8.0;
// Range of versions
pragma solidity >=0.8.0 <0.9.0;
// Experimental features (ABIEncoderV2 in older versions)
pragma experimental ABIEncoderV2;Kommentare & NatSpec
NatSpec-Kommentare (/// oder /** */) erzeugen Dokumentation. @notice ist für Endnutzer, @dev für Entwickler, @param beschreibt Parameter, @return beschreibt Rückgabewerte. Sie werden von Tools wie Etherscan und Remix aufgegriffen.
// Single-line comment
/* Multi-line
comment */
/// @title A Simple Contract
/// @author Alice
/// @notice This is visible to end users
/// @dev This is for developers
contract Commented {
/// @notice Sets the value
/// @param _x The new value
/// @dev Internal details here
function set(uint256 _x) public {}
}SPDX-Lizenz
Seit Solidity 0.6.8 ist der SPDX-Lizenzbezeichner am Dateianfang Pflicht. Er hilft Tools und Nutzern zu verstehen, wie der Code wiederverwendet werden darf. MIT für permissive Open Source, GPL-3.0 für Copyleft oder UNLICENSED für privaten Code.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Common licenses:
// MIT - permissive
// GPL-3.0 - copyleft
// Apache-2.0 - permissive with patent grant
// UNLICENSED - private/no license
// BSD-2-Clause, BSD-3-Clause
contract Licensed {}Dateistruktur & Imports
Imports bringen Contracts, Bibliotheken oder Interfaces herein. {Name} nutzen, um nur bestimmte Items zu importieren. Relative Pfade funktionieren wie erwartet. Das Schlüsselwort 'is' legt Vererbung fest. Dateien haben typisch einen Haupt-Contract, können aber mehrere enthalten.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OtherContract.sol";
import {SpecificContract, Helper} from "./Library.sol";
import * as Lib from "./Library.sol"; // namespace
import "openzeppelin/contracts/token/ERC20.sol";
contract MyContract is OtherContract {
// ...
}Werttypen
Ganzzahlen (uint / int)
uint = vorzeichenlos (keine Negativen), int = vorzeichenbehaftet. Größen reichen von 8 bis 256 in Schritten von 8. uint ist standardmäßig uint256. Seit 0.8.0 prüft Arithmetik automatisch auf Overflow/Underflow und revert-t. type(T).max / type(T).min nutzen, um Grenzen zu bekommen.
uint256 public bigNumber = 1 ether; // 10^18
uint8 public small = 255; // max 255
int256 public signed = -100;
uint public defaultSize = 42; // uint256 by default
// Arithmetic
uint256 a = 10;
uint256 b = 3;
uint256 sum = a + b; // 13
uint256 diff = a - b; // 7 (0.8+ reverts on underflow)
uint256 product = a * b; // 30
uint256 quotient = a / b; // 3
uint256 remainder = a % b; // 1
uint256 power = a ** 2; // 100
// Type min/max (0.8+)
uint256 max = type(uint256).max;
int256 min = type(int256).min;Boolean
bool kann nur true oder false sein. && und || kurzschließen, d. h. die rechte Seite wird nur bei Bedarf ausgewertet. Der Defaultwert ist false. Booleans kosten in manchen Kontexten (Storage Packing) mehr Gas als uint256.
bool public flag = true;
bool public negated = !flag; // false
bool public and = flag && false; // false
bool public or = flag || false; // true
// Short-circuit evaluation
bool result = (flag && expensiveCall()); // skips call if flag false
bool result2 = (!flag || expensiveCall());
// Equality
bool equal = (1 == 1); // true
bool notEq = (1 != 2); // true
// Boolean defaults to false
bool public defaultValue; // falseAddress
address hält eine 20-Byte-Ethereum-Adresse. address payable kann Ether empfangen (hat transfer/send-Methoden). payable(x) zum Konvertieren. Adressen haben die Eigenschaft .balance (in wei). Adress-Literale immer gegen die EIP-55-Checksumme prüfen, um Tippfehler zu erwischen.
address public owner = msg.sender;
address payable public treasury = payable(owner);
// Balance (read-only)
uint256 bal = owner.balance; // in wei
// Send Ether (payable address only)
treasury.transfer(1 ether);
bool sent = treasury.send(1 ether);
// Convert from address to payable
address addr = 0x123...;
address payable payableAddr = payable(addr);
// Address literals (checksummed)
address public constant BURN = 0x000000000000000000000000000000000000dEaD;
// Compare addresses
bool same = (addr1 == addr2);Bytes & Byte-Arrays
Feste Bytes (bytes1..bytes32) sind billig und dienen Hashes/Selektoren. Dynamisches bytes ist für rohe Binärdaten; string für UTF-8-Text. bytes32 für Hashes nutzen (keccak256 liefert bytes32). bytes.concat() (0.8.4+) ist billiger als abi.encodePacked für Byte-Arrays.
// Fixed-size byte arrays (bytes1 to bytes32)
bytes32 public hash = keccak256(abi.encodePacked("data"));
bytes1 public b1 = 0x41; // single byte
bytes4 public selector = bytes4(keccak256("transfer(address,uint256)"));
// Dynamic byte arrays
bytes public dynamic = "hello";
bytes public empty;
// String vs bytes
string public text = "Hello"; // UTF-8 string
bytes public raw = bytes(text);
// Operations on fixed bytes
bytes32 data = keccak256(abi.encode("x"));
bytes1 first = data[0]; // access by index
uint256 length = data.length; // 32
// Concatenation
bytes memory combined = bytes.concat(bytes("a"), bytes("b"));Enums
Enums definieren eine endliche Menge benannter Werte. Sie werden als uint8 gespeichert (max. 256 Mitglieder). Der Defaultwert ist das erste Mitglied (Index 0). Zwischen enum und uint per Casts konvertieren. type(EnumName).max liefert das höchste Mitglied.
contract EnumExample {
enum Status { Pending, Active, Paused, Closed }
Status public status = Status.Pending;
function activate() public {
require(status == Status.Pending, "Not pending");
status = Status.Active;
}
function next() public {
// Cast to uint to do math
uint current = uint(status);
if (current < uint(type(Status).max)) {
status = Status(current + 1);
}
}
// Default value is the first member (Pending)
Status public defaultValue; // Pending
}Typkonvertierung & Casting
Implizite Konvertierung passiert nur, wenn kein Datenverlust möglich ist (uint8 -> uint256). Für Verengungen (uint256 -> uint8) oder vorzeichenbehaftet/unvorzeichenbehaftet explizite Casts verwenden. Die Konvertierung eines negativen int nach uint ergibt eine riesige Zahl wegen des Zweierkomplements.
// Implicit conversion (safe, widening)
uint8 small = 10;
uint256 big = small; // OK: uint8 fits in uint256
// Explicit conversion (narrowing, may lose data)
uint256 large = 300;
uint8 narrow = uint8(large); // truncates to 44 (300 % 256)
// Address conversion
address addr = 0xAb8483F64d9C6d1Ec37F8D2C4fA6bA5d5C5e5C5e;
address payable payableAddr = payable(addr);
// Bytes conversion
bytes32 b32 = bytes32(uint256(42));
uint256 num = uint256(b32);
bytes4 selector = bytes4(keccak256("foo()"));
// String <-> bytes
string memory s = "hi";
bytes memory bs = bytes(s);
string memory s2 = string(bs);
// int <-> uint (explicit, watch for negatives)
int256 signed = -5;
uint256 unsigned = uint256(signed); // huge number!Referenztypen
String
Strings in Solidity sind UTF-8-Byte-Arrays — length() liefert die Byte- nicht die Zeichenzahl (Emoji/Multibyte-Zeichen weichen ab). Gleichheit muss über den keccak256-Hash geprüft werden. string.concat (0.8.12+) ist billiger als abi.encodePacked. Strings sind gas-teuer.
contract Strings {
string public greeting = "Hello, World!";
function concat(string memory a, string memory b)
public pure returns (string memory)
{
return string.concat(a, " ", b); // 0.8.12+
}
function length(string memory s) public pure returns (uint256) {
return bytes(s).length; // byte length, not char count
}
function equals(string memory a, string memory b)
public pure returns (bool)
{
return keccak256(bytes(a)) == keccak256(bytes(b));
}
// Storage string (state variable)
string public stored;
function set(string memory s) public { stored = s; }
}Arrays (fix & dynamisch)
Feste Arrays [N] haben eine Compile-Zeit-Größe; dynamische Arrays [] wachsen mit push/pop. Memory-Arrays müssen mit 'new Type[](size)' erzeugt werden. Storage-Arrays zu lesen/schreiben kostet Gas; für temporäre Daten memory bevorzugen. push() liefert ab 0.6+ eine Referenz.
contract Arrays {
// Fixed-size array
uint256[5] public fixedArr = [1, 2, 3, 4, 5];
// Dynamic array
uint256[] public dynamicArr;
function pushPop() public {
dynamicArr.push(10); // append: [10]
dynamicArr.push(20); // [10, 20]
dynamicArr.pop(); // remove last: [10]
}
function getLength() public view returns (uint256) {
return dynamicArr.length;
}
function iterate() public view returns (uint256 sum) {
for (uint256 i = 0; i < dynamicArr.length; i++) {
sum += dynamicArr[i];
}
}
// Array of arrays (2D)
uint256[][] public matrix;
// Memory array (must have fixed length when created)
function memArray() public pure returns (uint256[] memory) {
uint256[] memory arr = new uint256[](3);
arr[0] = 1; arr[1] = 2; arr[2] = 3;
return arr;
}
}Structs
Structs gruppieren verwandte Felder. Sie können im storage liegen, im memory oder als Funktionsargumente durchgereicht werden. Auf Datei- oder Contract-Ebene definieren. Initialisierung mit benannten Feldern {field: value} ist klarer; positional ist kürzer. Mapping-Werte können in älteren Versionen nicht als Ganzes strukturiert angesprochen werden.
contract Structs {
struct User {
address wallet;
uint256 balance;
bool active;
string name;
}
// Single struct (storage)
User public owner;
User[] public users; // array of structs
mapping(address => User) public userByAddr;
function createUser(string memory name) public {
User memory u = User({
wallet: msg.sender,
balance: 100,
active: true,
name: name
});
users.push(u);
}
// Shorter syntax
function createShort() public {
users.push(User(msg.sender, 50, true, "anon"));
}
// Update a field
function deactivate(uint256 index) public {
users[index].active = false; // direct storage write
}
}Mappings
Mappings sind Hash-Tabellen: keccak256(key) => value. Sie haben keine Länge und sind nicht iterierbar. Schlüssel können Werttypen sein (uint, address, bytes, enum); Werte alles. Verschachtelte Mappings erlauben Mehrschlüssel-Lookups. Zum Iterieren ein separates Schlüssel-Array pflegen. delete setzt einen Schlüssel auf seinen Nullwert zurück.
contract Mappings {
// keyType => valueType
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => bool) public isRegistered;
function setBalance(uint256 amount) public {
balances[msg.sender] = amount;
}
function approve(address spender, uint256 amount) public {
allowance[msg.sender][spender] = amount;
}
function register() public {
isRegistered[msg.sender] = true;
}
// Iterable mapping pattern
address[] public userList;
mapping(address => bool) public exists;
function addUser(address u) public {
if (!exists[u]) {
userList.push(u);
exists[u] = true;
}
}
// CANNOT iterate or get length of a mapping directly
// CANNOT delete a mapping, only individual keys
function remove() public {
delete balances[msg.sender]; // sets to 0
}
}Datenorte (storage / memory / calldata)
storage = dauerhafter On-Chain-Zustand (teuer). memory = temporär, lebt während des Funktionsaufrufs (billig). calldata = nur lesend, nur für Eingaben external-Funktionen (am billigsten). Für nur gelesene Argumente external-Funktionen immer calldata verwenden. Standardort: State-Variablen sind storage; lokale komplexe Typen in Funktionen sind standardmäßig memory.
contract DataLocations {
string public stateVar; // storage (state)
function f(string calldata input) external {
// calldata: read-only, only for external function args
string memory local = input; // memory: temporary copy
stateVar = local; // writes to storage
// storage reference (only inside a function)
string storage ref = stateVar;
ref = "new value"; // modifies stateVar
}
// External params can be calldata (cheapest)
function g(string calldata s) external pure returns (bytes32) {
return keccak256(bytes(s));
}
// Public/internal params default to memory
function h(string memory s) public pure returns (uint256) {
return bytes(s).length;
}
// Assignment rules:
// storage -> storage: reference (both point to same slot)
// memory -> memory: reference (both point to same memory)
// storage <-> memory: copy
}Verschachtelte Strukturen
Structs können Arrays, Mappings (nur im storage) und andere Structs enthalten. Der Zugriff auf verschachtelte Struct-Felder über eine storage-Referenz ist gas-effizient. Bei tiefer Verschachtelung vorsichtig — sie erhöht die Storage-Slot-Nutzung und die Deploy-Kosten. Mapping-of-Struct ist das häufigste On-Chain-Datenbankmuster.
contract Nested {
struct Order {
uint256 id;
uint256 amount;
Item[] items;
}
struct Item {
string sku;
uint256 qty;
}
mapping(uint256 => Order) public orders;
Order[] public allOrders;
function addOrder(uint256 id, string memory sku, uint256 qty) public {
Order storage o = orders[id];
o.id = id;
o.amount += qty * 1 ether;
o.items.push(Item(sku, qty));
}
// Mapping of struct arrays
mapping(address => Item[]) public userItems;
// Struct in a struct
struct Profile {
User user;
uint256 score;
}
struct User {
address addr;
string name;
}
Profile public profile;
}State-Variablen
Öffentliche & private State-Variablen
public-State-Variablen erzeugen automatisch eine Getter-Funktion. private beschränkt den Zugriff auf den Contract; internal erlaubt auch Subklassen. Default ist internal. KRITISCH: 'private' heißt NICHT geheim — alle Blockchain-Daten sind öffentlich lesbar. Für Vertraulichkeit Verschlüsselung/Hashing nutzen.
contract Visibility {
uint256 public publicVar = 1; // auto getter created
uint256 private privateVar = 2; // only this contract
uint256 internal internalVar = 3; // this + subclasses
// No 'external' for state variables
// internal is the default
uint256 defaultVar = 4; // internal
function readPrivate() public view returns (uint256) {
return privateVar; // readable from inside
}
// 'private' only means 'not via other contracts'.
// The data is still visible on-chain!
}
// public creates an automatic getter:
// function publicVar() external view returns (uint256) { return publicVar; }Konstante Variablen
constant-Variablen werden zur Compile-Zeit ausgewertet und in den Bytecode inlined — sie kosten zur Laufzeit kein Gas (kein SLOAD). Nur Werttypen (uint, address, bytes usw.) können constant sein. Der Wert muss ein Compile-Zeit-Ausdruck sein. constant für fixe Werte wie MAX_SUPPLY, DECIMALS, Adressen.
contract Constants {
// constant: evaluated at compile time, inlined into code
uint256 public constant MAX_SUPPLY = 1_000_000 * 10**18;
address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
uint8 public constant DECIMALS = 18;
// Must be value types, assigned a literal/expression
// No assignment in constructor
// Numeric separators (1_000_000) work since 0.8.0
function compute() public pure returns (uint256) {
return MAX_SUPPLY / 2; // inlined, no SLOAD
}
}Immutable-Variablen
immutable-Variablen werden einmal im Konstruktor gesetzt und sind danach nur lesend. Sie liegen im Bytecode (nicht im Storage), Lesevorgänge kosten also weniger als bei regulären State-Variablen. Anders als constant darf immutable Konstruktorargumente und Laufzeitwerte nutzen. immutable für Dinge, die beim Deployment gesetzt werden, wie owner, Token-Name oder ketten-spezifische Konfiguration.
contract Immutable {
// immutable: set once in constructor, then read-only
address public immutable owner;
uint256 public immutable creationBlock;
constructor(address _owner) {
owner = _owner;
creationBlock = block.number;
}
// Can be any value type
// Cheaper than regular state vars (no SLOAD slot, uses code)
// More flexible than constant (can use constructor args)
function check() public view returns (bool) {
return msg.sender == owner; // cheap read
}
}
// Use case: factory-deployed contracts with constructor args
contract Factory {
Child[] public children;
function create(address owner) public {
children.push(new Child(owner));
}
}
contract Child {
address public immutable owner;
constructor(address _owner) { owner = _owner; }
}Globale Variablen (msg, tx, block)
msg liefert den Aufrufkontext: msg.sender (unmittelbarer Aufrufer), msg.value (gesendetes wei), msg.data (rohes calldata), msg.sig (Funktions-Selektor). tx liefert Transaktionsinfo: tx.origin (die EOA, NICHT für Auth empfohlen). block liefert den aktuellen Block: block.timestamp, block.number, block.chainid, block.coinbase. tx.origin nie für Autorisierung — msg.sender verwenden.
contract Globals {
function msgVars() public view returns (
address sender,
bytes4 selector,
uint256 value,
bytes memory data
) {
sender = msg.sender; // caller address
selector = msg.sig; // function selector
value = msg.value; // wei sent with tx
data = msg.data; // full calldata
}
function txVars() public view returns (address origin, uint256 gasprice) {
origin = tx.origin; // EOA that started the tx
gasprice = tx.gasprice; // gas price in wei
}
function blockVars() public view returns (
uint256 number,
uint256 timestamp,
address miner,
uint256 chainId
) {
number = block.number; // current block height
timestamp = block.timestamp; // current block time (uint256 in 0.8+)
miner = block.coinbase; // block miner/validator
chainId = block.chainid; // chain ID
}
}Block- & Tx-Eigenschaften
blockhash() liefert nur Hashes der letzten 256 Blöcke; ältere liefern 0. block.timestamp wird vom Miner gesetzt und kann um ~15 Sekunden abweichen — nie für präzises Timing oder Zufälligkeit nutzen. block.basefee stammt aus EIP-1559. gasleft() ersetzt das veraltete msg.gas. chainid ist kritisch für Replay-Schutz.
contract BlockProps {
function getBlockInfo() public view returns (
uint256 number,
uint256 timestamp,
uint256 gasLimit,
uint256 gasPrice,
uint256 baseFee
) {
number = block.number;
timestamp = block.timestamp;
gasLimit = block.gaslimit;
gasPrice = tx.gasprice;
baseFee = block.basefee; // EIP-1559 (London)
}
function getChainId() public view returns (uint256) {
return block.chainid;
}
function getPrevHash(uint256 n) public view returns (bytes32) {
require(n < 256, "out of range");
return blockhash(block.number - n); // last 256 blocks
}
function gasLeft() public view returns (uint256) {
return gasleft(); // remaining gas
}
}Funktionen
Funktionssyntax
Funktionssyntax: function name(params) visibility mutability returns(...). Sichtbarkeit (public/external/internal/private) ist Pflicht. Mutabilität (pure/view/payable) ist optional, aber empfohlen. Mehrere Rückgabewerte werden unterstützt. Benannte Rückgaben erlauben direkte Zuweisung ohne das return-Schlüsselwort.
contract Func {
// function name(params) <visibility> <state-mutability> returns(...)
function add(uint256 a, uint256 b)
public
pure
returns (uint256)
{
return a + b;
}
// Multiple returns
function split(uint256 x)
public pure returns (uint256, uint256)
{
return (x / 2, x % 2);
}
// Named returns (no explicit return needed)
function named(uint256 x)
public pure returns (uint256 half, uint256 rest)
{
half = x / 2;
rest = x % 2;
// return statement optional
}
// Destructure returns
function caller() public pure returns (uint256) {
(uint256 h, uint256 r) = named(10);
return h + r;
}
}View-Funktionen
view-Funktionen dürfen den Zustand lesen, aber nicht ändern. Extern via eth_call aufgerufen sind sie kostenlos (keine Gasgebühr). Intern aus einer modifizierenden Funktion aufgerufen verbrauchen sie Gas. view für jede Funktion nutzen, die nur liest — das signalisiert die Absicht und erlaubt kostenlose Off-Chain-Lesevorgänge.
contract ViewFn {
uint256 public counter = 0;
// view: can READ state but not modify
function getCount() public view returns (uint256) {
return counter; // reading state
}
function doubleCount() public view returns (uint256) {
return counter * 2; // reading state
}
// Can call other view/pure functions
function combined() public view returns (uint256) {
return getCount() + 1;
}
// CANNOT:
// - write to state variables
// - emit events
// - call non-view functions
// - use selfdestruct
// - send Ether
// view functions can be called off-chain for free (eth_call)
}Pure-Funktionen
pure-Funktionen dürfen den Zustand weder lesen noch schreiben — sie rechnen nur auf ihren Eingaben. Sie sind am stärksten eingeschränkt und off-chain am billigsten aufzurufen. pure für Utility-Funktionen (Mathe, Hashing von Eingaben). Brauchst du msg.sender oder Blockdaten, stattdessen view. pure darf nur andere pure-Funktionen aufrufen.
contract PureFn {
// pure: cannot read OR write state
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function square(uint256 x) public pure returns (uint256) {
return x * x;
}
// pure can only use:
// - function parameters
// - local memory variables
// - other pure functions
function combined(uint256 x) public pure returns (uint256) {
uint256 y = square(x); // calling another pure fn
return add(y, 1);
}
// CANNOT read: state variables, msg.sender, block.timestamp, etc.
// CANNOT call view functions
}Payable-Funktionen
payable-Funktionen können Ether via msg.value empfangen. Der Ether wird automatisch dem Kontostand des Contracts zugeschlagen. Nur payable-Funktionen und receive/fallback können Ether akzeptieren. msg.value immer validieren, wenn ein bestimmter Betrag erwartet wird. Nicht-payable-Funktionen revert-en, wenn Ether gesendet wird.
contract Payable {
address payable public owner;
constructor() {
owner = payable(msg.sender);
}
// payable: function can receive Ether
function deposit() public payable {
// msg.value is the amount of wei sent
// Ether is automatically added to contract balance
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
// Withdraw to owner
function withdraw() public {
require(msg.sender == owner, "not owner");
owner.transfer(address(this).balance);
}
// payable address (the contract itself can be paid)
receive() external payable {
// called when calldata is empty + value sent
}
}Rückgabewerte & benannte Rückgaben
Funktionen können mehrere Werte via Tupel zurückgeben. Benannte Rückgaben verbessern die Lesbarkeit und erlauben direkte Zuweisung ohne return-Anweisung. Explizite return-Anweisungen überschreiben benannte Rückgaben. Destructuring (a, b) = f() nutzen, um mehrere Rückgaben zu fangen; (, b) oder (a,), um nicht benötigte Werte zu überspringen.
contract Returns {
// Single return
function one() public pure returns (uint256) {
return 42;
}
// Multiple returns
function two() public pure returns (uint256, bool) {
return (1, true);
}
// Named returns — assign directly
function named() public pure returns (uint256 a, uint256 b) {
a = 1;
b = 2;
// no return keyword needed
}
// Mixed: explicit return overrides
function mixed(bool x) public pure returns (uint256 a, uint256 b) {
a = 1;
if (x) return (10, 20); // explicit return
b = 2;
}
// Destructuring assignment
function caller() public pure returns (uint256) {
(uint256 x, uint256 y) = two();
return x + y;
}
// Skip values with commas
function skip() public pure returns (bool) {
(, bool y) = two();
return y;
}
}Funktions-Overloading
Solidity unterstützt Funktions-Overloading: mehrere Funktionen gleichen Namens, aber unterschiedlichen Parametertypen oder -zahlen. Der Compiler entscheidet anhand der Argumenttypen. Der Rückgabetyp allein kann Overloads nicht unterscheiden. Overloads sind nützlich, um address und address payable oder verschiedene Zahlenbereiche zu akzeptieren.
contract Overload {
// Same name, different parameter types/counts
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function add(uint256 a, uint256 b, uint256 c) public pure returns (uint256) {
return a + b + c;
}
function add(string memory a, string memory b)
public pure returns (string memory)
{
return string.concat(a, b);
}
// Caller selects which via argument types
function test() public pure returns (uint256, uint256, string memory) {
return (add(1, 2), add(1, 2, 3), add("a", "b"));
}
// NOTE: return type alone does NOT distinguish overloads
// function f() returns (uint256) and f() returns (bool) — INVALID
}Konstruktor & Sonderfunktionen
Konstruktor
constructor läuft einmal beim Deploy des Contracts, zur Initialisierung des Zustands. Er ist nicht erneut aufrufbar. Konstruktorargumente werden je nach Framework an den Deployment-Bytecode angehängt oder via ABI übergeben. Bei Vererbung Parent-Konstruktorargumente in der Vererbungsliste übergeben (Owned(_owner)) oder im Modifikator-Stil (A() B()).
contract Owned {
address public owner;
// constructor runs once at deployment
constructor(address _owner) {
owner = _owner;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
// Inheritance: constructor args
contract Child is Owned {
constructor(address _owner) Owned(_owner) {}
}
// No constructor = default constructor (no args)
contract NoCtor {}
// Multiple inheritance: order matters
contract A { constructor() {} }
contract B { constructor() {} }
contract C is A, B {
constructor() A() B() {}
}Receive-Funktion
receive() wird aufgerufen, wenn ein Aufruf ohne calldata Ether sendet (z. B. send/transfer an den Contract). Sie muss 'external payable' ohne Argumente oder Rückgaben sein. Nur eine receive-Funktion ist erlaubt. Fehlt sie und es gibt keinen fallback, revert-en plain Ether-Transfers (außer via selfdestruct, das Ether erzwingen kann).
contract Receiver {
event Received(address from, uint256 amount);
// receive: called on plain Ether transfers (no calldata)
// Must be 'external payable', no args, no returns
// Only ONE receive per contract
receive() external payable {
emit Received(msg.sender, msg.value);
}
// Triggered by: transfer(), send(), or empty calldata tx
// Use this to react to incoming Ether
function balance() public view returns (uint256) {
return address(this).balance;
}
}
// If no receive/fallback exists, the contract rejects plain Ether.
// Exception: contracts can be forced via selfdestruct (always).Fallback-Funktion
fallback() wird aufgerufen, wenn keine Funktion zum Selektor passt, oder wenn receive fehlt und ein plain Ether-Transfer versucht wird. Sie kann payable sein. Fallback-Logik minimal halten — beim Aufruf via send()/transfer() hat sie nur 2300 Gas (den Stipend), was Storage-Schreibvorgänge oder Event-Emission nicht deckt.
contract Fallback {
event Log(string message, address from, uint256 value, bytes data);
// fallback: called when no function matches the calldata
// OR when receive is absent and calldata is empty
fallback() external payable {
emit Log("fallback", msg.sender, msg.value, msg.data);
}
// With calldata (function not found)
// Without calldata + no receive => fallback runs
// Modern: separate receive and fallback
// receive() external payable { ... } // empty calldata + value
// fallback() external payable { ... } // unknown function
// Make fallback cheap — it can run out of gas on send()/transfer() (2300 stipend)
function safeFallback() external {
// logic here must be < 2300 gas if called via transfer/send
}
}Selfdestruct
selfdestruct sendet allen verbleibenden Ether an eine angegebene Adresse und (vor Dencun) entfernt den Contract-Code. Nach EIP-6780 (März 2024) entfernt es Code nur, wenn im selben Deployment-Transaction aufgerufen — sonst transferiert es nur Ether. selfdestruct niemals für Sicherheit verlassen: erzwungener Ether kann weiterhin ankommen, und Code kann bestehen bleiben.
contract SelfDestruct {
address payable public owner;
constructor() { owner = payable(msg.sender); }
function destroy() public {
require(msg.sender == owner, "not owner");
// Sends all Ether to recipient, then deletes the contract
selfdestruct(payable(msg.sender));
}
}
// IMPORTANT WARNINGS:
// - After EIP-6780 (Dencun), selfdestruct no longer deletes code
// unless called in the same transaction that deployed the contract
// - It still sends all Ether to the recipient
// - The recipient could be a contract with no receive/fallback and
// it still gets the Ether (forced transfer)
// - Do NOT rely on selfdestruct for security; prefer a 'paused' flagFunktions-Selektor
Jede Funktion hat einen 4-Byte-Selektor = die ersten 4 Bytes von keccak256(Signatur). Die Signatur ist der Funktionsname und die Parametertypen ohne Leerzeichen, z. B. 'transfer(address,uint256)'. Die EVM nutzt den Selektor, um Aufrufe zu routen. msg.sig liefert den Selektor der aktuellen Funktion. abi.encodeWithSelector/Signature bauen calldata für Low-Level-Aufrufe.
contract Selector {
// First 4 bytes of keccak256 of the function signature
// signature = "functionName(paramType1,paramType2,...)"
bytes4 public constant SELECTOR =
bytes4(keccak256("transfer(address,uint256)"));
function getSelector() public pure returns (bytes4) {
return bytes4(keccak256("transfer(address,uint256)")));
// = 0xa9059cbb
}
function thisSelector() public pure returns (bytes4) {
return msg.sig; // selector of the currently running function
}
// Used for low-level calls
function callTransfer(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
return (ok, data);
}
// abi.encodeWithSignature uses the string form
function altCall(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
return token.call(
abi.encodeWithSignature("transfer(address,uint256)", to, amount)
);
}
}Modifikatoren
Modifikator-Grundlagen
Modifikatoren umhüllen Funktionen mit wiederverwendbaren Vor-/Nachbedingungen. Der Platzhalter _; ist, wo der Funktionskörper läuft. Modifikatoren sind super für Zugriffskontrolle (onlyOwner), Validierung (validInput) und Reentrancy-Guards. Sie greifen standardmäßig vor dem Funktionskörper — mit _; steuerst du, wo der Körper läuft.
contract ModBasics {
address public owner;
uint256 public count;
constructor() { owner = msg.sender; }
// Define a modifier
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_; // placeholder for the function body
}
// Apply it
function increment() public onlyOwner {
count += 1;
}
function reset() public onlyOwner {
count = 0;
}
// Anyone can read
function getCount() public view returns (uint256) {
return count;
}
}Modifikator mit Argumenten
Modifikatoren dürfen Argumente nehmen, was sie flexibel macht. Die Argumente werden an der Aufrufstelle ausgewertet und beim Modifikatorlauf gebunden. Übliche Muster: costs(price) für Pay-per-Call, onlyRole(role) für RBAC, rateLimit(window) für Drosselung. Logik vor _; ist Vorbedingung, danach Nachbedingung.
contract ModArgs {
modifier costs(uint256 price) {
require(msg.value >= price, "insufficient payment");
_;
// optional: refund excess after function runs
if (msg.value > price) {
payable(msg.sender).transfer(msg.value - price);
}
}
modifier onlyAddress(address allowed) {
require(msg.sender == allowed, "not allowed");
_;
}
function buyItem() public payable costs(1 ether) {
// msg.value must be >= 1 ether to enter
// excess refunded after body runs
}
function adminOnly() public onlyAddress(0xAbC...) {
// restricted to a hardcoded address
}
}Mehrere Modifikatoren
Eine Funktion darf mehrere Modifikatoren haben. Sie laufen der Reihe nach und umhüllen den Funktionskörper wie ein Stack: die Vorbedingung des ersten Modifikators zuerst, dann die des zweiten, ..., dann der Körper, dann entwinden sie sich rückwärts. Die Reihenfolge zählt — billigste/am wahrscheinlichsten scheiternde Checks zuerst, um Gas zu sparen.
contract MultiMod {
address public owner;
bool public paused;
uint256 public value;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier validValue(uint256 v) {
require(v > 0, "invalid value");
_;
}
// Multiple modifiers — executed in order
// Stack-like: A B body B' A'
function setValue(uint256 v)
public
onlyOwner // 1. check owner
whenNotPaused // 2. check not paused
validValue(v) // 3. validate input
{
value = v;
}
}Modifikator-Reihenfolge & Gas
Die Modifikatorreihenfolge wirkt auf Gas und Klarheit. Billige Checks zuerst (Booleans, Adressvergleiche) und teure zuletzt (Storage-Schreibvorgänge, externe Aufrufe). Auch die Checks, die am wahrscheinlichsten scheitern, zuerst — das short-circuited und erstattet ungenutztes Gas. Die beabsichtigte Reihenfolge mit Kommentaren dokumentieren.
contract ModOrder {
// Order modifiers from cheapest to most expensive
// OR most likely to fail first (to short-circuit)
modifier onlyOwner() { require(msg.sender == owner, "1"); _; }
modifier nonZero(uint256 x) { require(x != 0, "2"); _; }
modifier withinRange(uint256 x) {
require(x >= 1 && x <= 100, "3");
_;
}
modifier notPaused() { require(!paused, "4"); _; }
// Good order: cheap + likely-to-fail first
function good(uint256 x)
public
notPaused // 1. cheap bool check
onlyOwner // 2. address compare
nonZero(x) // 3. cheap input check
withinRange(x) // 4. more complex range check
{}
address public owner;
bool public paused;
constructor() { owner = msg.sender; }
}Häufige Modifikator-Muster
Häufige Modifikator-Muster: nonReentrant (Lock vor dem Körper setzen, danach lösen), whenNotPaused/whenPaused (Circuit-Breaker), onlyRole (RBAC mit bytes32-Rollen), rateLimit (Drosselung pro Nutzer über Zeitstempel). Der Reentrancy-Guard ist der wichtigste — auf jede Funktion anwenden, die nach einer Zustandsänderung einen externen Aufruf macht.
contract Patterns {
// 1. Reentrancy guard
uint256 private _status = 1;
modifier nonReentrant() {
require(_status == 1, "reentrant");
_status = 2;
_;
_status = 1;
}
// 2. Pausable
bool public paused;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not paused");
_;
}
// 3. Role-based
mapping(bytes32 => bool) public hasRole;
modifier onlyRole(bytes32 role) {
require(hasRole[role], "missing role");
_;
}
// 4. Rate limit (basic)
mapping(address => uint256) public lastCall;
modifier rateLimit() {
require(block.timestamp >= lastCall[msg.sender] + 1 minutes, "rate");
lastCall[msg.sender] = block.timestamp;
_;
}
}Events
Event-Deklaration & Emit
Events werden auf die Blockchain geloggt und von Off-Chain-Clients lesbar (via eth_getLogs). Für andere Contracts sind sie NICHT lesbar. indexed auf bis zu 3 Parametern nutzen, um sie filterbar zu machen. Events kosten weniger Gas als Storage-Schreibvorgänge. Für wichtige Zustandsänderungen immer Events emittieren, damit dApps und Indexer reagieren können.
contract Events {
// Declare event (outside functions, can be at file level)
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public balances;
function transfer(address to, uint256 amount) public returns (bool) {
require(balances[msg.sender] >= amount, "insufficient");
balances[msg.sender] -= amount;
balances[to] += amount;
// Emit the event
emit Transfer(msg.sender, to, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
emit Approval(msg.sender, spender, amount);
return true;
}
}Indexierte Parameter
indexierte Parameter werden zu Topics, auf die Off-Chain-Clients (dApps, The Graph, Indexer) filtern können. Maximal 3 indexierte Params pro Event (das 4. Topic ist für den Event-Signatur-Hash reserviert). Indexierte Werttypen (uint, address) werden direkt gespeichert; indexierte Referenztypen (string, bytes, Arrays) werden keccak256-gehasht und sind nicht wiederherstellbar.
contract Indexed {
// Up to 3 indexed params (in non-anonymous events)
// Indexed params become 'topics' that clients can filter on
event OrderPlaced(
address indexed buyer, // topic 1
address indexed token, // topic 2
uint256 indexed orderId, // topic 3
uint256 amount, // data (not filterable)
uint256 price // data
);
function placeOrder(address token, uint256 amount, uint256 price)
public returns (uint256 id)
{
id = uint256(keccak256(abi.encodePacked(msg.sender, block.number)));
emit OrderPlaced(msg.sender, token, id, amount, price);
}
// Clients can filter:
// eth_getLogs({topics: [sig, buyerAddr, tokenAddr, orderId]})
//
// Indexed arrays/strings/bytes are hashed (keccak256) —
// you can't recover the original value, only compare hashes.
}Anonyme Events
Anonyme Events überspringen den Event-Signatur-Hash in topic[0] und geben einen Slot frei — so bekommst du 4 indexierte Params statt 3. Der Trade-off: Clients können nicht nach Event-Namen (Signatur) filtern, mehrere anonyme Events in einem Contract sind also schwerer zu unterscheiden. Selten nützlich; die Gasersparnis ist winzig.
contract Anonymous {
// anonymous: skips storing the event signature as topic[0]
// So you can have up to 4 indexed params instead of 3
event Log(
address indexed from,
address indexed to,
uint256 indexed amount,
uint256 indexed timestamp, // 4th indexed (only with anonymous)
bytes data
) anonymous;
function log() public {
emit Log(msg.sender, address(0), 100, block.timestamp, "");
}
// Trade-offs:
// + 1 more indexed param allowed
// - Clients cannot filter by event signature
// - Harder to distinguish multiple anonymous events
// - Slightly cheaper gas
// Rarely used; prefer named events for clarity.
}Event-Best-Practices
Best Practices: nach Zustandsänderungen emittieren (das Event spiegelt also den Endzustand), Felder einschließen, die Indexern Extra-RPC-Aufrufe ersparen (wie newBalance), Emission in engen Schleifen vermeiden (stattdessen bündeln) und die meistgefilterten Felder indexieren (Adressen, IDs, Statuscodes). Events sind der Hauptkommunikationskanal Contract-zu-Off-Chain.
contract EventBest {
// 1. Name events with past tense or noun: Transfer, Deposit, OrderPlaced
event Transfer(address indexed from, address indexed to, uint256 value);
// 2. Emit AFTER state changes succeed
mapping(address => uint256) public balances;
function transfer(address to, uint256 amt) public {
balances[msg.sender] -= amt; // state first
balances[to] += amt;
emit Transfer(msg.sender, to, amt); // event after
}
// 3. Include enough data to reconstruct state
event Deposit(
address indexed account,
uint256 amount,
uint256 newBalance, // helps indexers avoid extra reads
uint256 timestamp
);
// 4. Don't emit in a loop — batch instead
event BatchTransfer(address[] to, uint256[] amounts);
function batch(address[] memory to, uint256[] memory amounts) public {
emit BatchTransfer(to, amounts); // one event, not N
}
// 5. Index the fields users filter on (addresses, IDs)
}Events vs. Logs vs. Storage
Storage liegt im State-Trie — für andere Contracts und View-Funktionen lesbar, aber teuer (~20k Gas pro SSTORE). Events/Logs liegen im Receipt-Trie — für Contracts NICHT lesbar, aber billig (~1-2k Gas) und off-chain via eth_getLogs zugänglich. Storage für On-Chain-Entscheidungen, Events, um Zustandsänderungen an dApps und Indexer zu melden.
contract Compare {
// Storage: persistent, readable by contracts, expensive
uint256 public storedValue; // SSTORE costs ~20k gas
// Events (logs): persistent-ish, NOT readable by contracts, cheap
event ValueChanged(uint256 oldValue, uint256 newValue);
function set(uint256 newValue) public {
uint256 old = storedValue;
storedValue = newValue; // SSTORE (~20k gas)
emit ValueChanged(old, newValue); // LOG (~1-2k gas)
}
// Logs live in the block's receipt trie, NOT the state trie.
// They are NOT accessible from other contracts.
// function readLog() public view returns (...) {
// CANNOT access emitted events
// }
// Off-chain tools (dApps, The Graph) read logs via eth_getLogs.
// Use storage for on-chain logic; events for off-chain observers.
}Fehlerbehandlung
Require
require(cond, msg) revert-t die Transaktion und erstattet ungenutztes Gas, wenn cond falsch ist. Es ist die häufigste Validierungs-Primitive — für Eingabechecks, Zugriffskontrolle und Vorbedingungen. Der Meldungsstring kostet Gas (im Deployment-Bytecode gespeichert). Für Gasersparnis eigene Fehler nutzen (revert ErrorName()) statt String-Meldungen.
contract Require {
mapping(address => uint256) public balances;
function deposit() public payable {
require(msg.value > 0, "must send ether");
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) public {
// require(condition, message)
// Reverts with the message if condition is false
// Refunds all unused gas to the caller (post-0.8.0 with custom errors, also refunds)
require(balances[msg.sender] >= amount, "insufficient balance");
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
// Pre-0.8.0: require with no message was cheaper
// 0.8.4+: prefer custom errors (cheaper, see other item)
function cheap(uint256 x) public pure {
if (x == 0) revert ZeroValue(); // custom error
}
error ZeroValue();
}Revert
revert(msg) revert-t die Transaktion explizit mit einem Begründungsstring. revert() innerhalb von if-Anweisungen nutzen, wenn verzweigende Logik nötig ist (require ist nur syntaktischer Zucker). revert() ohne Meldung ist billiger als revert("msg"). Eigene Fehler (revert ErrorName(args)) sind am billigsten und beschreibendsten — in neuem Code bevorzugen.
contract Revert {
function explicit(uint256 x) public pure {
if (x == 0) {
revert("zero not allowed"); // explicit revert with message
}
if (x > 100) {
revert("too big"); // can place anywhere
}
}
// revert() with no message (cheapest string revert)
function silent(uint256 x) public pure {
if (x == 0) revert(); // no reason
}
// Custom error (0.8.4+) — recommended
error TooBig(uint256 given, uint256 max);
function custom(uint256 x) public pure {
if (x > 100) revert TooBig(x, 100);
}
// Inside an internal function, revert propagates up
function caller(uint256 x) public pure {
inner(x); // reverts here if x is bad
}
function inner(uint256 x) internal pure {
if (x == 0) revert("zero");
}
}Assert
assert(cond) ist für Invarianten, die bei korrektem Code nie falsch sein sollten — ein gescheitertes assert deutet auf einen Bug. Vor 0.8.0 verbrauchte assert alles Gas; seit 0.8.0 verhält es sich wie revert. require für Eingabevalidierung und erwartete Fehlerbedingungen; assert nur für unmögliche Zustände, die einen Bug anzeigen. Moderne Auto-Overflow-Checks nutzen revert, nicht assert.
contract Assert {
function check(uint256 x) public pure returns (uint256) {
uint256 result = x + 1;
// assert: for invariants that should NEVER be false
// If it fails, something is critically broken.
assert(result > x); // overflow check (auto in 0.8+)
return result;
}
// Pre-0.8.0: assert was used for overflow checks (used all gas)
// Post-0.8.0: arithmetic auto-checks use revert, not assert
//
// Modern guidance:
// - Use require/revert for input validation & expected failures
// - Use assert ONLY for invariants that indicate a code bug
// (something that should be impossible if the code is correct)
//
// Example: a state machine that should never reach an invalid state
enum State { Created, Paid, Shipped }
State public state;
function ship() public {
require(state == State.Paid, "not paid");
state = State.Shipped;
assert(state == State.Shipped); // invariant
}
}Eigene Fehler
Eigene Fehler (0.8.4+) sind der empfohlene Weg zu reverten. Sie kodieren als 4-Byte-Selektor plus ABI-kodierte Argumente — viel billiger als String-Meldungen (die als volles UTF-8 im Bytecode liegen). Clients dekodieren den Selektor, um zu wissen, welcher Fehler auftrat, und lesen die strukturierten Argumente. Fehler auf Datei- oder Contract-Ebene definieren, dann 'revert ErrorName(args);'.
contract CustomError {
// Define errors (outside functions, can be at file level)
error InsufficientBalance(uint256 available, uint256 required);
error Unauthorized(address caller);
error TransferFailed(address from, address to);
mapping(address => uint256) public balances;
function withdraw(uint256 amount) public {
if (balances[msg.sender] < amount) {
// Cheaper than require(..., "insufficient balance")
revert InsufficientBalance(balances[msg.sender], amount);
}
balances[msg.sender] -= amount;
(bool ok, ) = msg.sender.call{value: amount}("");
if (!ok) revert TransferFailed(address(this), msg.sender);
}
function adminOnly() public {
if (msg.sender != address(0x123)) {
revert Unauthorized(msg.sender);
}
}
// Why cheaper? The error selector (4 bytes) replaces a long string,
// saving bytecode size and gas per call.
// ABI decodes arguments so clients get structured data.
}Try / Catch
try/catch behandelt Fehler nur von externen Aufrufen — er kann Reverts interner Funktionsaufrufe nicht fangen. Die 'returns'-Klausel fängt den Erfolgswert. catch Error() fängt revert/require mit String-Meldungen; catch Panic() fängt assert-/Overflow-Panics; catch (bytes) ist ein Fallback für eigene Fehler und unbekannte Reverts. Nutzen, um Fehlschläge externer Contracts sanft zu behandeln.
contract TryCatch {
interface IToken {
function transfer(address to, uint256 amount) external returns (bool);
}
IToken public token;
constructor(address _token) { token = IToken(_token); }
function safeTransfer(address to, uint256 amount)
public returns (bool success, bool tokenOk)
{
try token.transfer(to, amount) returns (bool ok) {
// Called if no revert; 'ok' captures the return value
return (ok, true);
} catch Error(string memory reason) {
// revert("reason") or require(_, "reason")
// log reason
return (false, false);
} catch Panic(uint256 code) {
// assert failures (code 0x01) or overflow (0x11)
return (false, false);
} catch (bytes memory lowLevelData) {
// Any other revert (including custom errors)
return (false, false);
}
}
// try/catch ONLY works with EXTERNAL calls (or this.f()).
// It does NOT catch errors in internal calls.
// The called function MUST return something (not void).
}Fehlermeldungen & Muster
Moderne Fehlerbehandlung nutzt eigene Fehler für strukturierte, billige Reverts. Ältere String-Meldungen sind in Vor-0.8.4-Code weiterhin üblich. Immer handlungsrelevanten Kontext einschließen: welcher Wert falsch war, was erwartet wurde. Dynamische Adressen/Zahlen nicht in String-Meldungen legen — sie blähen den Bytecode auf und sind nicht parsebar. Bei Strings präfixierte Meldungen nutzen ('INVALID:'), um die Log-Indexierung zu unterstützen.
contract Errors {
// 1. Custom errors (best for new code)
error InvalidAmount(uint256 given);
error NotOwner(address caller, address owner);
// 2. String errors (older style)
function old(uint256 x) public pure {
require(x > 0, "INVALID: must be > 0"); // prefix helps indexing
require(x < 100, "INVALID: must be < 100");
}
// 3. Custom error with structured data
function newStyle(uint256 x) public pure {
if (x == 0) revert InvalidAmount(x);
}
// 4. Error with multiple fields
address public owner;
constructor() { owner = msg.sender; }
function guarded() public view {
if (msg.sender != owner) {
revert NotOwner(msg.sender, owner);
}
}
// 5. Don't put dynamic data in string errors (expensive & unparseable)
// BAD: require(msg.sender == owner, "not owner: caller 0x123...");
// GOOD: revert NotOwner(msg.sender, owner);
}Vererbung
Vererbung mit 'is'
Vererbung nutzt das Schlüsselwort 'is'. Ein Kind-Contract erbt alle State-Variablen, Funktionen und Modifikatoren seines Parents. Parent-Konstruktorargumente werden in der Vererbungsliste übergeben (Animal("dog")) oder im Modifikator-Stil des Konstruktors. Ein Kind kann Funktionen überschreiben, die im Parent als virtual markiert sind. Solidity unterstützt Mehrfachvererbung (Linearisierung via C3).
contract Animal {
string public species;
constructor(string memory _species) {
species = _species;
}
function speak() public virtual returns (string memory) {
return "...";
}
}
contract Dog is Animal {
constructor() Animal("dog") {}
// Override parent function
function speak() public override returns (string memory) {
return "Woof";
}
}
// Multiple inheritance
contract Puppy is Dog {
function speak() public override returns (string memory) {
return "Yip";
}
}Virtual & Override
virtual markiert eine Funktion als überschreibbar; override markiert eine Funktion als Überschreibung des Parents. Funktionen sind standardmäßig non-virtual (sicherer). Beim Überschreiben von mehreren Parents mit gemeinsamer Basis diese listen: override(A, B). Um weitere Überschreibungen zu erlauben, virtual override. State-Variablen können nicht überschrieben werden (nur im Speicher verdeckt).
contract Base {
function f() public pure virtual returns (string memory) {
return "base";
}
function g() public pure virtual returns (string memory) {
return "base-g";
}
}
contract Middle is Base {
// Override a single parent
function f() public pure override returns (string memory) {
return "middle";
}
}
contract Multi is Base {
// Override (also virtual so children can override again)
function g() public pure virtual override returns (string memory) {
return "multi";
}
}
contract Combined is Middle, Multi {
// Override multiple parents (explicit list)
function f() public pure override(Middle, Base) returns (string memory) {
return "combined";
}
function g() public pure override(Multi, Base) returns (string memory) {
return "combined-g";
}
}Super-Schlüsselwort
super.method() ruft die Parent-Version der Methode auf und erlaubt, Verhalten zu erweitern statt zu ersetzen. Bei einfacher Vererbung ist es intuitiv. Bei Mehrfachvererbung folgt super der C3-Linearisierung — es kann einen Geschwister-Contract aufrufen, nicht den lexikalischen Parent. Bei super in Diamond-Vererbung immer die Linearisierungsreihenfolge prüfen (am stärksten abgeleitet zuletzt).
contract A {
function label() public pure virtual returns (string memory) {
return "A";
}
}
contract B is A {
function label() public pure virtual override returns (string memory) {
return string.concat("B>", super.label()); // calls A.label()
}
}
contract C is B {
function label() public pure override returns (string memory) {
return string.concat("C>", super.label()); // calls B.label()
}
}
// super refers to the NEXT contract in the linearization,
// not necessarily the lexical parent. With multiple inheritance,
// super.label() may call a sibling.
contract P1 { function f() public pure virtual returns (uint) { return 1; } }
contract P2 { function f() public pure virtual returns (uint) { return 2; } }
contract Child is P1, P2 {
function f() public pure override(P1, P2) returns (uint) {
return super.f(); // calls P2.f() (last in linearization)
}
}Mehrfachvererbung
Solidity unterstützt Mehrfachvererbung über das Schlüsselwort 'is'. Parents vom am wenigsten- zum am stärksten-abgeleitet listen: 'is Ownable, Pausable'. Der C3-Linearisierungsalgorithmus erzeugt eine deterministische Reihenfolge und löst das Diamond-Problem. Beim Überschreiben einer von mehreren Parents geerbten Funktion 'override(A, B)' nutzen. Konstruktoren laufen in Linearisierungsreihenfolge (Parents zuerst).
contract Ownable {
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() { require(msg.sender == owner); _; }
}
contract Pausable {
bool public paused;
modifier whenNotPaused() { require(!paused); _; }
}
// Multiple inheritance: list parents from most base to most derived
contract Token is Ownable, Pausable {
mapping(address => uint256) public balances;
function mint(address to, uint256 amount)
public
onlyOwner // from Ownable
whenNotPaused // from Pausable
{
balances[to] += amount;
}
}
// C3 Linearization order (for 'Token'):
// Token -> Pausable -> Ownable -> (object)
// Determined by the order in 'is' list (left to right, base first)
//
// Diamond problem is resolved by C3 — there is a single
// deterministic order, no ambiguity. But you must understand it
// when using super.Konstruktorvererbung
Parent-Konstruktorargumente lassen sich in der Vererbungsliste übergeben (A(42)) für fixe Werte oder im Kindkonstruktor über Modifikator-Syntax (A(_a)) für Laufzeitwerte. Bei mehreren Parents in Linearisierungsreihenfolge übergeben (am wenigsten-abgeleitet zuerst). Hat ein Parent einen argumentlosen Konstruktor, kann er weggelassen werden. Konstruktoren laufen einmal beim Deployment, in Linearisierungsreihenfolge.
contract A {
uint256 public a;
constructor(uint256 _a) { a = _a; }
}
// Style 1: pass args in inheritance list
contract B1 is A(42) {
// 'a' is set to 42 at deployment
}
// Style 2: pass via modifier-style in child constructor
contract B2 is A {
constructor(uint256 _b) A(_b * 2) {
// 'a' is set to _b * 2
}
}
// Style 3: child has its own constructor + parent args
contract B3 is A {
uint256 public b;
constructor(uint256 _a, uint256 _b) A(_a) {
b = _b;
}
}
// With multiple parents, order = linearization order
contract C1 { constructor(uint) {} }
contract C2 { constructor(uint) {} }
contract C3 is C1, C2 {
constructor(uint x) C1(x) C2(x+1) {}
}Abstract Contracts & Interfaces
Abstract Contracts
Ein abstract contract hat mindestens eine Funktion ohne Rumpf (mit virtual deklariert, ohne Implementierung). Er lässt sich nicht direkt deployen — ein Kind muss alle abstrakten Funktionen implementieren. Abstract Contracts nutzen, wenn geteilter Zustand + Modifikatoren + teilweise Implementierung gewünscht sind. Das Schlüsselwort 'abstract' ist vor 0.6.0 Pflicht, wenn irgendeine Funktion ohne Rumpf ist.
abstract contract Ownable {
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
// abstract function — no body, must be implemented by children
function sensitiveAction() public virtual;
// Can have implemented functions too
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract Vault is Ownable {
function sensitiveAction() public override onlyOwner {
// implementation here
}
}Interfaces
Interfaces sind wie pure abstract contracts: kein Zustand, keine Konstruktoren, keine implementierten Funktionen, alle Funktionen external. Sie definieren die ABI eines Contracts zur Interaktion mit unbekannten Implementierungen. Interfaces nutzen, um andere Contracts aufzurufen, ohne deren Logik zu erben. Mit 'I'-Präfix benennen (IERC20, IUniswapV2Pair). Funktionen in Interfaces dürfen außer external view/payable keine Modifikatoren haben.
interface IERC20 {
// Functions only — no implementation, no state, no constructor
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external view returns (uint256);
function transferFrom(address from, address to, uint256 amount)
external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract MyToken is IERC20 {
// Must implement ALL functions declared in the interface
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
// ... implement the rest
}Virtual vs. Abstract
abstract = mindestens eine Funktion ohne Rumpf; der Contract lässt sich nicht deployen. virtual = eine Funktion mit Rumpf, die Kinder ÜBERSCHREIBEN können. Eine Funktion kann beides sein (virtual + ohne Rumpf). Interfaces sind implizit vollkommen abstrakt — jede Funktion ist virtual, hat keinen Rumpf und ist external. Abstract für geteilte Logik, Interfaces für reine ABI-Definitionen.
// ABSTRACT contract: has at least one unimplemented function
// Must declare 'abstract'; cannot be deployed directly
abstract contract Counter {
uint256 public count;
function increment() public virtual; // no body -> abstract
function reset() public {
count = 0;
}
}
// VIRTUAL: function HAS a body, but CAN be overridden
contract Base {
function f() public pure virtual returns (uint) {
return 1;
}
}
contract Child is Base {
function f() public pure override returns (uint) {
return 2;
}
}
// A function can be both virtual and abstract (no body)
abstract contract A {
function f() public pure virtual; // virtual + no body
}
// Interfaces are implicitly abstract — all functions virtual+abstract
interface I {
function f() external; // implicit virtual, no body
}Interface-Best-Practices
Interface-Best-Practices: 'I'-Präfix, minimal halten (nur was Aufrufer brauchen), alle Funktionen external, kein Zustand/Konstruktoren/Implementierung, Events erlaubt. Interfaces nutzen, um: (1) andere Contracts aufzurufen, deren Quellcode man nicht hat, (2) Standards zu definieren (IERC20, IERC721), (3) Bytecode zu verkleinern, indem man keine Implementierung erbt. Ein Interface zu implementieren zwingt deinen Contract, den Standard zu erfüllen.
// 1. Name with 'I' prefix
interface IERC721 {
function ownerOf(uint256 tokenId) external view returns (address);
function transferFrom(address from, address to, uint256 tokenId) external;
}
// 2. Keep minimal — only what callers need
interface IPriceFeed {
function latestAnswer() external view returns (int256);
function decimals() external view returns (uint8);
}
// 3. All functions external (required)
// 4. No state variables, no constructors, no implemented functions
// 5. Events ARE allowed in interfaces
interface IEvents {
event SomethingHappened(uint256 indexed id);
}
// 6. Use to call contracts you don't have source for
contract Consumer {
IPriceFeed public feed;
constructor(address _feed) { feed = IPriceFeed(_feed); }
function price() public view returns (int256) {
return feed.latestAnswer();
}
}
// 7. Implement to satisfy a standard (ERC20, ERC721)
contract MyToken is IERC20 { /* ... */ }IERC20-Beispiel (Interface)
IERC20 definiert den ERC-20-Fungible-Token-Standard. Das Interface deklariert die 6 Pflichtfunktionen (totalSupply, balanceOf, transfer, approve, allowance, transferFrom) plus optionale Metadaten (name, symbol, decimals) und 2 Events. Jeder Contract, der dieses Interface implementiert, kann als ERC-20-Token behandelt werden. Das Interface nutzen, um mit jedem ERC-20 zu interagieren, ohne seine interne Implementierung zu kennen.
// Canonical ERC-20 interface
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount)
external returns (bool);
}
// Minimal interaction using the interface
contract Wallet {
IERC20 public token;
constructor(address _token) { token = IERC20(_token); }
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function send(address to, uint256 amount) public returns (bool) {
return token.transfer(to, amount);
}
}Bibliotheken
Bibliotheks-Grundlagen
Bibliotheken sind wie Contracts, können aber keinen Zustand haben, nicht erben und nicht geerbt werden. Sie werden einmal deployt und via DELEGATECALL (extern) oder inlined (intern) wiederverwendet. interne Bibliotheksfunktionen werden in den aufrufenden Contract inlined — kein separates Deployment. Bibliotheken nutzen, um wiederverwendbare Funktionen zu gruppieren (Mathe, Validierung, Formatierung). Die Direktive 'using SafeMath for uint256' erlaubt Methodenaufrufe als a.b().
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "underflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "overflow");
return c;
}
// Libraries CANNOT have state variables
// Libraries CANNOT inherit or be inherited
// All functions must be internal or external
// No constructor, no fallback, no receive
}
contract UsingSafeMath {
using SafeMath for uint256;
function calc(uint256 a, uint256 b) public pure returns (uint256) {
return a.add(b).mul(2); // a.add(b) calls SafeMath.add(a, b)
}
}Using For
'using Library for Type' hängt die Funktionen der Bibliothek an diesen Typ an, sodass du value.method() statt Library.method(value) aufrufen kannst. Der erste Parameter der Bibliotheksfunktion muss dem Typ entsprechen. Die Direktive geht auch auf Dateiebene (0.8.13+) mit 'using {fn1, fn2} for Type;'. Reiner syntaktischer Zucker — der Compiler schreibt ihn zu direkten Aufrufen um.
library Strings {
function toString(uint256 value) internal pure returns (string memory) {
// convert uint to decimal string
if (value == 0) return "0";
uint256 temp = value;
uint256 digits;
while (temp != 0) { digits++; temp /= 10; }
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + value % 10));
value /= 10;
}
return string(buffer);
}
}
contract UsingExample {
// Attach library functions to a type
using Strings for uint256;
function describe(uint256 x) public pure returns (string memory) {
// x.toString() calls Strings.toString(x)
return string.concat("Value: ", x.toString());
}
// Attach to a specific type globally (Solidity 0.8.13+)
// using {toString} for uint256; // file-level
// using SafeMath for uint256;
// using SafeMath for *; // not allowed
}Interne Bibliotheken
Interne Bibliotheksfunktionen werden zur Compile-Zeit in den Bytecode des aufrufenden Contracts inlined — kein Laufzeit-DELEGATECALL, kein Bibliotheks-Deployment, kein Aufruf-Overhead. Aufrufe sind damit praktisch kostenlos (nur Gas für die Operationen selbst). Interne Bibliotheken für pure/view-Helfer (Mathe, String-Konvertierung). Die Bytecodegröße des Aufrufers wächst, aber das Aufrufgas ist niedriger als bei externen Bibliotheken.
library Math {
// internal functions are INLINED into the caller's bytecode
// No separate deployment needed — saves gas on each call
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b)
internal pure returns (uint256)
{
// (a + b) / 2 can overflow; this avoids it
return (a & b) + ((a ^ b) / 2);
}
}
contract Calc {
using Math for uint256;
function doMath(uint256 x, uint256 y)
public pure returns (uint256, uint256, uint256)
{
return (x.max(y), x.min(y), x.average(y));
}
}
// Internal libraries are like helper functions that don't add
// runtime call overhead. Good for: math, validation, conversions.Externe (deployte) Bibliotheken
Externe Bibliotheksfunktionen werden als separater Contract deployt und via DELEGATECALL aufgerufen — sie laufen im Kontext des Aufrufers (storage, msg.sender). Nützlich für geteilten Utility-Code, den viele Contracts nutzen (spart Gesamt-Deploy-Gas). Trade-offs: DELEGATECALL-Overhead pro Aufruf (~1400 Gas) und die Bibliothek muss deployt und ihre Adresse zur Compile-Zeit verlinkt werden. Die meisten Bibliotheken nutzen interne Funktionen; extern ist selten.
library BigMath {
// external functions => library is DEPLOYED as a separate contract
// Calls use DELEGATECALL — runs in caller's context (storage/msg)
function complexOperation(uint256[] storage arr)
external view returns (uint256 sum)
{
for (uint256 i = 0; i < arr.length; i++) {
sum += arr[i];
}
}
}
contract UsesExternal {
uint256[] public data;
using BigMath for uint256[];
function total() public view returns (uint256) {
return data.complexOperation(); // DELEGATECALL to BigMath
}
}
// External library trade-offs:
// + Shared bytecode: many contracts use one deployed library (saves deployment gas)
// + Caller bytecode stays small
// - DELEGATECALL overhead per call (~1400 gas)
// - Library must be deployed first and its address linked at compile time
//
// Most libraries are internal; external is rare (e.g., Create2BeaconProxy).SafeMath-Beispiel (vor 0.8.0)
SafeMath war die kanonische Overflow-Check-Bibliothek vor 0.8.0. Seit 0.8.0 revert-t Arithmetik bei Overflow automatisch, SafeMath ist für einfache Mathematik also unnötig. Weiterhin nützlich für: (1) Legacy-Code zu lesen, (2) unchecked-Operationen explizit zu umhüllen, (3) das Muster 'require Nachbedingung' als Lehrbeispiel. Die OpenZeppelin-Version bleibt weit referenziert.
// Before 0.8.0, arithmetic did NOT auto-check overflow.
// SafeMath was essential. Now it's mostly historical,
// but the pattern is instructive and still useful for
// explicit intent.
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage)
internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage)
internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
}Ether-Transfers
Payable & msg.value
payable-Funktionen akzeptieren Ether via msg.value (in wei). Der Ether wird automatisch dem Kontostand des Contracts zugeschlagen — manuelles Tracking ist nicht nötig, außer du willst Nutzer-abhängige Abrechnung. msg.value für exakte oder Mindestzahlungen validieren. Überzähligen Ether immer zurückerstatten, um ihn nicht im Contract einzusperren. 1 ether = 10^18 wei.
contract PayableContract {
address payable public owner;
constructor() {
owner = payable(msg.sender);
}
// payable = function accepts Ether
function deposit() public payable {
// msg.value = wei sent with this call
// Ether auto-added to address(this).balance
// No need to update a balance variable here
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
// Specify required payment
function buyItem() public payable {
require(msg.value == 1 ether, "must pay 1 ether");
// process purchase
}
// Send excess back
function refundExcess(uint256 price) public payable {
uint256 excess = msg.value - price;
if (excess > 0) {
(bool ok, ) = msg.sender.call{value: excess}("");
require(ok, "refund failed");
}
}
}Transfer
address.transfer(amount) sendet Ether und revert-t bei Fehlschlag. Er reicht einen fixen 2300-Gas-Stipend weiter, was historisch Reentrancy verhinderte, heute aber als zerbrechlich gilt (Gas-Kosten änderten sich in Istanbul 2019). Moderne Empfehlung: transfer nur beim Senden an eine vertrauenswürdige Adresse (etwa owner). Für beliebige Empfänger .call{value:} mit expliziten Reentrancy-Guards nutzen, da der 2300-Stipend für legitime receive/fallback-Logik unzureichend sein kann.
contract TransferExample {
address payable public recipient = payable(0xAbC...);
function sendViaTransfer() public payable {
// transfer: throws on failure, forwards 2300 gas stipend
// Simple and safe against reentrancy (limited gas)
recipient.transfer(1 ether);
}
function sendFromContract() public {
// address(this).balance = current contract balance
recipient.transfer(address(this).balance);
}
// Characteristics:
// - Reverts if recipient's receive/fallback uses > 2300 gas
// - 2300 gas stipend: enough for an event log, not a storage write
// - Safer than send (which returns false on failure)
// - But BEWARE: post-Istanbul (2019), some operations cost more,
// breaking contracts that relied on 2300 gas. Prefer .call{}.
}
// transfer is DEPRECATED for pushing to arbitrary addresses.
// Use .call{value:} and handle the return value.Send
address.send(amount) liefert einen Boolean zurück (true bei Erfolg, false bei Fehlschlag) — er revert-t NICHT automatisch. Den Rückgabewert MUSST du prüfen und bei Fehlschlag revert-en. Wie transfer reicht er nur 2300 Gas weiter. send ist fehleranfällig (Entwickler vergessen den Rückgabewert-Check) und in modernem Code selten. .call{value:} für neue Contracts bevorzugen.
contract SendExample {
address payable public recipient = payable(0xAbC...);
function sendViaSend() public payable returns (bool) {
// send: returns false on failure (does NOT revert)
// Also forwards 2300 gas stipend like transfer
bool success = recipient.send(1 ether);
require(success, "send failed"); // you MUST check the return value
return success;
}
// Common bug: forgetting to check the return value
function buggy() public payable {
recipient.send(1 ether); // BUG: silently fails
// state already updated => funds lost
}
// Correct: check + revert
function correct() public payable {
bool ok = recipient.send(1 ether);
require(ok, "send failed");
}
}
// send is rarely used in modern code.
// Prefer .call{value:} which gives more control + return data.Call (empfohlen)
.call{value: x}(...) ist der empfohlene Weg, Ether zu senden, seit 0.8.0. Er reicht alles verfügbare Gas weiter (unter Vorbehalt der 63/64-Regel), Empfänger können also komplexe Logik ausführen. Er liefert (bool, bytes) — der Boolean MUSS geprüft und bei Fehlschlag revert-et werden. Weil er alles Gas weiterreicht, ist er anfällig für Reentrancy — immer mit einem nonReentrant-Modifikator paaren oder checks-effects-interactions folgen. call für beliebige Empfänger; transfer nur für vertrauenswürdige Adressen.
contract CallExample {
address payable public recipient = payable(0xAbC...);
function sendViaCall() public payable returns (bool) {
// .call returns (bool success, bytes memory data)
// Forwards ALL gas (63/64 rule), so recipient can do more
(bool success, ) = recipient.call{value: 1 ether}("");
require(success, "call failed");
return success;
}
// With calldata (call a function while sending Ether)
function callWithFunction(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = token.call{value: 0}(
abi.encodeWithSignature("transfer(address,uint256)", to, amount)
);
return (ok, data);
}
// Forward gas explicitly
function withGas() public returns (bool) {
(bool ok, ) = recipient.call{gas: 100000, value: 0}("");
return ok;
}
// IMPORTANT: call forwards all gas, so a malicious recipient
// can re-enter your contract. Always use a reentrancy guard.
}Kontostand prüfen
address.balance liefert den wei-Kontostand einer beliebigen Adresse (inklusive address(this) für den Contract selbst). Es ist ein view und off-chain kostenlos. WARNUNG: Der Kontostand kann von jedermann via selfdestruct aufgebläht werden (erzwungener Ether), verlass dich also nie auf exakte Kontostands-Gleichheit in der Logik — >= nutzen oder eigene Abrechnungsvariablen pflegen. Immer querschreiben, dass die Einzahlungssumme dem Contract-Kontostand entspricht, als Invariante.
contract BalanceCheck {
mapping(address => uint256) public deposits;
function deposit() public payable {
deposits[msg.sender] += msg.value;
}
function contractBalance() public view returns (uint256) {
// Balance of THIS contract
return address(this).balance;
}
function userBalance(address user) public view returns (uint256) {
// Balance of any address (in wei)
return user.balance;
}
function myBalance() public view returns (uint256) {
return msg.sender.balance;
}
// Verify accounting invariant
function verify() public view returns (bool) {
// Sum of deposits should equal contract balance
// (in a real contract, this would be expensive to compute)
return address(this).balance >= deposits[msg.sender];
}
// CAUTION: address.balance can be manipulated by an attacker
// who forces Ether via selfdestruct. Never use balance == X
// as a strict equality check for logic — use >= or tracking vars.
function dangerous() public view returns (bool) {
// BAD: an attacker can selfdestruct-ETH into the contract
// and break this exact check
return address(this).balance == 1 ether;
}
}Gas-Optimierung
Storage vs. Memory
Storage-Lesevorgänge (SLOAD) kosten ~2100 Gas kalt / 100 warm pro Zugriff. Memory-Lesevorgänge (MLOAD) kosten nur 3 Gas. Liest eine Funktion eine State-Variable mehrfach (besonders in einer Schleife), zuerst in einer Memory-Variablen cachen. Das erste SLOAD ist teuer; nachfolgende Memory-Lesevorgänge sind fast kostenlos. Eine der einfachsten und wirkungsvollsten Optimierungen.
contract StorageVsMemory {
uint256 public stateVar; // storage slot 0
function expensive(uint256 x) public view returns (uint256) {
// Each access to stateVar = SLOAD (~2100 gas cold, 100 warm)
uint256 sum = 0;
for (uint256 i = 0; i < x; i++) {
sum += stateVar; // SLOAD every iteration
}
return sum;
}
function cheap(uint256 x) public view returns (uint256) {
// Cache to memory once: MLOAD costs 3 gas
uint256 cached = stateVar; // 1 SLOAD
uint256 sum = 0;
for (uint256 i = 0; i < x; i++) {
sum += cached; // MLOAD (cheap)
}
return sum;
}
// Rules of thumb:
// - storage: persistent, ~2100 gas per cold SLOAD, ~5000-20000 per SSTORE
// - memory: temporary, ~3 gas per access, free to create
// - calldata: read-only, free (passed in)
// Always cache state variables used multiple times in a function.
}Variable Packing
Solidity packt aufeinanderfolgende State-Variablen in 32-Byte-Storage-Slots. Für Gasersparnis kleine Typen (uint8, uint64, address) gruppieren, damit sie sich einen Slot teilen. Struct-Felder so ordnen, dass kleine dicht packen. Jeder gesparte Slot = ~20k Gas beim ersten Zugriff. Beachte: Mapping- und dynamische-Array-Einträge starten immer einen neuen Slot und lassen sich nicht packen.
contract Packing {
// BAD: each takes a full 32-byte slot
// 3 slots = 60k gas for cold SLOADs
struct Bad {
uint64 time;
address from; // 20 bytes
uint64 amount;
}
// GOOD: pack small types together into 32 bytes
// 1 slot = 20k gas (one SLOAD)
struct Good {
uint64 time;
uint64 amount;
address from; // 20 bytes => total 8+8+20 = 36... still 2 slots
}
// Pack carefully: declare small types together
struct Packed {
uint32 a; // 4
uint32 b; // 4
uint32 c; // 4
uint32 d; // 4 => 16 bytes => can fit address (20)? No, 16+20=36 > 32
address e; // => 2 slots
}
struct Tight {
uint128 a; // 16
uint128 b; // 16 => 1 slot (32 bytes)
}
// Order matters: variables are packed in declaration order.
// A variable that doesn't fit starts a new slot.
// Mapping/dynamic-array always start a new slot.Unchecked-Blöcke
unchecked { ... } deaktiviert Overflow-/Underflow-Checks innerhalb des Blocks und spart Gas (~50-80 pro Op). Sicher, wenn die Grenzen bereits validiert sind (nach require(a >= b) kann a - b nicht underflown). Der klassische sichere Anwendungsfall sind Schleifenzähler (i++ in einer for-Schleife überläuft nie 2^256). unchecked nicht blind nutzen — stiller Overflow ist ein Sicherheitsrisiko.
contract UncheckedBlock {
function loopWith(uint256 n) public pure returns (uint256 sum) {
// 0.8+ checks overflow on every operation (extra gas)
for (uint256 i = 0; i < n; i++) {
sum += i;
}
}
function loopUnchecked(uint256 n) public pure returns (uint256 sum) {
unchecked {
for (uint256 i = 0; i < n; i++) {
sum += i; // skips overflow check (cheaper)
}
}
}
// Safe to use when overflow is impossible:
// - Loop counters that won't reach 2^256
// - Differences of values you've already bounds-checked
function safeSub(uint256 a, uint256 b) public pure returns (uint256) {
require(a >= b, "underflow"); // checked here
unchecked { return a - b; } // safe: can't underflow now
}
// NEVER use unchecked when overflow/underflow is possible
// unless you intentionally want wraparound (rare).
}Eigene Fehler vs. Require
Eigene Fehler (0.8.4+) sind billiger als require(_, "msg"), weil der Meldungsstring im Bytecode liegt (kostet Gas pro Byte) und bei jedem Revert neu kodiert wird. Ein eigener Fehler ist nur ein 4-Byte-Selektor plus ABI-kodierte Argumente. Bei nicht-trivialen Fehlermeldungen sparen eigene Fehler Tausende Gas pro Aufruf UND verkleinern den Deployment-Bytecode. In neuem Code immer eigene Fehler bevorzugen.
contract Errors {
// BAD: string messages bloat bytecode + cost gas per call
function oldStyle(uint256 x) public pure {
require(x > 0, "value must be greater than zero");
require(x < 100, "value must be less than one hundred");
}
// GOOD: custom errors are cheap and structured
error InvalidValue(uint256 given, uint256 min, uint256 max);
function newStyle(uint256 x) public pure {
if (x == 0 || x >= 100) {
revert InvalidValue(x, 1, 99);
}
}
// Gas comparison (approximate):
// require(_, "msg") ~ 400 + 50 per byte of message
// revert CustomError() ~ 400 + small selector cost
//
// For long messages, custom errors save thousands of gas
// and reduce deployed bytecode size.
// Define errors at file level to reuse across contracts
error Unauthorized(address caller);
function guarded() public {
if (msg.sender != address(0)) revert Unauthorized(msg.sender);
}
}State-Variablen in Schleifen cachen
Die Array-Länge vor der Schleife in einer lokalen Variablen cachen (spart ein SLOAD pro Iteration). Bei kleinem Array einmal ins memory kopieren (ein SLOAD pro Element, dann billige MLOADs in der Schleife). Akkumulatoren sollten immer lokale (memory-)Variablen sein. Bei Storage-Struct-Feldern das ganze Struct ins memory cachen, wenn mehrfach genutzt.
contract Cache {
uint256[] public data;
mapping(address => uint256) public balances;
address[] public users;
// BAD: reads mapping in every iteration (SLOAD each time)
function sumBad() public view returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < users.length; i++) {
total += balances[users[i]]; // SLOAD each iteration
}
return total;
}
// GOOD: cache length, use local var for accumulator
function sumBetter() public view returns (uint256) {
uint256 total = 0;
uint256 len = users.length; // cache length
for (uint256 i = 0; i < len; i++) {
address u = users[i]; // SLOAD once
total += balances[u]; // still SLOAD, but unavoidable
}
return total;
}
// BEST: cache array to memory (if small enough)
function sumMemory() public view returns (uint256) {
address[] memory memUsers = users; // copy to memory once
uint256 total = 0;
uint256 len = memUsers.length;
for (uint256 i = 0; i < len; i++) {
total += balances[memUsers[i]]; // MLOAD each iteration
}
return total;
}
}Short-circuit & Schleifen-Optimierung
Short-circuit-Auswertung: billige Checks zuerst bei && und ||. ++i (Präfix) statt i++ nutzen (etwas billiger — kein Temporärwert). Schleifenzähler in unchecked wickeln (i kann realistisch nie 2^256 überlaufen). Schleifen früh verlassen, wenn das Gesuchte gefunden ist. Teure Operationen (externe Aufrufe, Storage-Schreibvorgänge) innerhalb von Schleifen vermeiden — außerhalb bündeln.
contract ShortCircuit {
// && and || short-circuit: right side only evaluated if needed
function cheap(address a, address b) public view returns (bool) {
// Put the cheap check first
return (a == b || expensiveCheck(a));
}
function expensiveCheck(address) internal view returns (bool) {
// imagine a heavy computation
return true;
}
// Loop optimization: prefer prefix increment
function good() public pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 10; ++i) { // ++i slightly cheaper than i++
sum += i;
}
return sum;
}
// Use unchecked for loop counters (always safe)
function best() public pure returns (uint256) {
uint256 sum = 0;
uint256 i = 0;
unchecked {
while (i < 10) {
sum += i;
++i;
}
}
return sum;
}
// Avoid unnecessary work: precompute, batch, early-exit
function find(uint256[] memory arr, uint256 target)
public pure returns (int256)
{
for (uint256 i = 0; i < arr.length; ++i) {
if (arr[i] == target) return int256(i); // early exit
}
return -1;
}
}Zeiteinheiten & Block-Eigenschaften
block.timestamp
block.timestamp (Alias 'now' vor 0.7.0) ist der Unix-Zeitstempel des aktuellen Blocks in Sekunden. Er wird vom Miner/Validator gesetzt und lässt sich um ~15 Sekunden manipulieren — NIE für Zufälligkeit oder präzises Timing nutzen. Für grobe Dauer (>=1 Minute) und Ordnung ist er in Ordnung. Übliche Einsätze: Time-Locks, Vesting-Pläne, Deadlines. block.number für strengere Garantien.
contract Time {
uint256 public startTime;
uint256 public constant DURATION = 1 days;
constructor() {
startTime = block.timestamp; // uint256 in 0.8+
}
function isExpired() public view returns (bool) {
return block.timestamp >= startTime + DURATION;
}
function elapsed() public view returns (uint256) {
return block.timestamp - startTime;
}
// WARNING: block.timestamp is set by the miner/validator.
// They can manipulate it by ~15 seconds. NEVER use it for:
// - Randomness (keccak256(block.timestamp) is exploitable)
// - Precise timing (use block.number as a fallback)
// It's fine for:
// - Coarse durations (>= 1 minute)
// - Deadlines that tolerate 15s drift
// - Order of events (timestamp comparison)
// Time locks: require(block.timestamp > unlockTime)
function lock() public payable returns (uint256) {
return block.timestamp + 1 weeks;
}
}block.number & blockhash
block.number ist die aktuelle Blockhöhe. blockhash(n) liefert den Hash von Block n, aber NUR für die letzten 256 Blöcke (ältere liefern 0) und nicht für den aktuellen Block (liefert 0). Sowohl block.number als auch blockhash sind von Minern beeinflussbar — nicht für hochriskante Zufälligkeit nutzen. Für echte Zufälligkeit Chainlink VRF oder ein Commit-Reveal-Schema mit nutzergelieferter Entropie.
contract BlockInfo {
function currentBlock() public view returns (uint256) {
return block.number;
}
function prevHash(uint256 n) public view returns (bytes32) {
// Only the last 256 blocks' hashes are available
require(n > 0 && n <= 256, "out of range");
return blockhash(block.number - n);
}
// blockhash returns 0 for current block, future blocks, or >256 old
function currentHash() public view returns (bytes32) {
return blockhash(block.number); // returns 0!
}
// Use case: weak randomness (still exploitable by miners)
function pseudoRandom() public view returns (uint256) {
// A miner CAN see this and choose to withhold blocks
// to manipulate the result. Don't use for high value.
return uint256(keccak256(abi.encodePacked(
blockhash(block.number - 1),
block.timestamp,
msg.sender
)));
}
// For real randomness, use Chainlink VRF or a commit-reveal scheme.
}Zeiteinheiten (seconds/minutes/hours/days/weeks)
Zeiteinheits-Suffixe (seconds, minutes, hours, days, weeks) konvertieren zu Sekunden als uint256. 'years' wurde in 0.5.0 wegen Schaltjahr-Mehrdeutigkeit entfernt. Ether-Einheiten (wei, gwei, ether) sind separat: 1 ether = 10^18 wei, 1 gwei = 10^9 wei. Beträge immer in wei speichern und die Suffixe für Lesbarkeit in Berechnungen nutzen.
contract TimeUnits {
// Suffixes convert to seconds (uint256):
uint256 public oneSecond = 1 seconds; // 1
uint256 public oneMinute = 1 minutes; // 60
uint256 public oneHour = 1 hours; // 3600
uint256 public oneDay = 1 days; // 86400
uint256 public oneWeek = 1 weeks; // 604800
// 'years' was removed in 0.5.0 (leap years made it ambiguous)
function deadline() public view returns (uint256) {
return block.timestamp + 7 days;
}
function hourly() public pure returns (uint256) {
return 24 hours; // 86400
}
// Ether units (different from time units!):
uint256 public oneWei = 1 wei; // 1
uint256 public oneGwei = 1 gwei; // 10^9
uint256 public oneEther = 1 ether; // 10^18
function fromEther(uint256 e) public pure returns (uint256) {
return e * 1 ether; // convert to wei
}
function toEther(uint256 weiAmount) public pure returns (uint256) {
return weiAmount / 1 ether;
}
}Gas & gasleft()
gasleft() liefert das verbleibende Gas zum Aufrufzeitpunkt (ersetzt das veraltete msg.gas). Nützlich, um zu messen, wie viel Gas ein Codeabschnitt verbraucht. Die 63/64-Regel: Externe Aufrufe reichen 63/64 des verbleibenden Gases weiter und behalten 1/64 reserviert, damit der Aufrufer die Rückgabe handhaben kann. Exakte Gaswerte nicht über Hard Forks hinweg verlassen — Opcode-Kosten ändern sich.
contract GasTrack {
function checkGas() public returns (uint256, uint256) {
uint256 start = gasleft(); // gas remaining at this point
// ...do some work...
uint256 sum = 0;
for (uint256 i = 0; i < 100; i++) {
sum += i;
}
uint256 end = gasleft();
return (start, start - end); // (initial, used)
}
// 63/64th rule: when an external call is made, only 63/64 of
// remaining gas is forwarded; 1/64 is reserved so the caller
// can finish processing (e.g., revert handling).
function forwardGas(address target) public returns (bool, uint256) {
uint256 before = gasleft();
(bool ok, ) = target.call{gas: 100000}("");
uint256 after = gasleft();
return (ok, before - after);
}
// gasleft() replaces the deprecated msg.gas.
// It's a view, so it can be used in modifiers to enforce budgets.
modifier usesLessThan(uint256 maxGas) {
uint256 start = gasleft();
_;
require(start - gasleft() <= maxGas, "too much gas");
}
}Chain ID & Netzwerkerkennung
block.chainid liefert die aktuelle Chain-ID. Essenziell für Replay-Schutz (EIP-155) und EIP-712-typisierte Datensignaturen (der Domain-Separator schließt chainId ein). chainId als immutable im Konstruktor cachen für Gaseffizienz — bei EIP-712 kann aber eine Neuberechnung nötig sein, wenn der Contract auf eine neue Kette geforkt wird. chainId in jeden Hash einschließen, der Autorisierung signiert.
contract Chain {
function getChainId() public view returns (uint256) {
return block.chainid; // current chain ID
}
// Common chain IDs:
// 1 = Ethereum mainnet
// 5 = Goerli testnet (deprecated)
// 11155111 = Sepolia testnet
// 137 = Polygon
// 42161 = Arbitrum One
// 10 = Optimism
// 56 = BNB Smart Chain
modifier onlyMainnet() {
require(block.chainid == 1, "only mainnet");
_;
}
// Prevent cross-chain replay attacks by including chainId in hashes
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(
keccak256("EIP712Domain(...)"),
block.chainid,
address(this)
));
}
// For multi-chain deployments, store chainId at construction
uint256 public immutable chainId;
constructor() {
chainId = block.chainid;
}
// NOTE: chainId can change during a fork (rare). For EIP-712
// signatures, cache it but allow re-initialization on mismatch.
}Sichtbarkeitsmodifikatoren
Public
public-Funktionen sind von überall aufrufbar: extern (von Nutzern oder anderen Contracts), intern (aus dem Contract) und von abgeleiteten Contracts. public-State-Variablen bekommen automatisch eine Getter-Funktion. Public ist am permissivsten, ergänzt aber Bytecode (die Funktion muss beide Aufrufkonventionen unterstützen). Wird eine public-Funktion intern via 'this.f()' aufgerufen, wird sie ein teurer externer Aufruf.
contract Public {
uint256 public counter; // public state var => auto getter
// public function: callable from anywhere
// - externally (via transaction or call)
// - internally (from this contract)
// - from derived contracts
function increment() public {
counter += 1;
}
function caller() public {
increment(); // internal call (cheap)
this.increment(); // external call (expensive, creates a msg)
}
// Public is the most permissive. Auto-getters for state vars
// are 'external' view functions generated by the compiler.
//
// Cost: public functions are part of the ABI and add bytecode.
// Internal calls to public functions skip the external wrapper.
}External
external-Funktionen sind NUR von außerhalb des Contracts aufrufbar — nicht intern. Sie sind etwas billiger als public, weil sie direkt aus calldata lesen (keine Memory-Kopie). external für Funktionen nutzen, die nur Einstiegspunkte sein sollen. Muss eine Funktion intern und extern aufrufbar sein, public machen ODER in einen external-Wrapper + interne Implementierung splitten.
contract External {
// external: ONLY callable from outside the contract
// CANNOT be called internally (this.f() works but is expensive)
function doWork(uint256 x) external pure returns (uint256) {
return x * 2;
}
function caller() public pure returns (uint256) {
// doWork(5); // COMPILER ERROR: external not callable internally
return this.doWork(5); // works but creates an external call (expensive)
}
// external with calldata params is cheapest for inputs
function process(string calldata input)
external
pure
returns (bytes32)
{
return keccak256(bytes(input));
}
// Use external when:
// - The function is only meant to be called by users/other contracts
// - You want to read calldata directly (cheaper than memory)
//
// State variables CANNOT be external.
}Internal
internal-Funktionen sind aus dem Contract und aus jedem abgeleiteten Contract (Subklassen) aufrufbar. Sie ist der Default für State-Variablen. internal ist billiger als public, weil sie den external-call-Wrapper nicht braucht. internal für Helferfunktionen und Kernlogik, die Subklassen aufrufen oder überschreiben können sollen. Konvention: interne Funktionen mit Unterstrich präfixieren (_helper).
contract Internal {
uint256 internal secret; // internal state var (default)
// internal: callable from this contract AND derived contracts
function _helper(uint256 x) internal pure returns (uint256) {
return x + 1;
}
function caller() public pure returns (uint256) {
return _helper(5); // internal call works
}
// Cannot be called externally:
// contract Other { function f() public { Internal._helper(5); } } // ERROR
}
contract Child is Internal {
function useParent() public pure returns (uint256) {
return _helper(10); // OK: child can call internal
}
function readSecret() public view returns (uint256) {
return secret; // OK: child can read internal
}
}
// internal is the DEFAULT for state variables.
// Use internal when:
// - You want subclasses to use/override it
// - You don't need external access
// It's cheaper than public (no external wrapper).Private
private-Funktionen und State-Variablen sind nur innerhalb des definierenden Contracts zugänglich — nicht einmal für Subklassen. Sie ist die restriktivste Sichtbarkeit. KRITISCH: 'private' heißt NICHT geheim — alle Blockchain-Daten sind via eth_getStorageAt und Bytecodeanalyse öffentlich lesbar. private nur nutzen, um anderen Contracts Aufrufe/Vererbung zu verwehren; für echte Vertraulichkeit Verschlüsselung/Hashing.
contract Private {
uint256 private counter; // private state var
// private: ONLY callable from THIS contract (not even subclasses)
function _secret(uint256 x) private pure returns (uint256) {
return x * 42;
}
function caller() public pure returns (uint256) {
return _secret(5); // OK: same contract
}
}
contract Sub is Private {
// function useIt() public pure returns (uint256) {
// return _secret(5); // COMPILER ERROR: not accessible
// }
// function readCounter() public view returns (uint256) {
// return counter; // COMPILER ERROR: not accessible
// }
}
// IMPORTANT: 'private' does NOT mean hidden on-chain.
// All storage and bytecode are publicly readable via RPC.
// 'private' only means 'not part of the contract's ABI'
// and 'not callable/inheritable by other contracts'.
// For real confidentiality, use encryption or zero-knowledge proofs.Sichtbarkeits-Best-Practices
Best Practices: die restriktivste funktionierende Sichtbarkeit nutzen (private > internal > external > public). public-State-Variablen vermeiden, außer der Auto-Getter ist gewollt — explizite Getter erlauben später Validierung. external+calldata für Einstiegspunkte. Interne/private Helfer mit Unterstrich präfixieren. Jede public/external-Funktion ergänzt Bytecode; die ABI zu minimieren senkt Deployment- und Aufrufgas.
contract Best {
// 1. Default to the MOST restrictive visibility that works.
// Order: private < internal < external < public
// 2. State variables: NEVER public unless you want a free getter.
// Prefer private/internal + explicit getter functions,
// so you can add validation/logic later.
uint256 private _balance;
function balance() public view returns (uint256) {
return _balance;
}
// 3. External functions: use 'external' + 'calldata' for entry points
function buy(uint256[] calldata ids) external payable {
for (uint256 i = 0; i < ids.length; i++) {
_buyOne(ids[i]);
}
}
// 4. Internal helper: prefix with underscore convention
function _buyOne(uint256 id) internal {
// ...
}
// 5. Private for truly internal-only logic
function _computeFee(uint256 amount) private pure returns (uint256) {
return amount / 100;
}
// 6. Avoid public functions that are never called externally
// (wastes bytecode). Make them internal.
}
// Summary: visibility is part of the contract's API design.
// Smaller ABI = less bytecode = lower deployment + call gas.Contract-Interaktion
Andere Contracts aufrufen
Um einen anderen Contract aufzurufen, seine Adresse auf einen Interface-Typ casten: IToken(addr).method(). View-Aufrufe sind off-chain kostenlos, kosten aber Gas, wenn aus einer Transaktion aufgerufen. Rückgabewerte zustandsändernder Aufrufe immer prüfen (token.transfer liefert bool). Eine Adresse auf ein Interface zu casten verifiziert NICHT, dass der Contract es implementiert — existiert die Funktion nicht, revert-t der Aufruf.
interface IToken {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
contract Caller {
IToken public token;
address public owner;
constructor(address _token) {
token = IToken(_token);
owner = msg.sender;
}
// Call a view function on another contract
function getBalance(address who) public view returns (uint256) {
return token.balanceOf(who); // external call
}
// Call a state-changing function
function sendTokens(address to, uint256 amount)
public returns (bool)
{
require(msg.sender == owner, "not owner");
bool ok = token.transfer(to, amount);
require(ok, "transfer failed");
return true;
}
// Cast any address to an interface (no validation!)
function checkAny(address maybeToken)
public view returns (uint256)
{
return IToken(maybeToken).balanceOf(address(this));
}
}Interface-basierte Aufrufe
Interfaces nutzen, um mit jedem Contract zu interagieren, dessen ABI man kennt, ohne seine Quelle zu brauchen. Das entkoppelt Aufrufer von Implementierungen und funktioniert mit jedem Token/Protokoll, das einem Standard folgt (ERC20, ERC721, Chainlink-Feeds). Interfaces halten deinen Bytecode klein (keine geerbte Logik) und erlauben generischen Code (eine Wallet, die mit jedem ERC20 funktioniert). Für externe Aufrufe immer Interfaces statt konkreter Contracts bevorzugen.
interface IERC20 {
function name() external view returns (string memory);
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
contract Wallet {
IERC20 public immutable token;
address public owner;
constructor(address _token) {
token = IERC20(_token);
owner = msg.sender;
}
function tokenBalance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function withdraw(uint256 amount) public {
require(msg.sender == owner, "not owner");
token.transfer(owner, amount);
}
function tokenName() public view returns (string memory) {
return token.name();
}
}
// Why use interfaces?
// - Decouple: Wallet doesn't need to know token implementation
// - Reusability: works with ANY ERC20 (USDC, DAI, WETH, ...)
// - Smaller bytecode: don't inherit the token's code
// - Standardization: IERC20 is a documented ABILow-level call
address.call(payload) ist der niedrigstufigste Aufruf und liefert (bool, bytes). Nutzen, wenn kein Interface vorliegt, beliebige calldata weitergereicht werden sollen oder feine Kontrolle nötig ist (Gas, Wert). Calldata mit abi.encodeWithSignature/Selector/Call bauen. KRITISCH: 'ok' ist nur bei EVM-Fehlschlägen false (revert, out-of-gas), nicht bei logischen — 'data' dekodieren, um Revert-Gründe oder eigene Fehler zu inspizieren.
contract LowLevel {
// call: lowest-level call, returns (bool, bytes)
function callFn(address target, bytes memory payload)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = target.call(payload);
require(ok, "call failed");
return (ok, data);
}
// With Ether
function callWithEth(address target, bytes memory payload)
public payable returns (bool, bytes memory)
{
(bool ok, bytes memory data) = target.call{value: msg.value}(payload);
return (ok, data);
}
// With gas limit
function callWithGas(address target, bytes memory payload, uint256 gas)
public returns (bool, bytes memory)
{
return target.call{gas: gas}(payload);
}
// Helpers to build calldata:
// abi.encodeWithSignature("transfer(address,uint256)", to, amount)
// abi.encodeWithSelector(bytes4(selector), to, amount)
// abi.encodeWithCall(IERC20.transfer.selector, to, amount)
// WARNING: low-level call returns true even if the called function
// reverts internally — you only get false on EVM-level failure.
// Decode 'data' to inspect custom errors or return values.
function safeCall(address target) public returns (uint256) {
(bool ok, bytes memory data) = target.call(
abi.encodeWithSignature("getValue()")
);
require(ok, "call reverted");
return abi.decode(data, (uint256));
}
}Delegatecall
delegatecall führt den Code des Ziels im Storage-Kontext des AUFRUFERS aus — Zustandsänderungen treffen also den Aufrufer, nicht das Ziel. msg.sender und msg.value bleiben erhalten. Das ist das Fundament aufrüstbarer Proxies (EIP-1967, UUPS) und des Diamond-Musters (EIP-2535). KRITISCH: Das Storage-Layout muss zwischen Aufrufer und Ziel übereinstimmen, sonst wird der Zustand korrumpiert. Immer ein geteiltes Storage-Layout oder das AppStorage-Muster nutzen.
contract Delegate {
// delegatecall: executes target's code in CALLER's context
// - msg.sender is the ORIGINAL caller (preserved)
// - msg.value is preserved
// - Storage reads/writes affect the CALLER, not the target
// - address(this) is the CALLER
uint256 public num;
address public sender;
function delegateSet(address target, uint256 value) public {
// target's setNum() runs in THIS contract's storage
(bool ok, ) = target.delegatecall(
abi.encodeWithSignature("setNum(uint256)", value)
);
require(ok, "delegatecall failed");
}
}
contract Target {
// MUST have the same storage layout as Delegate for sane behavior!
uint256 public num;
address public sender;
function setNum(uint256 value) public {
num = value;
sender = msg.sender; // this is the ORIGINAL caller, not Delegate
}
}
// Use cases:
// - Proxy patterns (EIP-1967, UUPS, Transparent): upgradeable logic
// - Diamond pattern (EIP-2535): modular facets
//
// DANGER: storage layout mismatch => corrupted state.
// Both contracts MUST declare variables in the same order/types.
// Use a shared storage contract or app storage pattern.Staticcall
staticcall führt den Code des Ziels aus, revert-t aber bei jeder Zustandsänderung — der sichere Weg, aus unvertrauten Contracts zu lesen. Der Compiler nutzt automatisch staticcall, wenn du eine view/pure-Funktion über ein Interface aufrufst. staticcall direkt nutzen, wenn ein nur lesender Aufruf an einen Contract sichergestellt werden soll, der vorgibt, ein view zu sein. Liefert (bool, bytes) wie call.
contract Static {
// staticcall: like call, but REVERTS if the target modifies state.
// Used to safely READ from untrusted contracts.
function safeRead(address target, bytes memory payload)
public view returns (bytes memory)
{
(bool ok, bytes memory data) = target.staticcall(payload);
require(ok, "staticcall reverted");
return data;
}
function getBalance(address token, address who)
public view returns (uint256)
{
(bool ok, bytes memory data) = token.staticcall(
abi.encodeWithSignature("balanceOf(address)", who)
);
require(ok, "balanceOf failed");
return abi.decode(data, (uint256));
}
// Use cases:
// - Read from untrusted contracts without risk of state changes
// - Verify a contract behaves as a view function
// - Compose view-only queries across multiple contracts
// Distinguish from call():
// - call: allows state changes (target can write)
// - staticcall: forbids state changes (reverts if target writes)
// view/pure functions are called via staticcall automatically
// by the compiler when you call them normally.
function normalCall(IToken t, address who) public view returns (uint256) {
return t.balanceOf(who); // compiler emits staticcall
}
}
interface IToken { function balanceOf(address) external view returns (uint256); }Sicherheitsmuster
Reentrancy-Guard
Der Reentrancy-Guard ist ein Mutex, der verhindert, dass eine Funktion erneut betreten wird, während sie noch läuft. Vor dem Körper ein Flag setzen, danach lösen. Das verhindert den klassischen Angriff, bei dem receive/fallback eines bösartigen Contracts withdraw() erneut aufruft, bevor der Kontostand auf Null gesetzt ist (das DAO-Hack-Muster). nonReentrant auf jede Funktion anwenden, die nach einer Zustandsänderung einen externen Aufruf macht — selbst wenn auch checks-effects-interactions beachtet werden (Defense in Depth).
contract ReentrancyGuard {
// Classic mutex pattern using a storage flag
uint256 private _status = 1; // 1 = NOT_ENTERED, 2 = ENTERED
modifier nonReentrant() {
require(_status == 1, "REENTRANT");
_status = 2;
_;
_status = 1;
}
mapping(address => uint256) public balances;
function withdraw() public nonReentrant {
uint256 amount = balances[msg.sender];
require(amount > 0, "no balance");
// CRITICAL: update state BEFORE the external call
balances[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "send failed");
}
// Why needed: if we sent Ether FIRST, the attacker's receive()
// could call withdraw() again before balances was zeroed,
// draining the contract. This is the DAO hack pattern.
//
// Even with checks-effects-interactions, the guard is defense-in-depth.
// Apply nonReentrant to ANY function that:
// - Sends Ether to msg.sender
// - Calls an external contract
// - Then continues executing
}Checks-Effects-Interactions
Checks-Effects-Interactions (CEI) ist das wichtigste Sicherheitsmuster: (1) alle require-/Validierungschecks ausführen, (2) alle State-Variablen aktualisieren, (3) DANN externe Aufrufe machen. Mischet sich ein externer Aufruf wieder in deinen Contract ein, ist der Zustand bereits aktualisiert — der Angreifer kann nicht doppelt ausgeben. CEI allein verhindert die meisten Reentrancy-Bugs; mit einem nonReentrant-Modifikator für Defense-in-Depth bei kritischen Funktionen paaren.
contract CEI {
mapping(address => uint256) public balances;
// BAD: interaction BEFORE effect => reentrancy vulnerability
function vulnerable() public {
uint256 amount = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amount}(""); // INTERACTION
require(ok);
balances[msg.sender] = 0; // EFFECT (too late!)
// Attacker's receive() re-called this; balances still has funds.
}
// GOOD: checks, then effects, then interactions
function safe() public {
// 1. CHECKS: validate conditions
uint256 amount = balances[msg.sender];
require(amount > 0, "no balance");
// 2. EFFECTS: update state BEFORE external calls
balances[msg.sender] = 0;
// 3. INTERACTIONS: external calls LAST
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "send failed");
// If attacker re-enters, balances[msg.sender] is already 0.
}
// Pattern: order your code as
// require() checks first,
// state updates second,
// external calls last.
// This single rule prevents most reentrancy bugs.
// Pair with nonReentrant for defense-in-depth.
}Pull over Push
Pull over Push: Statt in einer Transaktion Ether an viele Empfänger zu pushen (ein schlechter Empfänger blockiert alle), jedem Nutzer seinen Kontostand gutschreiben und ihn via withdraw() selbst abholen lassen. Das isoliert Fehlschläge (der defekte receive/fallback eines Nutzers blockiert keine anderen) und senkt das Gas pro Transaktion. Für Airdrops, Börsen, Auktionsauszahlungen, Rückerstattungen. Mit nonReentrant auf withdraw() kombinieren.
contract PullOverPush {
// BAD (push): send Ether to many recipients in one tx
// If any recipient reverts (or is a contract that blocks), the WHOLE tx fails.
mapping(address => uint256) public pendingWithdrawals;
function pushPay(address[] memory recipients) public payable {
uint256 share = msg.value / recipients.length;
for (uint256 i = 0; i < recipients.length; i++) {
// If recipients[i].call fails, the whole loop reverts.
(bool ok, ) = recipients[i].call{value: share}("");
require(ok, "push failed");
}
}
// GOOD (pull): credit each user, let them withdraw individually
function credit(address[] memory recipients) public payable {
uint256 share = msg.value / recipients.length;
for (uint256 i = 0; i < recipients.length; i++) {
pendingWithdrawals[recipients[i]] += share; // just update state
}
}
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "nothing to withdraw");
pendingWithdrawals[msg.sender] = 0; // effect
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction
require(ok, "withdraw failed");
}
// Pull pattern isolates failures: one user's failed withdrawal
// doesn't block others. Common in: airdrops, exchanges, auctions.
}Pausable-Muster
Das Pausable-Muster ergänzt einen Not-Aus: ein boolesches 'paused', das kritische Funktionen via whenNotPaused-Modifikator regelt. Der Owner kann pausieren/fortsetzen. Als Circuit-Breaker nutzen, wenn ein Bug oder Angriff erkannt wird — pausieren, um weiteren Schaden zu stoppen, während ein Fix vorbereitet wird. Oft mit aufrüstbaren Proxies kombiniert (pausieren, dann gepatchte Logik deployen). OpenZeppelin liefert einen praxiserprobten Pausable-Contract, der statt eigenem Bau genutzt werden sollte.
contract Pausable {
bool public paused;
address public owner;
constructor() { owner = msg.sender; }
modifier whenNotPaused() {
require(!paused, "contract is paused");
_;
}
modifier whenPaused() {
require(paused, "contract is not paused");
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
// Critical functions check whenNotPaused
function deposit() public payable whenNotPaused {
// ...
}
function withdraw(uint256 amount) public whenNotPaused {
// ...
}
// Use case: emergency stop. If a bug is discovered, pause the
// contract to prevent further damage while a fix is prepared.
// Often combined with upgradeable proxies to deploy a patched version.
}
// OpenZeppelin provides Pausable as a reusable contract.Zugriffskontrolle
Zugriffskontrollmuster: (1) Ownable — ein einziger Owner mit onlyOwner-Modifikator (einfach, zentralisiert). (2) RBAC — rollenbasiert mit bytes32-Rollen und onlyRole-Modifikator (flexibel, Multi-Admin). (3) Multi-Sig oder Timelock — für hochwertige Contracts auf Gnosis Safe oder OpenZeppelin Timelock ausweichen. KRITISCH: msg.sender für Auth nutzen, NIE tx.origin (das von bösartigen Zwischen-Contracts verfälscht werden kann). OpenZeppelin liefert Ownable und AccessControl.
contract AccessControl {
// 1. Simple owner (Ownable pattern)
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function setOwner(address newOwner) public onlyOwner {
require(newOwner != address(0), "zero address");
owner = newOwner;
}
// 2. Role-based (RBAC)
mapping(bytes32 => mapping(address => bool)) public roles;
bytes32 public constant ADMIN = keccak256("ADMIN");
bytes32 public constant MINTER = keccak256("MINTER");
modifier onlyRole(bytes32 role) {
require(roles[role][msg.sender], "missing role");
_;
}
function grantRole(bytes32 role, address account)
public onlyRole(ADMIN)
{
roles[role][account] = true;
}
function revokeRole(bytes32 role, address account)
public onlyRole(ADMIN)
{
roles[role][account] = false;
}
function mint(address to, uint256 amount) public onlyRole(MINTER) {
// ...
}
// 3. Multi-sig / time-locked (defer to Gnosis Safe or OpenZeppelin Timelock)
// Always use msg.sender (NOT tx.origin) for authorization.
// tx.origin can be spoofed if a user interacts with a malicious
// intermediate contract.
}ERC20-Token-Standard
ERC20-Interface
ERC-20 ist der Standard für fungible Token (USDC, DAI, UNI). Das Interface definiert 6 Pflichtfunktionen (totalSupply, balanceOf, transfer, allowance, approve, transferFrom) und 2 Events (Transfer, Approval). Optionale Metadaten (name, symbol, decimals) werden universell implementiert. Für neue Token immer OpenZeppelins ERC20-Basis-Contract nutzen — auditiert, behandelt Randfälle und wird von Wallets/DEXs erkannt.
interface IERC20 {
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Metadata (optional but standard)
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Required functions
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount)
external returns (bool);
}
// ERC-20 is THE standard for fungible tokens (USDC, DAI, UNI, ...).
// Implemented by thousands of tokens; supported by every wallet/Dex.
// Implementing the interface correctly ensures interoperability.
// Use OpenZeppelin's ERC20 base contract — battle-tested and audited.Transfer-Funktion
transfer(to, amount) bewegt Token vom Aufrufer zu 'to'. Standard-Checks: Empfängeradresse ungleich Null, ausreichender Kontostand. Kontostände VOR dem Emittieren des Transfer-Events aktualisieren (CEI-Muster). Minting wird als Transfer von address(0) modelliert; Burning als Transfer an address(0). Das decimals-Feld (meist 18) heißt, Beträge sind in atomaren Einheiten (wei-äquivalent); UIs teilen durch 10^decimals für die Anzeige.
contract SimpleToken is IERC20 {
string public name = "Simple Token";
string public symbol = "SIM";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor(uint256 _initialSupply) {
totalSupply = _initialSupply;
balanceOf[msg.sender] = _initialSupply;
emit Transfer(address(0), msg.sender, _initialSupply);
}
function transfer(address to, uint256 amount) external returns (bool) {
require(to != address(0), "zero address");
require(balanceOf[msg.sender] >= amount, "insufficient");
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
// Note: 0.8+ auto-checks underflow, so we can simplify:
// balanceOf[msg.sender] -= amount;
// If insufficient, it reverts automatically.
// But explicit require gives clearer error messages.
}Approve & Allowance
approve(spender, amount) legt fest, wie viel 'spender' in deinem Namen transferieren darf (via transferFrom). Üblich bei DEXs und Staking. WARNUNG: Die approve-Race-Bedingung — Allowance von A auf B zu ändern lässt einen Angreifer A und B ausgeben, wenn er davor ausführt. Abmildern durch erst auf 0 setzen, dann auf den neuen Wert, ODER increaseAllowance/decreaseAllowance nutzen (OpenZeppelin). Das Approval-Event muss bei jeder Änderung emittiert werden.
contract ApprovalExample is IERC20 {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// approve: allow 'spender' to spend up to 'amount' on your behalf
function approve(address spender, uint256 amount) external returns (bool) {
require(spender != address(0), "zero address");
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// Common use cases:
// - DEX trading: approve the DEX router to spend your tokens
// - Staking: approve the staking contract
// - Subscriptions: approve a recurring spender
// WARNING: the approve race condition.
// If you change allowance from 100 to 50, an attacker who saw 100
// could spend 100 BEFORE your tx, then spend 50 AFTER = 150 total.
// Mitigation (EIP-20): set to 0 first, then to new value.
// approve(spender, 0); approve(spender, 50);
// Or use increaseAllowance / decreaseAllowance (OpenZeppelin).
function increaseAllowance(address spender, uint256 added)
public returns (bool)
{
uint256 newAllowance = allowance[msg.sender][spender] + added;
allowance[msg.sender][spender] = newAllowance;
emit Approval(msg.sender, spender, newAllowance);
return true;
}
}TransferFrom
transferFrom(from, to, amount) erlaubt einem genehmigten Spender, Token von 'from' nach 'to' zu bewegen. Die Allowance des Spenders muss >= amount sein; die Allowance als Teil des Effekts verringern (CEI). Genutzt von DEX-Routern, Staking-Contracts und jedem pull-basierten Workflow. Token-Eigenheiten: USDT verringert die Allowance nicht; manche Token revert-en bei Zero-Address-Transfers. Vor der Integration immer mit dem konkreten Token testen.
contract TransferFromExample is IERC20 {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// transferFrom: spender moves tokens from 'from' to 'to'
// Requires allowance[from][spender] >= amount
function transferFrom(address from, address to, uint256 amount)
external returns (bool)
{
require(to != address(0), "zero address");
require(balanceOf[from] >= amount, "insufficient balance");
require(allowance[from][msg.sender] >= amount, "insufficient allowance");
// Update allowance FIRST (CEI)
allowance[from][msg.sender] -= amount;
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
return true;
}
// Used by:
// - DEX routers (user approves router, router calls transferFrom)
// - Staking contracts
// - Any 'pull' workflow where a contract takes tokens from a user
// Note on infinite allowance:
// Some tokens (USDT) do NOT decrement allowance on transferFrom,
// and others set allowance to max uint256 by default. Read the
// specific token's docs before integrating.
}ERC20-Events
ERC-20 definiert zwei Events: Transfer (bei jeder Token-Bewegung emittiert, inklusive Mint von address(0) und Burn an address(0)) und Approval (bei jeder Allowance-Änderung emittiert). Diese Events sind, wie dApps und Indexer (The Graph, Dune, Etherscan) Token-Aktivität tracken, ohne den Zustand direkt abzufragen. Immer emittieren — Events wegzulassen bricht die Interoperabilität mit Wallets und Börsen, die auf Logs bauen.
contract ERC20Events {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 public totalSupply;
function _mint(address to, uint256 amount) internal {
require(to != address(0), "zero address");
totalSupply += amount;
balanceOf[to] += amount;
// Minting = transfer from address(0)
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal {
require(balanceOf[from] >= amount, "insufficient");
balanceOf[from] -= amount;
totalSupply -= amount;
// Burning = transfer to address(0)
emit Transfer(from, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
emit Approval(owner, spender, amount);
}
// Events let dApps and indexers (The Graph, Dune) track:
// - Every transfer (incl. mint/burn)
// - Every approval change
// - Token holdings over time
// Without events, integrating with wallets/DEXs is much harder.
}Deployment & Testing
Remix IDE
Remix ist der einfachste Einstieg in Solidity — eine Browser-IDE ohne Installation. Sie enthält einen Compiler, eine JavaScript-VM für lokales Testen, Deployment auf Testnets, einen Transaktions-Debugger und statische Analyse. Super zum Lernen und Prototyping. Für Produktion zu Hardhat oder Foundry wechseln für Scripting, automatisierte Tests und CI/CD-Integration.
// Remix is a browser-based IDE for Solidity.
// URL: https://remix.ethereum.org
// Features:
// - File explorer, editor, compiler, deployer in one tab
// - Built-in Solidity compiler (no install needed)
// - Deploy to JavaScript VM, local node, or testnet
// - Interact with deployed contracts via GUI
// - Debug transactions step-by-step
// - Static analysis tools (Remix Analyzer)
// Workflow:
// 1. Create a .sol file in the File Explorer
// 2. Compile in the "Solidity Compiler" tab (pick version)
// 3. Deploy in the "Deploy & Run Transactions" tab
// 4. Interact via the deployed contract panel
// Good for: learning, prototyping, quick tests, debugging.
// Not ideal for: production workflows, automated testing, scripting.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Hello {
string public msg = "Hello from Remix";
}Hardhat-Setup
Hardhat ist eine JavaScript-/TypeScript-basierte Entwicklungsumgebung. Via npm installieren, Netzwerke und Compiler in hardhat.config.ts konfigurieren. Er liefert Kompilierung, Tests (Mocha/Chai), einen lokalen Knoten (hardhat node), Deployment-Skripte und eine Konsole. Das Hardhat-Toolbox-Plugin-Bündel schließt ethers.js, chai, typechain und mehr ein. .env für Geheimnisse nutzen (private Schlüssel, RPC-URLs).
// Hardhat: JavaScript/TypeScript development environment
// Install: npm install --save-dev hardhat
// Init: npx hardhat init
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
const config: HardhatUserConfig = {
solidity: {
version: "0.8.19",
settings: { optimizer: { enabled: true, runs: 200 } },
},
networks: {
hardhat: {}, // built-in local network
sepolia: {
url: `${process.env.ALCHEMY_URL}`,
accounts: [process.env.PRIVATE_KEY ?? ""],
},
},
};
export default config;
// Project layout:
// contracts/ Solidity source files
// scripts/ deployment scripts (JS/TS)
// test/ test files (Chai/Mocha)
// ignition/ Hardhat Ignition modules (declarative deploy)
// Common commands:
// npx hardhat compile
// npx hardhat test
// npx hardhat run scripts/deploy.ts --network sepolia
// npx hardhat node // start local node
// npx hardhat console // interactive REPLHardhat-Tests
Hardhat-Tests nutzen Mocha + Chai + ethers.js. getSigners() liefert Testkonten mit ETH. connect(addr) sendet eine Tx von einem bestimmten Konto. Assertions: Gleichheit (equal), Reverts (revertedWith), Events (emit + withArgs). TypeChain erzeugt automatisch TypeScript-Typen aus deinen ABIs — Autocomplete und Compile-Zeit-Checks. Tests mit 'npx hardhat test' ausführen.
// test/Token.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { Token } from "../typechain-types";
describe("Token", () => {
let token: Token;
let owner: any, addr1: any;
beforeEach(async () => {
[owner, addr1] = await ethers.getSigners();
const Factory = await ethers.getContractFactory("Token");
token = await Factory.deploy(1000);
await token.waitForDeployment();
});
it("assigns initial supply to owner", async () => {
expect(await token.balanceOf(owner.address)).to.equal(1000);
});
it("transfers tokens between accounts", async () => {
await token.transfer(addr1.address, 100);
expect(await token.balanceOf(addr1.address)).to.equal(100);
});
it("reverts on insufficient balance", async () => {
await expect(
token.connect(addr1).transfer(owner.address, 1)
).to.be.revertedWith("insufficient");
});
it("emits Transfer event", async () => {
await expect(token.transfer(addr1.address, 100))
.to.emit(token, "Transfer")
.withArgs(owner.address, addr1.address, 100);
});
});
// Run: npx hardhat test
// TypeChain generates typed contract bindings in typechain-types/.Foundry-Setup
Foundry (forge) ist ein schnelles Rust-basiertes Toolkit, in dem Tests in Solidity selbst geschrieben werden — kein JavaScript/TypeScript nötig. Installation via foundryup. Kernwerkzeuge: forge (build, test, script), cast (CLI für RPC-Aufrufe), anvil (lokaler Knoten), chisel (Solidity-REPL). Schneller als Hardhat und mit eingebautem Fuzz-Testing. Dependencies sind git-Submodule unter lib/. Konfiguration liegt in foundry.toml.
// Foundry: Rust-based, fast Solidity dev toolkit
// Install: curl -L https://foundry.paradigm.xyz | bash
// foundryup
// Init: forge init my-project
// Project layout:
// src/ Solidity sources (Default = src/Contract.sol)
// test/ Solidity tests (*.t.sol)
// script/ Deployment scripts (*.s.sol)
// lib/ Dependencies (git submodules, e.g. forge-std, openzeppelin)
// Commands:
// forge build // compile
// forge test // run tests
// forge test -vvv // verbose (shows console logs)
// forge coverage // code coverage
// forge script script/Deploy.s.sol --rpc-url $RPC --broadcast
// Foundry config (foundry.toml):
// [profile.default]
// src = "src"
// out = "out"
// libs = ["lib"]
// solc = "0.8.19"
// optimizer = true
// optimizer_runs = 200
// Why Foundry?
// - Tests are written IN Solidity (no JS/TS context switch)
// - Extremely fast (parallelized, cached)
// - Built-in fuzzing and invariant testing
// - Cast/anvil/chisel CLI tools includedFoundry-Tests (Solidity)
Foundry-Tests sind Solidity-Contracts, die forge-std/Test erweitern. assertEq, assertTrue usw. für Assertions nutzen. Cheatcodes (vm.*) manipulieren die EVM: vm.prank, um msg.sender zu fälschen, vm.warp, um die Zeit zu setzen, vm.deal, um ETH zu minten, vm.expectRevert, um Fehlschläge zu behaupten. Fuzz-Tests (testFuzz_*) erzeugen automatisch zufällige Eingaben innerhalb von Einschränkungen (vm.assume). Invariant-Tests (testInvariant_*) laufen zufällige Sequenzen, um gebrochene Invarianten zu finden.
// test/Token.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenTest is Test {
Token public token;
address owner = address(this);
address user = address(0x1);
function setUp() public {
token = new Token(1000);
}
function testInitialSupply() public view {
assertEq(token.balanceOf(owner), 1000);
}
function testTransfer() public {
token.transfer(user, 100);
assertEq(token.balanceOf(user), 100);
}
function testRevertOnInsufficient() public {
vm.expectRevert("insufficient");
token.transfer(user, 99999);
}
// Fuzz test: 'x' is randomized by the framework
function testFuzzTransfer(uint256 x) public {
vm.assume(x <= 1000);
token.transfer(user, x);
assertEq(token.balanceOf(user), x);
}
// Cheatcodes (vm.*):
// vm.prank(addr) // next call from addr
// vm.startPrank(addr) // all subsequent calls from addr
// vm.warp(timestamp) // set block.timestamp
// vm.roll(blockNum) // set block.number
// vm.deal(addr, 1 ether) // give ETH to addr
// vm.expectRevert(...) // assert next call reverts
// vm.expectEmit(...) // assert next call emits event
}
// Run: forge test -vvvVerwandte Solidity-Snippets
Copy-paste ready code for common tasks.
Vertrag-Grundlagen
Einen einfachen Smart Contract mit Zustand und Funktionen definieren.
Funktionen und Sichtbarkeit
Funktionssichtbarkeit, payable und Rückgabewerte.
Modifiers und Zugriffskontrolle
Validierungslogik mit Modifiers wiederverwenden.
Events und Logs
Events für Off-Chain-Listener emittieren.
Mappings, Structs & Verschachtelter Storage
Verwandte Daten mit Structs gruppieren und per Schlüssel mit Mappings abfragen.
Vererbung, Abstract & Interfaces
Logik via Vererbung wiederverwenden; Verträge mit abstract und interface definieren.
Payable, receive & fallback (ETH-Flüsse)
ETH via payable-Funktionen und receive/fallback-Hooks empfangen.
Reentrancy & Checks-Effects-Interactions
Verträge gegen den häufigsten Smart-Contract-Angriff härten.
Was this helpful?