가스 비용 모델
가스가 발생하는 작업
가스 비용 모델은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Gas Exists
Every operation on the Ethereum Virtual Machine (EVM) costs gas. Gas is a unit that measures the computational work required to execute a transaction.
Gas exists to:
- Pay validators for the resources they spend
- Prevent infinite loops and denial-of-service attacks
- Price scarce on-chain resources fairly
The total fee you pay equals gasUsed * gasPrice, denominated in wei.
Gas, Gas Price, and Gas Limit
Three numbers matter for every transaction:
- gasUsed — how much computation actually happened
- gasPrice (or maxFeePerGas under EIP-1559) — how much you pay per unit
- gasLimit — the maximum gas you allow before the transaction reverts
If execution exceeds the gas limit, the transaction reverts with an out of gas error, but you still pay for the gas consumed.
// Fee calculation
// totalFee = gasUsed * effectiveGasPrice
// Example: 50000 gas * 20 gwei = 1,000,000 gwei = 0.001 ETHOpcode Costs
Each EVM opcode has a fixed gas cost defined in the Ethereum protocol. Cheap arithmetic costs very little, while storage and external calls cost a lot.
ADD,SUB— 3 gasMUL— 5 gasSLOAD(read storage) — 2100 gas cold, 100 warmSSTORE(write storage) — up to 22100 gas
Storage dominates the cost of most contracts.
The Cost of Storage
Persistent storage is the single most expensive resource on the EVM. Writing a storage slot from zero to non-zero costs 20000 gas; updating a non-zero slot costs 5000 gas.
Reading is cheaper than writing but still significant. This is why the golden rule of gas optimization is: touch storage as rarely as possible.
contract Counter {
uint256 public count; // each increment writes a storage slot
function increment() external {
count += 1; // 1 SLOAD + 1 SSTORE
}
}Memory vs Storage vs Calldata
The EVM has three data locations, each with a different cost profile:
- storage — persistent, most expensive
- memory — temporary per-call, cheap but grows quadratically
- calldata — read-only input data, cheapest for function arguments
Using calldata instead of memory for external function parameters avoids an unnecessary copy.
function sum(uint256[] calldata nums) external pure returns (uint256 total) {
for (uint256 i = 0; i < nums.length; i++) {
total += nums[i];
}
}Intrinsic Gas
Before any code runs, every transaction pays a base cost called intrinsic gas:
- 21000 gas for a base transaction
- 16 gas per non-zero calldata byte
- 4 gas per zero calldata byte
This means even an empty transfer costs 21000 gas, and larger calldata payloads make transactions more expensive before execution even begins.
Cold vs Warm Access
Since EIP-2929, the first access to an account or storage slot in a transaction is cold and expensive; subsequent accesses are warm and cheap.
- Cold
SLOAD: 2100 gas - Warm
SLOAD: 100 gas - Cold account access: 2600 gas
Caching a storage value in a local variable converts repeated cold reads into a single read plus cheap memory access.
uint256 cached = count; // one SLOAD
for (uint256 i = 0; i < cached; i++) {
// use cached instead of re-reading count
}Refunds
The EVM grants a partial gas refund when you clear storage, setting a non-zero slot back to zero (via SSTORE or SELFDESTRUCT historically).
Refunds are capped at one fifth of the transaction gas used (EIP-3529). Patterns like deleting array elements or zeroing balances can recover some gas, but you should never rely on refunds as a primary optimization.
function clear(uint256 key) external {
delete data[key]; // zeroing a slot triggers a refund
}EIP-1559 Fee Market
EIP-1559 split the gas price into two parts:
- base fee — burned, adjusts automatically per block based on demand
- priority fee (tip) — paid to the validator
Users set maxFeePerGas and maxPriorityFeePerGas. The effective price never exceeds the max, and unused amounts are refunded. This makes fees more predictable.
Deployment vs Runtime Gas
Contracts have two distinct gas profiles:
- Deployment gas — paid once, proportional to bytecode size (200 gas per byte stored)
- Runtime gas — paid on every call to the deployed contract
Sometimes you trade a larger, more expensive deployment for cheaper runtime, or vice versa. Optimize for the dimension that matters most to your use case.
The Optimization Mindset
Effective gas optimization follows a hierarchy:
- Avoid storage writes (biggest wins)
- Minimize cold accesses by caching
- Use
calldataovermemory - Reduce calldata size
- Micro-optimize opcodes last
Always measure before and after. Premature micro-optimization often hurts readability for negligible gain.
Quick Check
Which operation is typically the most expensive in an EVM contract?
Recap
You now understand the EVM gas cost model:
- Fees equal
gasUsed * gasPrice, bounded by a gas limit - Storage writes dominate cost; arithmetic is cheap
- Cold accesses cost more than warm ones
- Intrinsic gas (21000 + calldata bytes) is paid before execution
- EIP-1559 splits fees into a burned base fee and a validator tip
Next we apply this knowledge to optimize contract storage layout.
AI 튜터와 함께 Web3 & DApp Development Fundamentals을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 29
- 레슨
- 105
자주 묻는 질문
“가스 비용 모델” 강의는 무료인가요?
네 — “가스 비용 모델” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“가스 비용 모델”에서 뭘 배우나요?
가스가 발생하는 작업 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“가스 비용 모델” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 가스 비용 모델
- 스토리지 최적화
- 반복문과 Calldata 기법
- 가스 측정하기