What Are Smart Contracts and How Do Token Swaps Happen On-Chain?
Smart contracts are self-executing programs stored on a blockchain that automatically enforce agreements when predefined conditions are met. They’re the foundation of DeFi, enabling trustless token swaps, lending, and more.
What is a Smart Contract?
A smart contract is code deployed to a blockchain that:
- Lives at an address - Just like a wallet, but contains code instead of just a balance
- Executes automatically - Runs when called by a transaction
- Is immutable - Once deployed, the code cannot be changed (unless upgradeable)
- Is transparent - Anyone can read the code and verify behavior
Simple Example: Token Swap Contract Logic
function swap(tokenIn, tokenOut, amountIn):
1. Transfer tokenIn from user to contract
2. Calculate amountOut based on pool reserves
3. Transfer amountOut from contract to user
4. Update pool reserves
5. Emit Swap event
How a Token Swap Works On-Chain
When you swap tokens on a DEX, here’s what happens at the blockchain level:
Step 1: Approval (if first time)
Before a smart contract can move your tokens, you must approve it:
Transaction 1: Approve
├─ From: Your wallet (0xYou...)
├─ To: Token contract (0xToken...)
├─ Function: approve(spender, amount)
├─ Parameters:
│ ├─ spender: DEX router address
│ └─ amount: How many tokens it can move
└─ Gas: ~46,000 units
Step 2: The Swap Transaction
Transaction 2: Swap
├─ From: Your wallet (0xYou...)
├─ To: DEX Router contract
├─ Function: swapExactTokensForTokens(...)
├─ Parameters:
│ ├─ amountIn: 1000 USDC
│ ├─ amountOutMin: 0.45 ETH (slippage protection)
│ ├─ path: [USDC, ETH]
│ └─ deadline: Block timestamp + 20 minutes
└─ Internal calls:
├─ 1. USDC.transferFrom(you, pool, 1000)
├─ 2. Pool calculates output: 0.47 ETH
├─ 3. ETH.transfer(you, 0.47)
└─ 4. Emit Swap(you, 1000 USDC, 0.47 ETH)
The Role of Router Contracts
DEX routers are smart contracts that:
- Find optimal paths - Route through multiple pools if needed
- Handle approvals - Interface with token contracts
- Enforce slippage - Revert if output is below minimum
- Set deadlines - Prevent stale transactions from executing
Multi-Hop Swaps
Sometimes the best price requires multiple swaps:
PEPE → ETH (direct route): 1000 PEPE = 0.001 ETH
PEPE → USDC → ETH (multi-hop): 1000 PEPE = 0.00105 ETH
The router automatically finds and executes the better path.
Key Smart Contract Patterns in DeFi
1. Liquidity Pool Contracts
Hold reserves of two tokens and execute swaps:
- Uniswap V2 Pairs - x * y = k constant product
- Uniswap V3 Pools - Concentrated liquidity positions
- Curve Pools - StableSwap invariant for pegged assets
2. Factory Contracts
Create new pool contracts permissionlessly:
Factory.createPair(tokenA, tokenB) → New Pool at 0xNewPool...
3. Aggregator Contracts
Split orders across multiple DEXs:
1inch.swap() internally calls:
├─ Uniswap: 60% of order
├─ SushiSwap: 30% of order
└─ Curve: 10% of order
Reading Smart Contract Events
Every swap emits events that indexers and explorers can read:
Swap Event:
├─ sender: Router contract
├─ amount0In: 1000000000 (1000 USDC, 6 decimals)
├─ amount1In: 0
├─ amount0Out: 0
├─ amount1Out: 470000000000000000 (0.47 ETH, 18 decimals)
└─ to: Your wallet address
Block explorers like Etherscan, Basescan, and Arbiscan let you view these events for any transaction.
See It on Ramaris
Ramaris indexes these swap events to build trade charts automatically. When a tracked wallet buys and later sells a token, the platform pairs the swaps and generates a candlestick chart showing entry price, exit price, and trade outcome. View these on any wallet’s Activity page and share them as images or links.
Security Considerations
Approval Risks
- Unlimited approvals - Some dApps request max approval; revoke unused ones
- Malicious contracts - Only approve contracts you trust
- Tools: Revoke.cash, Etherscan Token Approvals
Transaction Risks
- Front-running - Bots see your pending transaction and trade first
- Sandwich attacks - Bots buy before and sell after your trade
- Protection: Use private mempools (Flashbots), MEV-protected DEXs (CowSwap)
Contract Risks
- Rug pulls - Malicious token contracts that prevent selling
- Proxy upgrades - Upgradeable contracts can change behavior
- Verification: Check if contract is verified on block explorer
Tools for Exploring Smart Contracts
- Etherscan/Basescan - Read contract code, view transactions
- Tenderly - Simulate transactions before executing
- Dedaub - Decompile unverified contracts
- DeFiLlama - Track protocol TVL and safety scores