시작하기
계약 기초
Solidity는 이더리움 스마트 계약의 주 언어입니다. pragma는 컴파일러 버전을 지정합니다. 계약(contract)은 클래스와 같습니다. 함수는 public, private, view(읽기 전용), payable이 될 수 있습니다.
// 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와 컴파일러 버전
pragma는 컴파일러 버전을 지정합니다. ^0.8.0은 모든 0.8.x 패치 버전을 허용합니다. 운영 환경에서는 예기치 않은 문제를 피하려고 버전을 정확히 고정하세요(0.8.19). 모든 .sol 파일 맨 위에 항상 pragma를 포함하세요.
// 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;주석과 NatSpec
NatSpec 주석(/// 또는 /** */)은 문서를 생성합니다. @notice는 최종 사용자용, @dev는 개발자용, @param은 매개변수 설명, @return은 반환 값 설명입니다. Etherscan과 Remix 같은 도구가 이를 수집합니다.
// 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 라이선스
Solidity 0.6.8부터 파일 맨 위에 SPDX 라이선스 식별자를 넣는 것이 필수입니다. 도구와 사용자가 코드 재사용 방식을 이해하는 데 도움이 됩니다. 관대한 오픈 소스에는 MIT, 카피레프트에는 GPL-3.0, 비공개 코드에는 UNLICENSED를 사용하세요.
// 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 {}파일 구조와 가져오기
가져오기(import)는 계약, 라이브러리, 인터페이스를 불러옵니다. {Name}을 쓰면 특정 항목만 가져옵니다. 상대 경로도 예상대로 동작합니다. 'is' 키워드는 상속을 설정합니다. 파일에는 보통 주 계약 하나가 있지만 여러 개가 있을 수도 있습니다.
// 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 {
// ...
}값 타입
정수(uint / int)
uint는 부호 없는 정수(음수 없음), int는 부호 있는 정수입니다. 크기는 8에서 256까지 8 단위로 있습니다. uint의 기본값은 uint256입니다. 0.8.0부터 산술 연산이 오버플로/언더플로를 자동 검사하고 되돌립니다. 경계 값은 type(T).max / type(T).min으로 얻으세요.
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;불리언
bool은 true 또는 false만 될 수 있습니다. &&와 ||는 단락 평가라 필요할 때만 오른쪽을 평가합니다. 기본값은 false입니다. 일부 문맥(스토리지 패킹)에서는 불리언이 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; // false주소
address는 20바이트 이더리움 주소를 담습니다. address payable은 이더를 받을 수 있습니다(transfer/send 메서드 보유). 변환에는 payable(x)를 사용하세요. 주소에는 .balance 속성(단위 wei)이 있습니다. 오타를 잡으려면 주소 리터럴을 EIP-55 체크섬으로 항상 검증하세요.
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);바이트와 바이트 배열
고정 바이트(bytes1..bytes32)는 저렴하고 해시/선택자에 사용됩니다. 동적 bytes는 원시 바이너리 데이터, string은 UTF-8 텍스트용입니다. 해시에는 bytes32를 사용하세요(keccak256은 bytes32 반환). 바이트 배열에는 bytes.concat()(0.8.4+)이 abi.encodePacked보다 저렴합니다.
// 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"));열거형
열거형(enum)은 이름 있는 값의 유한 집합을 정의합니다. uint8로 저장됩니다(최대 256개 멤버). 기본값은 첫 번째 멤버(인덱스 0)입니다. 캐스트로 enum과 uint를 변환하세요. type(EnumName).max는 가장 높은 멤버를 제공합니다.
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
}타입 변환과 캐스팅
암시적 변환은 데이터 손실 가능성이 없을 때만 일어납니다(uint8 -> uint256). 좁히는 변환(uint256 -> uint8)이나 부호 있는/없는 변환에는 명시적 캐스트를 사용하세요. 음수 int를 uint로 변환하면 2의 보수 때문에 매우 큰 수가 됩니다.
// 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!참조 타입
문자열
Solidity의 문자열은 UTF-8 바이트 배열입니다. length()는 문자 수가 아니라 바이트 수를 반환합니다(이모지/다중 바이트 문자는 다름). 동등 비교는 keccak256 해시로 해야 합니다. string.concat(0.8.12+)은 abi.encodePacked보다 저렴합니다. 문자열은 가스가 비쌉니다.
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; }
}배열(고정 및 동적)
고정 배열 [N]은 컴파일 시 크기가 정해지고, 동적 배열 []은 push/pop으로 커집니다. 메모리 배열은 'new Type[](size)'로 만들어야 합니다. 스토리지 배열 읽기/쓰기는 가스가 들므로 임시 데이터에는 memory를 권장합니다. 0.6+에서 push()는 참조를 반환합니다.
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;
}
}구조체
구조체(struct)는 관련 필드를 묶습니다. storage나 memory에 저장하거나 함수 인자로 전달할 수 있습니다. 파일이나 계약 수준에서 정의하세요. 이름 있는 필드 {field: value}로 초기화하면 더 명확하고, 위치 기반은 더 짧습니다. 구버전에서는 매핑 값을 구조체로 통째로 접근할 수 없습니다.
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
}
}매핑
매핑(mapping)은 해시 테이블입니다: keccak256(key) => value. 길이가 없고 반복할 수 없습니다. 키는 값 타입(uint, address, bytes, enum)이 될 수 있고 값은 무엇이든 가능합니다. 중첩 매핑은 다중 키 조회를 허용합니다. 반복하려면 키 배열을 따로 유지하세요. delete는 키를 0 값으로 초기화합니다.
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
}
}데이터 위치(storage / memory / calldata)
storage는 온체인 영구 상태(비쌈)입니다. memory는 함수 호출 동안 존재하는 임시 공간(저렴)입니다. calldata는 읽기 전용이며 external 함수 입력에만 쓰입니다(가장 저렴). 읽기만 하는 external 함수 인자에는 항상 calldata를 사용하세요. 기본 위치: 상태 변수는 storage, 함수 지역의 복합 타입은 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
}중첩 구조
구조체는 배열, 매핑(스토리지에서만), 다른 구조체를 담을 수 있습니다. 스토리지 참조로 중첩 구조체 필드에 접근하면 가스 효율이 좋습니다. 깊은 중첩은 스토리지 슬롯 사용과 배포 비용을 늘리므로 주의하세요. 구조체 매핑은 가장 흔한 온체인 데이터베이스 패턴입니다.
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;
}상태 변수
public 및 private 상태 변수
public 상태 변수는 getter 함수를 자동 생성합니다. private은 계약 내부로 접근을 제한하고, internal은 하위 클래스도 허용합니다. 기본값은 internal입니다. 중요: 'private'은 비밀을 뜻하지 않습니다. 모든 블록체인 데이터는 공개적으로 읽을 수 있습니다. 기밀성이 필요하면 암호화/해싱을 사용하세요.
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; }상수 변수
constant 변수는 컴파일 시 평가되어 바이트코드에 인라인되므로 런타임 가스가 0입니다(SLOAD 없음). 값 타입(uint, address, bytes 등)만 constant가 될 수 있습니다. 값은 컴파일 시 표현식이어야 합니다. MAX_SUPPLY, DECIMALS, 주소 같은 고정 값에 constant를 사용하세요.
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 변수는 생성자에서 한 번 설정된 뒤 읽기 전용이 됩니다. 스토리지가 아니라 바이트코드에 저장되므로 읽기가 일반 상태 변수보다 저렴합니다. constant와 달리 생성자 인자와 런타임 값을 사용할 수 있습니다. owner, 토큰 이름, 체인별 설정처럼 배포 시 정해지는 값에 immutable을 사용하세요.
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; }
}전역 변수(msg, tx, block)
msg는 호출 문맥을 제공합니다: msg.sender(직접 호출자), msg.value(보낸 wei), msg.data(원시 calldata), msg.sig(함수 선택자). tx는 트랜잭션 정보를 제공합니다: tx.origin(EOA, 인증에는 권장하지 않음). block은 현재 블록 정보를 제공합니다: block.timestamp, block.number, block.chainid, block.coinbase. 권한 인증에 tx.origin을 절대 쓰지 말고 msg.sender를 사용하세요.
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
}
}블록과 트랜잭션 속성
blockhash()는 최근 256개 블록의 해시만 반환하고 그보다 오래된 블록은 0을 반환합니다. block.timestamp는 채굴자가 설정하며 약 15초까지 오차가 있을 수 있으므로 정밀한 타이밍이나 난수에 절대 사용하지 마세요. block.basefee는 EIP-1559에서 왔습니다. gasleft()는 폐기된 msg.gas를 대체합니다. chainid는 재전송 공격 방어에 중요합니다.
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
}
}함수
함수 문법
함수 문법: function 이름(매개변수) 가시성 변경가능성 returns(...). 가시성(public/external/internal/private)은 필수입니다. 변경가능성(pure/view/payable)은 선택이지만 권장합니다. 여러 반환 값을 지원합니다. 명명 반환을 쓰면 직접 할당하고 return 키워드를 생략할 수 있습니다.
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 함수
view 함수는 상태를 읽을 수 있지만 수정할 수 없습니다. eth_call로 외부 호출하면 무료입니다(가스비 없음). 상태를 수정하는 함수에서 내부 호출하면 가스를 소모합니다. 상태만 읽는 함수에는 view를 사용하세요. 의도를 드러내고 오프체인 무료 읽기를 가능하게 합니다.
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 함수
pure 함수는 상태를 읽거나 쓸 수 없고 입력만으로 계산합니다. 가장 제한적이며 오프체인 호출 비용이 가장 저렴합니다. 유틸리티 함수(수학, 입력 해싱)에 pure를 사용하세요. msg.sender나 블록 데이터가 필요하면 view를 사용하세요. pure는 다른 pure 함수만 호출할 수 있습니다.
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 함수
payable 함수는 msg.value로 이더를 받을 수 있습니다. 이더는 자동으로 계약 잔액에 추가됩니다. 이더를 받을 수 있는 것은 payable 함수와 receive/fallback뿐입니다. 특정 금액을 기대하면 항상 msg.value를 검증하세요. non-payable 함수에 이더를 보내면 되돌립니다.
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
}
}반환 값과 명명 반환
함수는 튜플로 여러 값을 반환할 수 있습니다. 명명 반환은 가독성을 높이고 return 문 없이 직접 할당할 수 있게 합니다. 명시적 return 문은 명명 반환을 덮어씁니다. 구조 분해 (a, b) = f()로 여러 반환을 받고, 필요 없는 값은 (, b)나 (a,)로 건너뛰세요.
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;
}
}함수 오버로딩
Solidity는 함수 오버로딩을 지원합니다. 같은 이름에 매개변수 타입이나 개수가 다른 여러 함수를 둘 수 있습니다. 컴파일러가 인자 타입으로 어느 것을 호출할지 결정합니다. 반환 타입만으로는 오버로드를 구분할 수 없습니다. address와 address payable, 또는 서로 다른 숫자 범위를 모두 받을 때 유용합니다.
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
}생성자와 특수 함수
생성자
constructor는 계약이 배포될 때 한 번 실행되며 상태를 초기화합니다. 다시 호출할 수 없습니다. 생성자 인자는 프레임워크에 따라 배포 바이트코드에 붙거나 ABI로 전달됩니다. 상속에서는 부모 생성자 인자를 상속 목록(Owned(_owner))이나 수정자 스타일(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 함수
receive()는 calldata 없이 이더를 보내는 호출(예: 계약으로 send/transfer) 시 실행됩니다. 인자나 반환 없이 'external payable'이어야 합니다. receive 함수는 하나만 허용됩니다. receive와 fallback이 모두 없으면 순수 이더 전송은 되돌려집니다(selfdestruct로 강제 전송하는 경우 제외).
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 함수
fallback()은 선택자와 일치하는 함수가 없거나, receive가 없는데 순수 이더 전송이 시도될 때 호출됩니다. payable이 될 수 있습니다. fallback 로직은 최소한으로 유지하세요. send()/transfer()로 호출되면 2300 가스(스티펜드)만 받으므로 스토리지 쓰기나 이벤트 발생을 감당하지 못합니다.
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는 남은 이더를 지정 주소로 보내고 (Dencun 이전에는) 계약 코드를 제거합니다. EIP-6780(2024년 3월) 이후에는 같은 배포 트랜잭션 안에서 호출될 때만 코드를 제거하고, 그 외에는 이더만 전송합니다. 보안을 위해 selfdestruct에 의존하지 마세요. 강제 이더가 여전히 들어올 수 있고 코드가 남을 수 있습니다.
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' flag함수 선택자
모든 함수에는 4바이트 선택자가 있습니다. keccak256(시그니처)의 첫 4바이트입니다. 시그니처는 공백 없는 함수 이름과 매개변수 타입입니다(예: 'transfer(address,uint256)'). EVM은 선택자로 호출을 라우팅합니다. msg.sig는 현재 함수의 선택자를 제공합니다. abi.encodeWithSelector/Signature는 저수준 호출용 calldata를 만듭니다.
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)
);
}
}수정자
수정자 기초
수정자(modifier)는 재사용 가능한 사전/사후 조건으로 함수를 감쌉니다. _; 자리 표시자에서 함수 본문이 실행됩니다. 수정자는 접근 제어(onlyOwner), 검증(validInput), 재진입 가드에 좋습니다. 기본적으로 함수 본문 전에 적용되며 _;로 본문 실행 위치를 제어합니다.
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;
}
}인자가 있는 수정자
수정자는 인자를 받을 수 있어 유연합니다. 인자는 호출 지점에서 평가되고 수정자가 실행될 때 바인딩됩니다. 흔한 패턴: 호출당 과금용 costs(price), RBAC용 onlyRole(role), 스로틀링용 rateLimit(window). _; 앞 로직은 사전 조건, 뒤 로직은 사후 조건입니다.
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
}
}여러 수정자
한 함수에 여러 수정자를 붙일 수 있습니다. 수정자는 스택처럼 함수 본문을 감싸며 순서대로 실행됩니다. 첫 수정자의 사전 조건이 먼저 실행되고, 그다음 두 번째, ..., 본문, 그 뒤 역순으로 풀립니다. 순서가 중요하므로 가장 저렴하고 실패 가능성이 높은 검사를 먼저 두어 가스를 절약하세요.
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;
}
}수정자 순서와 가스
수정자 순서는 가스와 명확성에 영향을 줍니다. 저렴한 검사(불리언, 주소 비교)를 먼저, 비싼 검사(스토리지 쓰기, 외부 호출)를 나중에 두세요. 실패 가능성이 높은 검사를 먼저 두면 단락 평가로 불필요한 가스를 환불받습니다. 의도한 순서를 주석으로 문서화하세요.
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; }
}흔한 수정자 패턴
흔한 수정자 패턴: nonReentrant(본문 전에 락 설정, 후에 해제), whenNotPaused/whenPaused(회로 차단기), onlyRole(bytes32 역할 기반 RBAC), rateLimit(타임스탬프 기반 사용자별 스로틀). 재진입 가드가 가장 중요합니다. 상태 변경 후 외부 호출을 하는 모든 함수에 적용하세요.
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;
_;
}
}이벤트
이벤트 선언과 emit
이벤트는 블록체인에 기록되며 오프체인 클라이언트가 eth_getLogs로 읽을 수 있습니다. 다른 계약은 읽을 수 없습니다. 최대 3개 매개변수에 indexed를 붙여 필터링 가능하게 하세요. 이벤트는 스토리지 쓰기보다 가스가 저렴합니다. dApp과 인덱서가 반응할 수 있도록 중요한 상태 변경에는 항상 이벤트를 발생시키세요.
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;
}
}Indexed 매개변수
indexed 매개변수는 오프체인 클라이언트(dApp, The Graph, 인덱서)가 필터링할 수 있는 토픽이 됩니다. 이벤트당 최대 3개 indexed 매개변수(네 번째 토픽은 이벤트 시그니처 해시용으로 예약). indexed 값 타입(uint, address)은 직접 저장되고, indexed 참조 타입(string, bytes, 배열)은 keccak256 해시되어 복원할 수 없습니다.
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.
}익명 이벤트
익명(anonymous) 이벤트는 topic[0]의 이벤트 시그니처 해시를 생략해 슬롯을 확보하므로 indexed 매개변수를 3개 대신 4개까지 쓸 수 있습니다. 대신 클라이언트가 이벤트 이름(시그니처)으로 필터링할 수 없어 여러 익명 이벤트를 구분하기 어렵습니다. 유용한 경우는 드물고 가스 절약도 미미합니다.
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.
}이벤트 모범 사례
모범 사례: 상태 변경 후 이벤트 발생(최종 상태 반영), 인덱서가 추가 RPC 호출을 피하도록 돕는 필드 포함(newBalance 등), 빡빡한 루프에서 발생 피하기(배치 처리), 가장 자주 필터링하는 필드(주소, ID, 상태 코드)를 인덱싱. 이벤트는 계약과 오프체인 간 주요 통신 채널입니다.
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)
}이벤트 vs 로그 vs 스토리지
스토리지는 상태 트라이에 있어 다른 계약과 view 함수가 읽을 수 있지만 비쌉니다(SSTORE당 약 20k 가스). 이벤트/로그는 영수증 트라이에 있어 계약이 읽을 수 없지만 저렴하고(약 1-2k 가스) eth_getLogs로 오프체인에서 접근할 수 있습니다. 온체인 의사결정에는 스토리지, 상태 변경을 dApp/인덱서에 알리는 데는 이벤트를 사용하세요.
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.
}오류 처리
Require
require(cond, msg)는 cond가 거짓이면 트랜잭션을 되돌리고 사용하지 않은 가스를 환불합니다. 가장 흔한 검증 기본 요소로 입력 검사, 접근 제어, 사전 조건에 사용하세요. 메시지 문자열은 가스를 소모합니다(배포 바이트코드에 저장). 가스를 절약하려면 문자열 메시지 대신 사용자 정의 오류(revert ErrorName())를 사용하세요.
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)는 이유 문자열과 함께 트랜잭션을 명시적으로 되돌립니다. 분기 로직이 필요할 때 if 문 안에서 revert()를 사용하세요(require는 문법적 편의일 뿐). 메시지 없는 revert()가 revert("msg")보다 저렴합니다. 사용자 정의 오류(revert ErrorName(args))는 가장 저렴하고 설명적이므로 새 코드에서 권장합니다.
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)는 코드가 올바르다면 절대 거짓이 되어선 안 되는 불변 조건용입니다. assert 실패는 버그를 뜻합니다. 0.8.0 이전에는 assert가 모든 가스를 소모했지만, 0.8.0부터는 revert처럼 동작합니다. 입력 검증과 예상된 오류 조건에는 require를, 버그를 알리는 불가능한 상태에만 assert를 사용하세요. 최신 자동 오버플로 검사는 assert가 아니라 revert를 씁니다.
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
}
}사용자 정의 오류
사용자 정의 오류(0.8.4+)는 되돌리기의 권장 방법입니다. 4바이트 선택자와 ABI 인코딩 인자로 표현되어 문자열 메시지(바이트코드에 전체 UTF-8로 저장)보다 훨씬 저렴합니다. 클라이언트는 선택자를 디코드해 어떤 오류인지 알고 구조화된 인자를 읽습니다. 파일이나 계약 수준에서 오류를 정의한 뒤 '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는 외부 호출의 오류만 처리합니다. 내부 함수 호출의 revert는 잡을 수 없습니다. 'returns' 절은 성공 값을 캡처합니다. catch Error()는 문자열 메시지가 있는 revert/require를, catch Panic()은 assert/오버플로 패닉을 잡습니다. catch (bytes)는 사용자 정의 오류와 알 수 없는 revert를 위한 폴백입니다. 외부 계약 실패를 우아하게 처리하는 데 사용하세요.
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).
}오류 메시지와 패턴
최신 오류 처리는 구조화되고 저렴한 revert를 위해 사용자 정의 오류를 사용합니다. 구버전 문자열 메시지는 0.8.4 이전 코드에서 여전히 흔합니다. 항상 실행 가능한 문맥을 포함하세요: 어떤 값이 잘못됐고 무엇이 기대됐는지. 동적 주소/숫자를 문자열 메시지에 넣지 마세요. 바이트코드를 비대하게 만들고 파싱할 수 없습니다. 문자열을 꼭 써야 하면 'INVALID:' 같은 접두사를 붙여 로그 인덱싱을 돕세요.
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);
}상속
'is'로 상속
상속은 'is' 키워드를 사용합니다. 자식 계약은 부모의 모든 상태 변수, 함수, 수정자를 상속합니다. 부모 생성자 인자는 상속 목록(Animal("dog"))이나 생성자 수정자 스타일로 전달합니다. 자식은 부모에서 virtual로 표시된 함수를 재정의할 수 있습니다. Solidity는 다중 상속을 지원합니다(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은 함수를 재정의 가능으로 표시하고, override는 부모 함수를 재정의함을 표시합니다. 함수는 기본적으로 비가상(더 안전)입니다. 공통 기반을 공유하는 여러 부모에서 재정의할 때는 override(A, B)처럼 나열하세요. 추가 재정의를 허용하려면 virtual override를 사용하세요. 상태 변수는 재정의할 수 없습니다(메모리에서 가릴 수만 있음).
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 키워드
super.method()는 부모 버전의 메서드를 호출해 동작을 대체하지 않고 확장할 수 있게 합니다. 단일 상속에서는 직관적입니다. 다중 상속에서 super는 C3 선형화를 따르므로 어휘적 부모가 아니라 형제 계약을 호출할 수 있습니다. 다이아몬드 상속에서 super를 쓸 때는 선형화 순서(가장 파생된 것이 마지막)를 항상 확인하세요.
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)
}
}다중 상속
Solidity는 'is' 키워드로 다중 상속을 지원합니다. 부모를 가장 기반인 것부터 가장 파생된 것 순으로 나열하세요: 'is Ownable, Pausable'. C3 선형화 알고리즘이 결정적 순서를 만들어 다이아몬드 문제를 해결합니다. 여러 부모에게서 상속한 함수를 재정의할 때는 'override(A, B)'를 사용하세요. 생성자는 선형화 순서(부모 먼저)로 실행됩니다.
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.생성자 상속
부모 생성자 인자는 고정 값이면 상속 목록(A(42))에서, 런타임 값이면 자식 생성자의 수정자 문법(A(_a))으로 전달할 수 있습니다. 부모가 여러 개면 선형화 순서(가장 기반 먼저)로 전달하세요. 부모에게 인자 없는 생성자가 있으면 생략할 수 있습니다. 생성자는 배포 시 선형화 순서로 한 번 실행됩니다.
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) {}
}추상 계약과 인터페이스
추상 계약
추상 계약은 본문 없는 함수가 하나 이상 있습니다(virtual로 선언, 구현 없음). 직접 배포할 수 없고 자식이 모든 추상 함수를 구현해야 합니다. 공유 상태 + 수정자 + 부분 구현을 원할 때 추상 계약을 사용하세요. 0.6.0 이전에는 본문 없는 함수가 있으면 'abstract' 키워드가 필수였습니다.
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
}
}인터페이스
인터페이스는 순수 추상 계약과 같습니다. 상태, 생성자, 구현된 함수가 없고 모든 함수가 external입니다. 알 수 없는 구현과 상호작용하기 위한 계약의 ABI를 정의합니다. 로직을 상속하지 않고 다른 계약을 호출할 때 인터페이스를 사용하세요. 'I' 접두사로 이름을 붙이세요(IERC20, IUniswapV2Pair). 인터페이스 함수에는 external view/payable 외의 수정자를 붙일 수 없습니다.
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 = 본문 없는 함수가 하나 이상 있어 배포할 수 없는 계약. virtual = 본문이 있지만 자식이 재정의할 수 있는 함수. 함수는 둘 다 될 수 있습니다(virtual + 본문 없음). 인터페이스는 암묵적으로 완전 추상이라 모든 함수가 virtual이고 본문이 없으며 external입니다. 공유 로직에는 abstract, 순수 ABI 정의에는 인터페이스를 사용하세요.
// 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
}인터페이스 모범 사례
인터페이스 모범 사례: 'I' 접두사, 최소한만 유지(호출자에게 필요한 것만), 모든 함수 external, 상태/생성자/구현 없음, 이벤트는 허용. 인터페이스 용도: (1) 소스가 없는 다른 계약 호출, (2) 표준 정의(IERC20, IERC721), (3) 구현을 상속하지 않아 바이트코드 축소. 인터페이스를 구현하면 계약이 표준을 충족해야 합니다.
// 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 예제(인터페이스)
IERC20은 ERC-20 대체 가능 토큰 표준을 정의합니다. 인터페이스는 6개 필수 함수(totalSupply, balanceOf, transfer, approve, allowance, transferFrom)와 선택적 메타데이터(name, symbol, decimals), 2개 이벤트를 선언합니다. 이 인터페이스를 구현한 계약은 ERC-20 토큰으로 취급될 수 있습니다. 내부 구현을 몰라도 모든 ERC-20과 상호작용할 때 이 인터페이스를 사용하세요.
// 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);
}
}라이브러리
라이브러리 기초
라이브러리는 계약과 비슷하지만 상태를 가질 수 없고 상속하거나 상속될 수 없습니다. 한 번 배포되어 DELEGATECALL(외부)이나 인라인(내부)으로 재사용됩니다. internal 라이브러리 함수는 호출 계약에 인라인되어 별도 배포가 없습니다. 재사용 함수(수학, 검증, 서식)를 묶는 데 라이브러리를 사용하세요. 'using SafeMath for uint256' 지시문을 쓰면 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'은 라이브러리 함수를 해당 타입에 붙여 Library.method(value) 대신 value.method()로 호출하게 합니다. 라이브러리 함수의 첫 매개변수가 타입과 일치해야 합니다. 0.8.13+에서는 파일 수준에서 'using {fn1, fn2} for Type;'도 가능합니다. 순전히 문법적 편의이며 컴파일러가 직접 호출로 다시 씁니다.
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
}내부 라이브러리
internal 라이브러리 함수는 컴파일 시 호출 계약의 바이트코드에 인라인됩니다. 런타임 DELEGATECALL, 라이브러리 배포, 호출 오버헤드가 없습니다. 따라서 호출이 사실상 무료입니다(연산 자체의 가스만 듦). 순수/view 도우미(수학, 문자열 변환)에 internal 라이브러리를 사용하세요. 호출자 바이트코드는 커지지만 호출 가스는 외부 라이브러리보다 낮습니다.
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.외부(배포) 라이브러리
external 라이브러리 함수는 별도 계약으로 배포되고 DELEGATECALL로 호출됩니다. 호출자의 문맥(스토리지, msg.sender)에서 실행됩니다. 많은 계약이 공유하는 유틸리티 코드에 유용합니다(전체 배포 가스 절약). 단점: 호출당 DELEGATECALL 오버헤드(약 1400 가스)와 컴파일 시 라이브러리를 배포하고 주소를 연결해야 합니다. 대부분의 라이브러리는 internal 함수를 쓰고 external은 드뭅니다.
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 예제(0.8.0 이전)
SafeMath는 0.8.0 이전의 대표적인 오버플로 검사 라이브러리였습니다. 0.8.0부터 산술 연산이 오버플로 시 자동 revert하므로 기본 수학에는 SafeMath가 불필요합니다. 여전히 유용한 경우: (1) 레거시 코드 읽기, (2) unchecked 연산을 명시적으로 감싸기, (3) '사후 조건 require' 패턴의 학습 예제. OpenZeppelin 버전은 여전히 널리 참조됩니다.
// 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;
}
}이더 전송
Payable과 msg.value
payable 함수는 msg.value(단위 wei)로 이더를 받습니다. 이더는 자동으로 계약 잔액에 추가되므로 사용자별 회계를 원하지 않으면 직접 추적할 필요가 없습니다. 정확한 금액이나 최소 금액 지불에는 msg.value를 검증하세요. 초과 이더는 항상 환불해 계약에 묶이지 않게 하세요. 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)는 이더를 보내고 실패 시 revert합니다. 고정 2300 가스 스티펜드를 전달해 과거에는 재진입을 막았지만 지금은 취약한 방식으로 여겨집니다(2019년 이스탄불 이후 가스 비용 변경). 최신 지침: 신뢰할 수 있는 주소(owner 등)로 보낼 때만 transfer를 사용하세요. 임의 수신자에는 명시적 재진입 가드와 함께 .call{value:}를 사용하세요. 2300 스티펜드는 정당한 receive/fallback 로직에 부족할 수 있습니다.
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)는 불리언을 반환합니다(성공 시 true, 실패 시 false). 자동으로 revert하지 않으므로 반환 값을 반드시 확인하고 실패 시 revert해야 합니다. transfer처럼 2300 가스만 전달합니다. send는 오류가 나기 쉽고(개발자가 반환 값 확인을 잊음) 최신 코드에서는 드뭅니다. 새 계약에는 .call{value:}를 권장합니다.
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(권장)
.call{value: x}(...)는 0.8.0 이후 이더 전송의 권장 방법입니다. 사용 가능한 모든 가스를 전달하므로(63/64 규칙 적용) 수신자가 복잡한 로직을 수행할 수 있습니다. (bool, bytes)를 반환하므로 불리언을 반드시 확인하고 실패 시 revert하세요. 모든 가스를 전달하므로 재진입에 취약합니다. 항상 nonReentrant 수정자와 함께 쓰거나 checks-effects-interactions를 따르세요. 임의 수신자에는 call, 신뢰 주소에만 transfer를 사용하세요.
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.
}잔액 확인
address.balance는 모든 주소(계약 자신은 address(this))의 wei 잔액을 반환합니다. view라 오프체인 호출은 무료입니다. 경고: 잔액은 selfdestruct(강제 이더)로 누구나 부풀릴 수 있으므로 정확한 잔액 동등 비교에 의존하지 말고 >=를 쓰거나 자체 회계 변수를 유지하세요. 입금 합계가 계약 잔액과 같은지 항상 불변 조건으로 교차 확인하세요.
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;
}
}가스 최적화
스토리지 vs 메모리
스토리지 읽기(SLOAD)는 접근당 콜드 약 2100 가스, 웜 100 가스입니다. 메모리 읽기(MLOAD)는 3 가스에 불과합니다. 함수가 상태 변수를 여러 번 읽으면(특히 루프에서) 먼저 메모리 변수에 캐시하세요. 첫 SLOAD는 비싸지만 이후 메모리 읽기는 거의 무료입니다. 가장 쉽고 효과 큰 최적화 중 하나입니다.
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.
}변수 패킹
Solidity는 연속된 상태 변수를 32바이트 스토리지 슬롯에 패킹합니다. 가스를 절약하려면 작은 타입(uint8, uint64, address)을 함께 묶어 같은 슬롯을 공유하게 하세요. 구조체 필드를 작은 것끼리 촘촘히 패킹되도록 재정렬하세요. 슬롯 하나를 절약하면 첫 접근 시 약 20k 가스가 절약됩니다. 참고: 매핑과 동적 배열 항목은 항상 새 슬롯을 시작해 패킹할 수 없습니다.
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 블록
unchecked { ... }는 블록 안의 오버플로/언더플로 검사를 비활성화해 가스를 절약합니다(연산당 약 50-80). 경계를 이미 검증한 경우에 안전합니다(예: require(a >= b) 후 a - b는 언더플로 불가). 고전적 안전 사례는 루프 카운터입니다(for 루프의 i++는 2^256을 넘지 않음). unchecked를 무분별하게 쓰지 마세요. 조용한 오버플로는 보안 위험입니다.
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).
}사용자 정의 오류 vs Require
사용자 정의 오류(0.8.4+)는 require(_, "msg")보다 저렴합니다. 메시지 문자열이 바이트코드에 저장되어 바이트당 가스가 들고 revert마다 다시 인코딩되기 때문입니다. 사용자 정의 오류는 4바이트 선택자와 ABI 인코딩 인자일 뿐입니다. 사소하지 않은 오류 메시지에서는 호출당 수천 가스를 절약하고 배포 바이트코드도 줄입니다. 새 코드에서는 항상 사용자 정의 오류를 권장합니다.
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);
}
}루프에서 상태 변수 캐시
루프 전에 배열 길이를 지역 변수에 캐시하세요(반복당 SLOAD 하나 절약). 배열이 작으면 한 번 메모리로 복사하세요(요소당 SLOAD 하나 후 루프에서는 저렴한 MLOAD). 누산기는 항상 지역(메모리) 변수여야 합니다. 스토리지 구조체 필드는 여러 번 쓰이면 구조체 전체를 메모리에 캐시하세요.
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;
}
}단락 평가와 루프 최적화
단락 평가: &&와 ||에서 저렴한 검사를 먼저 두세요. i++ 대신 ++i(접두사)를 사용하세요(임시 값이 없어 약간 저렴). 루프 카운터를 unchecked로 감싸세요(i는 현실적으로 2^256을 넘지 않음). 필요한 것을 찾으면 루프를 일찍 종료하세요. 루프 안에서 비싼 연산(외부 호출, 스토리지 쓰기)을 피하고 밖에서 배치 처리하세요.
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;
}
}시간 단위와 블록 속성
block.timestamp
block.timestamp(0.7.0 이전 별칭 'now')는 현재 블록의 Unix 타임스탬프(초)입니다. 채굴자/검증자가 설정하며 약 15초까지 조작될 수 있으므로 난수나 정밀한 타이밍에 절대 사용하지 마세요. 대략적인 기간(>=1분)과 순서에는 괜찮습니다. 흔한 용도: 타임락, 베스팅 일정, 마감 시각. 더 엄격한 보장이 필요하면 block.number를 사용하세요.
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는 현재 블록 높이입니다. blockhash(n)은 블록 n의 해시를 반환하지만 최근 256개 블록에만 유효하고(그보다 오래되면 0) 현재 블록에는 0을 반환합니다. block.number와 blockhash는 채굴자의 영향을 받을 수 있으므로 고위험 난수에 사용하지 마세요. 실제 난수에는 Chainlink VRF나 사용자 제공 엔트로피를 쓰는 커밋-리빌 방식을 사용하세요.
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.
}시간 단위(seconds/minutes/hours/days/weeks)
시간 단위 접미사(seconds, minutes, hours, days, weeks)는 uint256 초로 변환됩니다. 'years'는 윤년 모호성 때문에 0.5.0에서 제거되었습니다. 이더 단위(wei, gwei, ether)는 별개입니다: 1 ether = 10^18 wei, 1 gwei = 10^9 wei. 금액은 항상 wei로 저장하고 계산의 가독성을 위해 접미사를 사용하세요.
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;
}
}가스와 gasleft()
gasleft()는 호출 시점의 남은 가스를 반환합니다(폐기된 msg.gas 대체). 코드가 가스를 얼마나 소모하는지 측정하는 데 유용합니다. 63/64 규칙: 외부 호출은 남은 가스의 63/64를 전달하고 1/64를 예약해 호출자가 반환을 처리할 수 있게 합니다. 하드포크마다 opcode 비용이 바뀌므로 정확한 가스 값에 의존하지 마세요.
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");
}
}체인 ID와 네트워크 감지
block.chainid는 현재 체인 ID를 반환합니다. 재전송 공격 방어(EIP-155)와 EIP-712 타입 데이터 서명(도메인 구분자에 chainId 포함)에 필수입니다. 가스 효율을 위해 생성자에서 chainId를 immutable로 캐시하되, EIP-712에서는 계약이 새 체인으로 포크되면 다시 계산해야 할 수 있습니다. 권한을 서명하는 모든 해시에 chainId를 포함하세요.
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.
}가시성 수정자
Public
public 함수는 어디서나 호출할 수 있습니다. 외부(사용자나 다른 계약), 내부(계약 안), 파생 계약에서 모두 가능합니다. public 상태 변수는 getter 함수를 자동으로 얻습니다. public은 가장 허용적이지만 바이트코드가 늘어납니다(내부/외부 호출 규약을 모두 지원해야 함). public 함수를 내부에서 'this.f()'로 호출하면 비싼 외부 호출이 됩니다.