Transaction Fee
Transaction fee = Gas units * Gas price
Core Concepts
- Gas units: unit of computation for executing an operation.
- Gas price: how much ETH you pay for every gas unit, it is composed of base fee and priority fee (tip).
- Gas limit: the maximum gas you allow for one transaction.
Important Mechanism
- Gas refund: unused gas will be refunded to sender after the transaction finish.
-
Out of Gas: if
gasUsed > gasLimit
, transaction will fail and rollback all state changes, but the gas already used will not be refunded. - Batching: better to split heavy computation into multiple smaller transactions to avoid exceeding gas limit.
// ❌ Bad:
// function doMassiveLoop() public {
// for (uint i = 0; i < 1000000; i++) {
// // ... do work
// }
// }
// ✅ Good: batches
uint public start = 0;
uint public constant INCREMENT = 100;
function doWorkInBatches() public {
uint end = start + INCREMENT;
for (uint i = start; i < end; i++) {
// ... only do small part of work
}
start = end; // update next starting index
}
Top comments (0)