Understanding Smart Contracts
What is a Smart Contract
A smart contract is a program stored on the blockchain that executes automatically. Rules like "if condition A is met, execute B" are written in code, and when conditions are satisfied, it runs automatically without anyone's intervention.
Traditional contracts are enforced by intermediaries (lawyers, courts). Smart contracts enforce themselves through code. When contract conditions are met, the blockchain network automatically executes them, and no one can stop or change this.
Example: Crowdfunding Smart Contract
- Goal amount reached → Funds automatically sent to the project
- Deadline passed without reaching goal → Funds automatically returned to backers
- Code handles everything without intermediaries
DeFi and Smart Contracts
All DeFi services are implemented through smart contracts.
| Service | Smart Contract Role |
|---|---|
| DEX (Uniswap) | Token swap rules, liquidity pool management, fee distribution |
| Lending (Aave) | Collateral management, interest rate calculation, liquidation execution |
| Stablecoin (DAI) | Collateral deposit, token minting/burning, liquidation auctions |
| Yield Farming (Yearn) | Strategy execution, yield optimization, auto-compounding |
What loan officers do at banks is replaced by smart contract code. It operates 24/7, applies the same rules to everyone, and doesn't make mistakes.
Transactions and Gas
Transactions
A transaction is an action recorded on the blockchain. All state changes like token transfers, smart contract calls, and contract deployments are done through transactions.
Each transaction contains the following information:
- From Address: The wallet that initiated the transaction
- To Address: Target wallet or contract address
- Value: Native token being transferred (ETH, etc.)
- Data: Function and parameters when calling a contract
- Gas: Transaction execution fee
Gas
Gas is a unit that measures the computational cost required to execute a transaction. Complex smart contract calls require more gas than simple transfers.
| Operation | Approximate Gas Usage |
|---|---|
| ETH Transfer | 21,000 |
| ERC-20 Token Transfer | 65,000 |
| Uniswap Swap | 150,000~200,000 |
| Aave Deposit/Borrow | 200,000~400,000 |
| Complex DeFi Transaction | 500,000+ |
Gas Fee Calculation
Gas Fee = Gas Used x Gas Price
Gas price is expressed in Gwei (1 ETH = 1,000,000,000 Gwei).
Example: Uniswap swap, 200,000 gas, gas price 30 Gwei
- Gas fee = 200,000 x 30 Gwei = 6,000,000 Gwei = 0.006 ETH
- If ETH is $3,000, approximately $18
Gas Price Fluctuation
Gas prices fluctuate in real-time based on network congestion.
- Low traffic: 10~20 Gwei
- Normal: 30~50 Gwei
- Congested: 100~500 Gwei
- Extreme congestion (NFT mints, etc.): 1,000+ Gwei
You can check current gas prices at Etherscan Gas Tracker.
EIP-1559 and Fee Structure
Ethereum's current gas fee structure:
- Base Fee: Determined by the network. Gets burned
- Priority Fee (Tip): Set by the user. Paid to validators
In MetaMask, you can easily set "Slow", "Average", "Fast" options or manually input in advanced settings.
Approval (Approve)
Why Token Approval is Needed
To use ERC-20 tokens in a smart contract, you first need Approval. This is giving permission that "this contract can use X amount of my tokens."
Why is this needed? For security. To prevent any contract from arbitrarily taking user tokens, users must explicitly grant permission.
Approval Process
When swapping USDC to ETH on Uniswap:
- First Transaction (Approve): Approve the USDC contract to "allow Uniswap router to use my USDC"
- Second Transaction (Swap): Execute the actual swap. Uniswap takes the approved USDC and sends ETH
When using the same token on the same protocol again, it's already approved so you only need to swap.
Approval Amount
You can set the amount when approving:
- Exact amount: Approve only the amount needed for this transaction. Safest but requires approval each time
- Unlimited: Once approved, no need to approve again. Convenient but risky
Risks of Unlimited Approval: If the contract is hacked or maliciously designed, all approved tokens can be stolen. Millions of dollars were stolen in the 2022 Multichain hack due to unlimited approvals.
Managing Approvals
You can check and revoke existing approvals:
- Revoke.cash: Most popular. Multi-chain support
- Etherscan Token Approvals: Ethereum only
Regularly cleaning up old approvals is good for security. Especially revoke approvals for protocols you no longer use.
Interacting with Smart Contracts
Confirming Transactions in MetaMask
When you request an action on a DeFi site, a MetaMask popup appears. Items to verify:
- Site URL: Confirm it's not a phishing site
- To Address: The contract address you're interacting with
- Function Name: What function is being called (swap, deposit, etc.)
- Amount: Amount of tokens/ETH being transferred
- Estimated Gas Fee: Fee you'll pay
Never approve transactions you don't understand.
Read Functions vs Write Functions
Smart contract functions are of two types:
Read Functions (Read/View):
- Only query data
- Don't change blockchain state
- Free (no gas)
- Examples: Check balance, query interest rate
Write Functions:
- Change blockchain state
- Require gas
- Recorded as transactions
- Examples: Token transfer, swap, deposit
Verifying Contracts
Verified Contracts
If the contract code is public on Etherscan, there's a check mark in the "Contract" tab. This means the deployed bytecode matches the source code.
Unverified contracts are riskier because you can't check the code. Be especially cautious with new protocols or small projects.
What to Check
- Contract Verification: Is the code public?
- Audit Status: Has it been security audited by Trail of Bits, OpenZeppelin, etc.?
- Upgradeability: If it's a Proxy pattern, logic can change
- Admin Privileges: Who can control the contract?
Security Audits
A process where professional security firms review smart contract code to find vulnerabilities. Being audited doesn't guarantee 100% safety, but it's much safer than not being audited.
Major security audit firms:
- Trail of Bits
- OpenZeppelin
- Consensys Diligence
- ChainSecurity
- Certik
Audit reports are usually published in project documentation or GitHub.
Layer 2 and Gas Fee Savings
What is Layer 2
Due to high gas fees on Ethereum mainnet, using DeFi on Layer 2 (L2) has become popular. L2 inherits mainnet security while providing faster and cheaper transactions.
Major Layer 2s
| L2 | Type | Gas Fee (vs ETH) | Features |
|---|---|---|---|
| Arbitrum One | Optimistic Rollup | ~5~10% | Largest TVL, diverse DeFi |
| Optimism | Optimistic Rollup | ~5~10% | Synthetix, Velodrome |
| Base | Optimistic Rollup | ~5~10% | Operated by Coinbase |
| zkSync Era | ZK Rollup | ~5~10% | ZK technology leader |
| Polygon zkEVM | ZK Rollup | ~5~10% | Polygon ecosystem |
Getting Started with DeFi on L2
- Add L2 network to MetaMask (use Chainlist)
- Move assets via bridge (official bridge or Orbiter, etc.)
- Use DeFi on L2 (same UI as Uniswap, Aave, etc.)
On L2, gas fees are around $0.1~1, very affordable, allowing active DeFi use even with small amounts.
Common Mistakes and Prevention
Transaction Failure
Gas is consumed even when transactions fail. Common failure causes:
- Gas Limit set too low
- Slippage setting too low
- Another transaction already processed
- Contract conditions not met
Prevention: Set sufficient gas limit, appropriate slippage (0.5~1%)
Wrong Network
Trying to send from Ethereum to Arbitrum but sending on the wrong network. Even the same address on different networks can result in trapped assets.
Prevention: Check current network before sending. Test with small amounts first.
Wrong Address
Sending ETH directly to a contract address can result in permanent loss. Especially sending ETH to token contract addresses is unrecoverable.
Prevention: Double-check after copy/pasting addresses. Test with small amounts on first transfers.
Summary
Smart contracts are programs that execute automatically on the blockchain, powering all DeFi services. Gas fees are required for transaction execution and fluctuate based on network congestion. Using tokens in contracts requires Approval, but unlimited approvals carry risks, so manage them regularly. Using Layer 2 can significantly reduce gas fees. Always carefully verify all transactions before signing.
Next article: DeFi Ecosystem Map - Understanding Chains and Protocols