Comparing curve with optimism
curve
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Curve Finance
Curve is the dominant AMM for pegged-asset swaps (stablecoins, wrapped tokens, LSTs). Its StableSwap invariant concentrates liquidity around peg, delivering 10-100x lower slippage than constant-product AMMs for like-kind assets. CryptoSwap (Tricrypto) extends this to volatile pairs. The protocol also issues crvUSD, a stablecoin backed by LLAMMA — a soft-liquidation mechanism that gradually converts collateral instead of instant liquidation. CRV emissions are directed to liquidity gauges via vote-escrowed CRV (veCRV).
All Curve pool contracts are written in Vyper. ABI encoding is identical to Solidity — viem works without modification.
What You Probably Got Wrong
Curve is one of the most commonly mis-integrated protocols. Each pool type has different interfaces, and token ordering is deployment-specific.
- Curve pools have DIFFERENT ABIs per pool type — StableSwap (2-pool, 3-pool), CryptoSwap, Tricrypto, Meta pools, and Factory pools all have different function signatures. There is NO universal pool ABI. Always read the specific pool's ABI from Etherscan or the Curve docs.
- Token indices are pool-specific and NOT sorted — The order depends on deployment, not address sorting. Always call
coins(i)to verify which token is at which index. Getting this wrong swaps the wrong token. exchange()uses token indices, not addresses — You passi(sell token index) andj(buy token index), not token addresses. Passing the wrong index silently swaps the wrong token pair.get_dy()returns the estimated output BEFORE fees — The actual received amount is slightly less. Useget_dy()for quoting but apply slippage tolerance on top.add_liquidity()amounts array length varies per pool — 2 for 2-pool, 3 for 3-pool, 4 for 4-pool. Passing the wrong array length causes a revert with no useful error message.exchange()vsexchange_underlying()— Plain pools useexchange(). Meta pools useexchange_underlying()to swap between the meta-asset and the underlying basepool tokens. Calling the wrong function reverts.- crvUSD uses LLAMMA (soft liquidation), NOT traditional liquidation — Positions are gradually converted between collateral and crvUSD as price moves through bands. There is no instant liquidation threshold. Health approaching 0 means bands are fully converted.
- Gauge voting requires veCRV (vote-escrowed CRV) — Lock CRV for 1-4 years to get voting power. Voting power decays linearly. You cannot transfer or sell veCRV.
remove_liquidity_one_coin()has high slippage for large withdrawals from imbalanced pools — The StableSwap invariant penalizes imbalanced withdrawals. Always simulate first.- Virtual price only goes up (monotonic) —
get_virtual_price()returns the LP token value in underlying. It increases from fees and never decreases. Useful for pricing LP positions but NOT for detecting exploits (it was manipulated in some reentrancy attacks on Vyper <0.3.1 pools).
Quick Start
Installation
npm install viem
Client Setup
import { createPublicClient, createWalletClient, http, type Address } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
const publicClient = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
const walletClient = createWalletClient({
account,
chain: mainnet,
transport: http(process.env.RPC_URL),
});
Swap USDC to USDT on 3pool
const THREE_POOL = "0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7" as const;
// 3pool indices: 0 = DAI, 1 = USDC, 2 = USDT
// Always verify with coins(i) before swapping
const threePoolAbi = [
{
name: "exchange",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "i", type: "int128" },
{ name: "j", type: "int128" },
{ name: "dx", type: "uint256" },
{ name: "min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "get_dy",
type: "function",
stateMutability: "view",
inputs: [
{ name: "i", type: "int128" },
{ name: "j", type: "int128" },
{ name: "dx", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "coins",
type: "function",
stateMutability: "view",
inputs: [{ name: "i", type: "uint256" }],
outputs: [{ name: "", type: "address" }],
},
] as const;
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" as const;
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7" as const;
const amountIn = 10_000_000000n; // 10,000 USDC (6 decimals)
// Verify token indices
const coin1 = await publicClient.readContract({
address: THREE_POOL,
abi: threePoolAbi,
functionName: "coins",
args: [1n],
});
if (coin1.toLowerCase() !== USDC.toLowerCase()) {
throw new Error(`Expected USDC at index 1, got ${coin1}`);
}
// Quote expected output
const expectedOut = await publicClient.readContract({
address: THREE_POOL,
abi: threePoolAbi,
functionName: "get_dy",
args: [1n, 2n, amountIn], // i=1 (USDC) -> j=2 (USDT)
});
// 0.1% slippage tolerance (stableswap pools have tight spreads)
const minDy = (expectedOut * 999n) / 1000n;
// Approve 3pool to spend USDC
const erc20Abi = [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const;
const { request: approveRequest } = await publicClient.simulateContract({
address: USDC,
abi: erc20Abi,
functionName: "approve",
args: [THREE_POOL, amountIn],
account: account.address,
});
const approveHash = await walletClient.writeContract(approveRequest);
await publicClient.waitForTransactionReceipt({ hash: approveHash });
// Execute swap
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: threePoolAbi,
functionName: "exchange",
args: [1n, 2n, amountIn, minDy],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Swap reverted");
Pool Types
StableSwap Pools (Pegged Assets)
The original Curve pool type. Optimized for assets that trade near 1:1 (stablecoins, wrapped tokens). Uses the StableSwap invariant which blends constant-sum and constant-product formulas, controlled by the amplification parameter A.
| Pool | Address | Coins | Indices |
|---|---|---|---|
| 3pool | 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7 | DAI, USDC, USDT | 0, 1, 2 |
| stETH/ETH | 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022 | ETH, stETH | 0, 1 |
| frxETH/ETH | 0xa1F8A6807c402E4A15ef4EBa36528A3FED24E577 | ETH, frxETH | 0, 1 |
Key parameters:
- A (amplification) — Higher A means tighter peg. 3pool uses A=2000. Ranges from 1 (constant product) to ~5000.
- Fee — Typically 0.01%-0.04% for stableswap pools. Read via
fee()(returns value in 1e10 precision, so4000000= 0.04%).
CryptoSwap Pools (Volatile Pairs)
Two-token pools for non-pegged assets using the CryptoSwap invariant. Internally re-pegs around the current price, providing concentrated liquidity that auto-rebalances.
| Pool | Address | Coins |
|---|---|---|
| tricrypto2 | 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46 | USDT, WBTC, WETH |
Meta Pools
Pools that pair a single token against an existing basepool's LP token. For example, FRAX/3CRV pairs FRAX against the 3pool LP token, giving FRAX access to DAI/USDC/USDT liquidity.
// Meta pool: exchange_underlying() swaps between the meta-asset
// and any token in the basepool
const metaPoolAbi = [
{
name: "exchange_underlying",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "i", type: "int128" },
{ name: "j", type: "int128" },
{ name: "dx", type: "uint256" },
{ name: "min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// LUSD/3CRV meta pool
// Underlying indices: 0 = LUSD, 1 = DAI, 2 = USDC, 3 = USDT
// exchange_underlying(0, 2, amount, minOut) swaps LUSD -> USDC
Factory Pools
User-deployed pools created through the Curve Factory. They follow the same interface as their pool type (StableSwap or CryptoSwap) but are created permissionlessly.
const CURVE_FACTORY = "0xB9fC157394Af804a3578134A6585C0dc9cc990d4" as const;
const factoryAbi = [
{
name: "pool_count",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "pool_list",
type: "function",
stateMutability: "view",
inputs: [{ name: "i", type: "uint256" }],
outputs: [{ name: "", type: "address" }],
},
] as const;
const poolCount = await publicClient.readContract({
address: CURVE_FACTORY,
abi: factoryAbi,
functionName: "pool_count",
});
Swapping
Basic Exchange (StableSwap)
All StableSwap pools use exchange(i, j, dx, min_dy) where i and j are token indices.
// Older pools (like 3pool) use int128 for indices
const stableSwapExchangeAbi = [
{
name: "exchange",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "i", type: "int128" },
{ name: "j", type: "int128" },
{ name: "dx", type: "uint256" },
{ name: "min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Newer factory pools may use uint256 for indices
const factoryExchangeAbi = [
{
name: "exchange",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "i", type: "uint256" },
{ name: "j", type: "uint256" },
{ name: "dx", type: "uint256" },
{ name: "min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
Exchange with ETH
ETH pools (stETH/ETH, frxETH/ETH) accept native ETH via msg.value. Pass ETH as value, not as an ERC-20 approval.
const STETH_POOL = "0xDC24316b9AE028F1497c275EB9192a3Ea0f67022" as const;
// stETH/ETH pool: 0 = ETH, 1 = stETH
const ethPoolExchangeAbi = [
{
name: "exchange",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "i", type: "int128" },
{ name: "j", type: "int128" },
{ name: "dx", type: "uint256" },
{ name: "min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const ethAmount = 1_000_000_000_000_000_000n; // 1 ETH
const expectedSteth = await publicClient.readContract({
address: STETH_POOL,
abi: threePoolAbi, // get_dy has same signature
functionName: "get_dy",
args: [0n, 1n, ethAmount],
});
const minSteth = (expectedSteth * 999n) / 1000n;
const { request } = await publicClient.simulateContract({
address: STETH_POOL,
abi: ethPoolExchangeAbi,
functionName: "exchange",
args: [0n, 1n, ethAmount, minSteth],
value: ethAmount, // send ETH with the call
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Swap reverted");
Curve Router
For optimal routing across multiple pools, use the Curve Router. It finds the best path automatically.
const CURVE_ROUTER = "0xF0d4c12A5768D806021F80a262B4d39d26C58b8D" as const;
const routerAbi = [
{
name: "exchange",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "_route", type: "address[11]" },
{ name: "_swap_params", type: "uint256[5][5]" },
{ name: "_amount", type: "uint256" },
{ name: "_min_dy", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "get_dy",
type: "function",
stateMutability: "view",
inputs: [
{ name: "_route", type: "address[11]" },
{ name: "_swap_params", type: "uint256[5][5]" },
{ name: "_amount", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Route encoding: alternating [token, pool, token, pool, ..., token]
// padded with zero addresses to length 11
// swap_params[i] = [i, j, swap_type, pool_type, n_coins]
// swap_type: 1 = exchange, 2 = exchange_underlying, 3 = exchange on underlying
// pool_type: 1 = stableswap, 2 = cryptoswap, 3 = tricrypto
Liquidity
Add Liquidity (Balanced)
Provide all tokens proportionally to minimize slippage.
const addLiquidityAbi = [
{
name: "add_liquidity",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "amounts", type: "uint256[3]" },
{ name: "min_mint_amount", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "calc_token_amount",
type: "function",
stateMutability: "view",
inputs: [
{ name: "amounts", type: "uint256[3]" },
{ name: "is_deposit", type: "bool" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Deposit 1000 of each stablecoin into 3pool
const amounts: readonly [bigint, bigint, bigint] = [
1000_000000000000000000n, // 1000 DAI (18 decimals)
1000_000000n, // 1000 USDC (6 decimals)
1000_000000n, // 1000 USDT (6 decimals)
];
// Estimate LP tokens received
const expectedLp = await publicClient.readContract({
address: THREE_POOL,
abi: addLiquidityAbi,
functionName: "calc_token_amount",
args: [amounts, true],
});
// 0.5% slippage on LP token mint
const minMintAmount = (expectedLp * 995n) / 1000n;
// Approve all three tokens to the pool
// (omitted for brevity — same pattern as swap approval)
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: addLiquidityAbi,
functionName: "add_liquidity",
args: [amounts, minMintAmount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Add liquidity reverted");
Add Liquidity (Single-Sided)
Deposit only one token. The pool rebalances internally, charging a small imbalance fee.
// Deposit 5000 USDC only into 3pool
const singleSidedAmounts: readonly [bigint, bigint, bigint] = [
0n, // 0 DAI
5000_000000n, // 5000 USDC
0n, // 0 USDT
];
const expectedLp = await publicClient.readContract({
address: THREE_POOL,
abi: addLiquidityAbi,
functionName: "calc_token_amount",
args: [singleSidedAmounts, true],
});
// Wider slippage for single-sided (imbalance fee applies)
const minMintAmount = (expectedLp * 990n) / 1000n;
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: addLiquidityAbi,
functionName: "add_liquidity",
args: [singleSidedAmounts, minMintAmount],
account: account.address,
});
Remove Liquidity (Proportional)
Withdraw all tokens proportionally — no slippage from imbalance.
const removeLiquidityAbi = [
{
name: "remove_liquidity",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "_amount", type: "uint256" },
{ name: "min_amounts", type: "uint256[3]" },
],
outputs: [{ name: "", type: "uint256[3]" }],
},
] as const;
const lpAmount = 3000_000000000000000000n; // 3000 LP tokens
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: removeLiquidityAbi,
functionName: "remove_liquidity",
args: [lpAmount, [0n, 0n, 0n]], // SET MIN AMOUNTS IN PRODUCTION
account: account.address,
});
Remove Liquidity (Single Coin)
Withdraw everything as a single token. Higher slippage for large amounts or imbalanced pools.
const removeOneCoinAbi = [
{
name: "remove_liquidity_one_coin",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "_token_amount", type: "uint256" },
{ name: "i", type: "int128" },
{ name: "_min_amount", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "calc_withdraw_one_coin",
type: "function",
stateMutability: "view",
inputs: [
{ name: "_token_amount", type: "uint256" },
{ name: "i", type: "int128" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const lpToWithdraw = 1000_000000000000000000n; // 1000 LP tokens
// Estimate how much USDC we get
const expectedUsdc = await publicClient.readContract({
address: THREE_POOL,
abi: removeOneCoinAbi,
functionName: "calc_withdraw_one_coin",
args: [lpToWithdraw, 1n], // index 1 = USDC
});
const minUsdc = (expectedUsdc * 995n) / 1000n;
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: removeOneCoinAbi,
functionName: "remove_liquidity_one_coin",
args: [lpToWithdraw, 1n, minUsdc],
account: account.address,
});
Remove Liquidity (Imbalanced)
Withdraw specific amounts of each token.
const removeImbalanceAbi = [
{
name: "remove_liquidity_imbalance",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "amounts", type: "uint256[3]" },
{ name: "max_burn_amount", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Withdraw exactly 500 DAI and 500 USDC, no USDT
const withdrawAmounts: readonly [bigint, bigint, bigint] = [
500_000000000000000000n, // 500 DAI
500_000000n, // 500 USDC
0n, // 0 USDT
];
// Estimate LP tokens burned
const estimatedBurn = await publicClient.readContract({
address: THREE_POOL,
abi: addLiquidityAbi,
functionName: "calc_token_amount",
args: [withdrawAmounts, false], // false = withdrawal
});
// Allow 1% more LP burn than estimated
const maxBurnAmount = (estimatedBurn * 1010n) / 1000n;
const { request } = await publicClient.simulateContract({
address: THREE_POOL,
abi: removeImbalanceAbi,
functionName: "remove_liquidity_imbalance",
args: [withdrawAmounts, maxBurnAmount],
account: account.address,
});
crvUSD (LLAMMA)
crvUSD is Curve's stablecoin. Loans are backed by collateral deposited into LLAMMA (Lending-Liquidating AMM Algorithm). Instead of instant liquidation at a threshold, LLAMMA gradually converts collateral to crvUSD as the collateral price drops through user-defined bands. If the price recovers, it converts back.
Create a crvUSD Loan
// crvUSD Controller for WETH collateral
const CRVUSD_WETH_CONTROLLER = "0xA920De414eA4Ab66b97dA1bFE9e6EcA7d4219635" as const;
const controllerAbi = [
{
name: "create_loan",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "collateral", type: "uint256" },
{ name: "debt", type: "uint256" },
{ name: "N", type: "uint256" },
],
outputs: [],
},
{
name: "max_borrowable",
type: "function",
stateMutability: "view",
inputs: [
{ name: "collateral", type: "uint256" },
{ name: "N", type: "uint256" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "health",
type: "function",
stateMutability: "view",
inputs: [
{ name: "user", type: "address" },
],
outputs: [{ name: "", type: "int256" }],
},
{
name: "user_state",
type: "function",
stateMutability: "view",
inputs: [
{ name: "user", type: "address" },
],
outputs: [
{ name: "collateral", type: "uint256" },
{ name: "stablecoin", type: "uint256" },
{ name: "debt", type: "uint256" },
{ name: "N", type: "uint256" },
],
},
] as const;
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" as const;
const collateralAmount = 10_000000000000000000n; // 10 WETH
// N = number of bands (4-50). More bands = wider liquidation range = safer but lower LTV
const numBands = 10n;
// Check max borrowable amount
const maxDebt = await publicClient.readContract({
address: CRVUSD_WETH_CONTROLLER,
abi: controllerAbi,
functionName: "max_borrowable",
args: [collateralAmount, numBands],
});
// Borrow 80% of max for safety margin
const debtAmount = (maxDebt * 80n) / 100n;
// Approve WETH to controller
const { request: approveReq } = await publicClient.simulateContract({
address: WETH,
abi: erc20Abi,
functionName: "approve",
args: [CRVUSD_WETH_CONTROLLER, collateralAmount],
account: account.address,
});
await walletClient.writeContract(approveReq);
// Create loan
const { request } = await publicClient.simulateContract({
address: CRVUSD_WETH_CONTROLLER,
abi: controllerAbi,
functionName: "create_loan",
args: [collateralAmount, debtAmount, numBands],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Loan creation reverted");
Monitor Loan Health
// Health > 0 means position is safe
// Health approaching 0 means bands are being converted (soft liquidation)
// Health < 0 means position can be hard-liquidated
const health = await publicClient.readContract({
address: CRVUSD_WETH_CONTROLLER,
abi: controllerAbi,
functionName: "health",
args: [account.address],
});
// Health is returned in 1e18 precision
// health = 100e18 means 100% above liquidation
const healthPercent = Number(health) / 1e18;
if (healthPercent < 10) {
console.warn(`Low health: ${healthPercent.toFixed(2)}% — consider repaying or adding collateral`);
}
// Read full user state
const [collateral, stablecoin, debt, bands] = await publicClient.readContract({
address: CRVUSD_WETH_CONTROLLER,
abi: controllerAbi,
functionName: "user_state",
args: [account.address],
});
Repay crvUSD Loan
const repayAbi = [
{
name: "repay",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "_d_debt", type: "uint256" },
],
outputs: [],
},
] as const;
const CRVUSD = "0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E" as const;
const repayAmount = 5000_000000000000000000n; // repay 5000 crvUSD
// Approve crvUSD to controller
const { request: approveReq } = await publicClient.simulateContract({
address: CRVUSD,
abi: erc20Abi,
functionName: "approve",
args: [CRVUSD_WETH_CONTROLLER, repayAmount],
account: account.address,
});
await walletClient.writeContract(approveReq);
const { request } = await publicClient.simulateContract({
address: CRVUSD_WETH_CONTROLLER,
abi: repayAbi,
functionName: "repay",
args: [repayAmount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Repay reverted");
Gauge System
Curve directs CRV emissions to liquidity providers via gauges. Deposit your LP tokens into a gauge to earn CRV rewards. Boost your rewards up to 2.5x by holding veCRV.
Deposit LP Tokens into Gauge
// 3pool gauge
const THREE_POOL_GAUGE = "0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A" as const;
const THREE_POOL_LP = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490" as const;
const gaugeAbi = [
{
name: "deposit",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "_value", type: "uint256" }],
outputs: [],
},
{
name: "withdraw",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "_value", type: "uint256" }],
outputs: [],
},
{
name: "claimable_tokens",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "addr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const lpAmount = 1000_000000000000000000n; // 1000 LP tokens
// Approve gauge to spend LP tokens
const { request: approveReq } = await publicClient.simulateContract({
address: THREE_POOL_LP,
abi: erc20Abi,
functionName: "approve",
args: [THREE_POOL_GAUGE, lpAmount],
account: account.address,
});
await walletClient.writeContract(approveReq);
// Deposit into gauge
const { request } = await publicClient.simulateContract({
address: THREE_POOL_GAUGE,
abi: gaugeAbi,
functionName: "deposit",
args: [lpAmount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Gauge deposit reverted");
Claim CRV Rewards
const MINTER = "0xd061D61a4d941c39E5453435B6345Dc261C2fcE0" as const;
const minterAbi = [
{
name: "mint",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "gauge_addr", type: "address" }],
outputs: [],
},
] as const;
// Check claimable amount
const claimable = await publicClient.simulateContract({
address: THREE_POOL_GAUGE,
abi: gaugeAbi,
functionName: "claimable_tokens",
args: [account.address],
});
// Mint (claim) CRV rewards
const { request } = await publicClient.simulateContract({
address: MINTER,
abi: minterAbi,
functionName: "mint",
args: [THREE_POOL_GAUGE],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("CRV claim reverted");
Gauge Voting
Lock CRV for veCRV
Lock CRV tokens to receive vote-escrowed CRV (veCRV). Longer lock = more voting power. Lock duration: 1 week to 4 years. Voting power decays linearly toward the unlock date.
const CRV = "0xD533a949740bb3306d119CC777fa900bA034cd52" as const;
const VECRV = "0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2" as const;
const veCrvAbi = [
{
name: "create_lock",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "_value", type: "uint256" },
{ name: "_unlock_time", type: "uint256" },
],
outputs: [],
},
{
name: "increase_amount",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "_value", type: "uint256" }],
outputs: [],
},
{
name: "increase_unlock_time",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "_unlock_time", type: "uint256" }],
outputs: [],
},
{
name: "withdraw",
type: "function",
stateMutability: "nonpayable",
inputs: [],
outputs: [],
},
] as const;
const lockAmount = 10000_000000000000000000n; // 10,000 CRV
// Lock for 4 years (max voting power)
// unlock_time must be rounded down to the nearest week (Thursday 00:00 UTC)
const WEEK = 7n * 24n * 60n * 60n;
const FOUR_YEARS = 4n * 365n * 24n * 60n * 60n;
const now = BigInt(Math.floor(Date.now() / 1000));
const unlockTime = ((now + FOUR_YEARS) / WEEK) * WEEK;
// Approve CRV to veCRV
const { request: approveReq } = await publicClient.simulateContract({
address: CRV,
abi: erc20Abi,
functionName: "approve",
args: [VECRV, lockAmount],
account: account.address,
});
await walletClient.writeContract(approveReq);
// Create lock
const { request } = await publicClient.simulateContract({
address: VECRV,
abi: veCrvAbi,
functionName: "create_lock",
args: [lockAmount, unlockTime],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("veCRV lock reverted");
Vote on Gauge Weights
Direct CRV emissions to specific gauges. Votes persist until changed. Each veCRV holder gets 10,000 vote points (100%) to allocate across gauges.
const GAUGE_CONTROLLER = "0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB" as const;
const gaugeControllerAbi = [
{
name: "vote_for_gauge_weights",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "_gauge_addr", type: "address" },
{ name: "_user_weight", type: "uint256" },
],
outputs: [],
},
{
name: "gauge_relative_weight",
type: "function",
stateMutability: "view",
inputs: [{ name: "addr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "vote_user_power",
type: "function",
stateMutability: "view",
inputs: [{ name: "user", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Allocate 50% of voting power to 3pool gauge
// Weight is in basis points: 5000 = 50%
const { request } = await publicClient.simulateContract({
address: GAUGE_CONTROLLER,
abi: gaugeControllerAbi,
functionName: "vote_for_gauge_weights",
args: [THREE_POOL_GAUGE, 5000n],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Gauge vote reverted");
Check Voting Power Usage
// Returns total weight used out of 10000 (100%)
const usedPower = await publicClient.readContract({
address: GAUGE_CONTROLLER,
abi: gaugeControllerAbi,
functionName: "vote_user_power",
args: [account.address],
});
const remainingBps = 10000n - usedPower;
Pool Discovery
MetaRegistry
The MetaRegistry aggregates all pool registries (main, factory, crypto factory) into a single interface.
const META_REGISTRY = "0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC" as const;
const metaRegistryAbi = [
{
name: "find_pool_for_coins",
type: "function",
stateMutability: "view",
inputs: [
{ name: "_from", type: "address" },
{ name: "_to", type: "address" },
],
outputs: [{ name: "", type: "address" }],
},
{
name: "find_pools_for_coins",
type: "function",
stateMutability: "view",
inputs: [
{ name: "_from", type: "address" },
{ name: "_to", type: "address" },
],
outputs: [{ name: "", type: "address[]" }],
},
{
name: "get_coins",
type: "function",
stateMutability: "view",
inputs: [{ name: "_pool", type: "address" }],
outputs: [{ name: "", type: "address[8]" }],
},
{
name: "get_balances",
type: "function",
stateMutability: "view",
inputs: [{ name: "_pool", type: "address" }],
outputs: [{ name: "", type: "uint256[8]" }],
},
] as const;
// Find the best pool for USDC -> USDT
const pool = await publicClient.readContract({
address: META_REGISTRY,
abi: metaRegistryAbi,
functionName: "find_pool_for_coins",
args: [USDC, USDT],
});
// Find ALL pools for a pair
const pools = await publicClient.readContract({
address: META_REGISTRY,
abi: metaRegistryAbi,
functionName: "find_pools_for_coins",
args: [USDC, USDT],
});
Reading Pool State
Virtual Price
Virtual price represents the LP token value in terms of the underlying asset. It only increases over time from trading fees.
const poolStateAbi = [
{
name: "get_virtual_price",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "balances",
type: "function",
stateMutability: "view",
inputs: [{ name: "i", type: "uint256" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "A",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "fee",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Virtual price is 1e18 precision
const virtualPrice = await publicClient.readContract({
address: THREE_POOL,
abi: poolStateAbi,
functionName: "get_virtual_price",
});
// LP token value in USD (assuming underlying = $1)
const lpValueUsd = Number(virtualPrice) / 1e18;
// Pool balances per coin index
const [daiBalance, usdcBalance, usdtBalance] = await Promise.all([
publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [0n] }),
publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [1n] }),
publicClient.readContract({ address: THREE_POOL, abi: poolStateAbi, functionName: "balances", args: [2n] }),
]);
// Amplification parameter
const amplification = await publicClient.readContract({
address: THREE_POOL,
abi: poolStateAbi,
functionName: "A",
});
// Fee in 1e10 precision (4000000 = 0.04%)
const poolFee = await publicClient.readContract({
address: THREE_POOL,
abi: poolStateAbi,
functionName: "fee",
});
const feePercent = Number(poolFee) / 1e10 * 100;
Contract Addresses
Last verified: February 2026
See resources/contract-addresses.md for the full address table.
| Contract | Ethereum |
|---|---|
| 3pool | 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7 |
| stETH/ETH | 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022 |
| Tricrypto2 | 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46 |
| CRV Token | 0xD533a949740bb3306d119CC777fa900bA034cd52 |
| veCRV | 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2 |
| Curve Router | 0xF0d4c12A5768D806021F80a262B4d39d26C58b8D |
| MetaRegistry | 0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC |
| crvUSD | 0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E |
Error Handling
| Error | Cause | Fix |
|---|---|---|
Exchange resulted in fewer coins than expected | Output below min_dy | Increase slippage tolerance or re-quote |
Exceeds allowance | Pool not approved to spend token | Call approve() with sufficient amount |
Insufficient funds | Balance below swap amount | Check balanceOf before calling exchange |
| Empty revert (Vyper) | Wrong function signature or invalid index | Verify ABI matches pool type, check coin indices |
dev: exceeds allowance | Vyper dev error for allowance check | Approve token to the correct pool address |
Lock expired | Trying to increase amount on expired veCRV lock | Withdraw first, then create new lock |
Withdraw old tokens first | Creating veCRV lock when one already exists | Call withdraw() on expired lock first |
Security
Slippage Protection
Never set min_dy to 0 in production. Always quote with get_dy() first.
const expectedOut = await publicClient.readContract({
address: poolAddress,
abi: threePoolAbi,
functionName: "get_dy",
args: [i, j, amountIn],
});
// For stableswap: 10-50 bps is reasonable
const minDy = (expectedOut * 9990n) / 10000n; // 10 bps
// For cryptoswap/volatile: 50-200 bps
const minDyCrypto = (expectedOut * 9950n) / 10000n; // 50 bps
USDT Approval Reset
USDT requires setting allowance to 0 before setting a new non-zero value.
async function approveUsdt(spender: Address, amount: bigint): Promise<void> {
const currentAllowance = await publicClient.readContract({
address: USDT,
abi: erc20Abi,
functionName: "allowance",
args: [account.address, spender],
});
if (currentAllowance > 0n && currentAllowance < amount) {
const { request: resetReq } = await publicClient.simulateContract({
address: USDT,
abi: erc20Abi,
functionName: "approve",
args: [spender, 0n],
account: account.address,
});
const resetHash = await walletClient.writeContract(resetReq);
await publicClient.waitForTransactionReceipt({ hash: resetHash });
}
const { request } = await publicClient.simulateContract({
address: USDT,
abi: erc20Abi,
functionName: "approve",
args: [spender, amount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("USDT approval failed");
}
Front-Running Mitigation
- Use tight
min_dyon every swap (quote + slippage) - Use Flashbots Protect RPC for mainnet transactions
- Large liquidity operations should use proportional add/remove to minimize extractable value
- For large single-sided deposits, split into multiple smaller transactions
References
optimism
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Optimism
Optimism is an EVM-equivalent Layer 2 using optimistic rollups. Transactions execute on L2 with data posted to Ethereum L1 for security. The OP Stack is the modular framework powering OP Mainnet, Base, Zora, Mode, and the broader Superchain. Smart contracts deploy identically to Ethereum — no custom compiler, no special opcodes.
What You Probably Got Wrong
- OP Mainnet IS EVM-equivalent, not just EVM-compatible — Your Solidity contracts deploy without modification. No
--legacyflag, no custom compiler.forge createandhardhat deploywork identically to Ethereum. If someone tells you to change your Solidity for "OP compatibility", they are wrong. - Gas has two components, not one — Every transaction pays L2 execution gas AND an L1 data fee for posting calldata/blobs to Ethereum. If you only estimate L2 gas via
eth_estimateGas, your cost estimate will be wrong. The L1 data fee often dominates total cost. Use theGasPriceOraclepredeploy at0x420000000000000000000000000000000000000F. - L2→L1 withdrawals take 7 days, not minutes — L1→L2 deposits finalize in ~1-3 minutes. L2→L1 withdrawals require a 7-day challenge period (the "fault proof window"). Users must prove the withdrawal, wait 7 days, then finalize. Three separate transactions on L1. If your UX assumes instant bridging both ways, it is broken.
block.numberreturns the L2 block number, not L1 — On OP Mainnet,block.numberis the L2 block number. To get the L1 block number, read theL1Blockpredeploy at0x4200000000000000000000000000000000000015. L2 blocks are produced every 2 seconds.msg.senderworks normally — there is notx.originaliasing on L2 — Cross-domain messages from L1 to L2 alias the sender address (add0x1111000000000000000000000000000000001111). But for normal L2 transactions,msg.senderbehaves exactly like Ethereum. Only worry about aliasing when receiving L1→L2 messages in your contract.- Predeploy contracts live at fixed addresses starting with
0x4200...— These are NOT deployed by you. They exist at genesis.L2CrossDomainMessenger,L2StandardBridge,GasPriceOracle,L1Block, and others all live at hardcoded addresses in the0x4200...range. Do not try to deploy them. - The sequencer is centralized but cannot steal funds — The sequencer orders transactions and proposes state roots. If it goes down, you cannot submit new transactions until it recovers (or until permissionless fault proofs allow forced inclusion). But the sequencer cannot forge invalid state — the fault proof system protects withdrawals.
- EIP-4844 blob data changed the gas model — After the Ecotone upgrade (March 2024), OP Mainnet posts data using EIP-4844 blobs instead of calldata. This reduced L1 data fees by ~10-100x. The
GasPriceOraclemethods changed. If you are reading pre-Ecotone documentation, the fee formulas are outdated. - SuperchainERC20 is not a standard ERC20 — It is a cross-chain token standard for OP Stack chains that enables native interop between Superchain members. Tokens must implement
ICrosschainERC20withcrosschainMintandcrosschainBurn. Do not assume a regular ERC20 works across chains.
Quick Start
Chain Configuration
import { defineChain } from "viem";
import { optimism, optimismSepolia } from "viem/chains";
// OP Mainnet is built-in
// Chain ID: 10
// RPC: https://mainnet.optimism.io
// Explorer: https://optimistic.etherscan.io
// OP Sepolia is also built-in
// Chain ID: 11155420
// RPC: https://sepolia.optimism.io
// Explorer: https://sepolia-optimistic.etherscan.io
Environment Setup
# .env
PRIVATE_KEY=your_private_key_here
OP_MAINNET_RPC=https://mainnet.optimism.io
OP_SEPOLIA_RPC=https://sepolia.optimism.io
ETHERSCAN_API_KEY=your_optimistic_etherscan_api_key
Viem Client Setup
import { createPublicClient, createWalletClient, http } from "viem";
import { optimism } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(`0x${process.env.PRIVATE_KEY}`);
const publicClient = createPublicClient({
chain: optimism,
transport: http(process.env.OP_MAINNET_RPC),
});
const walletClient = createWalletClient({
account,
chain: optimism,
transport: http(process.env.OP_MAINNET_RPC),
});
Chain Configuration
| Property | OP Mainnet | OP Sepolia |
|---|---|---|
| Chain ID | 10 | 11155420 |
| Currency | ETH | ETH |
| RPC | https://mainnet.optimism.io | https://sepolia.optimism.io |
| Explorer | https://optimistic.etherscan.io | https://sepolia-optimistic.etherscan.io |
| Block time | 2 seconds | 2 seconds |
| Withdrawal period | 7 days | ~12 seconds (testnet) |
Alternative RPCs
| Provider | Endpoint |
|---|---|
| Alchemy | https://opt-mainnet.g.alchemy.com/v2/<KEY> |
| Infura | https://optimism-mainnet.infura.io/v3/<KEY> |
| QuickNode | Custom endpoint per project |
| Conduit | https://rpc.optimism.io |
Deployment
OP Mainnet is EVM-equivalent. Deploy exactly as you would to Ethereum.
Foundry
# Deploy to OP Mainnet
forge create src/MyContract.sol:MyContract \
--rpc-url $OP_MAINNET_RPC \
--private-key $PRIVATE_KEY \
--broadcast
# Deploy with constructor args
forge create src/MyToken.sol:MyToken \
--rpc-url $OP_MAINNET_RPC \
--private-key $PRIVATE_KEY \
--constructor-args "MyToken" "MTK" 18 \
--broadcast
# Deploy via script
forge script script/Deploy.s.sol:DeployScript \
--rpc-url $OP_MAINNET_RPC \
--private-key $PRIVATE_KEY \
--broadcast \
--verify \
--etherscan-api-key $ETHERSCAN_API_KEY
Hardhat
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
const config: HardhatUserConfig = {
solidity: "0.8.24",
networks: {
optimism: {
url: process.env.OP_MAINNET_RPC || "https://mainnet.optimism.io",
accounts: [process.env.PRIVATE_KEY!],
},
optimismSepolia: {
url: process.env.OP_SEPOLIA_RPC || "https://sepolia.optimism.io",
accounts: [process.env.PRIVATE_KEY!],
},
},
etherscan: {
apiKey: {
optimisticEthereum: process.env.ETHERSCAN_API_KEY!,
optimisticSepolia: process.env.ETHERSCAN_API_KEY!,
},
},
};
export default config;
npx hardhat run scripts/deploy.ts --network optimism
Verification
Foundry
# Verify after deployment
forge verify-contract <DEPLOYED_ADDRESS> src/MyContract.sol:MyContract \
--chain-id 10 \
--etherscan-api-key $ETHERSCAN_API_KEY
# Verify with constructor args
forge verify-contract <DEPLOYED_ADDRESS> src/MyToken.sol:MyToken \
--chain-id 10 \
--etherscan-api-key $ETHERSCAN_API_KEY \
--constructor-args $(cast abi-encode "constructor(string,string,uint8)" "MyToken" "MTK" 18)
Hardhat
npx hardhat verify --network optimism <DEPLOYED_ADDRESS> "MyToken" "MTK" 18
Blockscout
OP Mainnet also has a Blockscout explorer at https://optimism.blockscout.com. Verification works via the standard Blockscout API — set the verifier URL in Foundry:
forge verify-contract <DEPLOYED_ADDRESS> src/MyContract.sol:MyContract \
--verifier blockscout \
--verifier-url https://optimism.blockscout.com/api/
Cross-Chain Messaging
The CrossDomainMessenger is the canonical way to send arbitrary messages between L1 and L2. It handles replay protection, sender authentication, and gas forwarding.
Architecture
L1 → L2 (Deposits):
User → L1CrossDomainMessenger → OptimismPortal → L2CrossDomainMessenger → Target
L2 → L1 (Withdrawals):
User → L2CrossDomainMessenger → L2ToL1MessagePasser → [7 day wait] → OptimismPortal → L1CrossDomainMessenger → Target
L1 → L2 Message (Deposit)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IL1CrossDomainMessenger {
function sendMessage(
address _target,
bytes calldata _message,
uint32 _minGasLimit
) external payable;
}
contract L1Sender {
IL1CrossDomainMessenger public immutable messenger;
constructor(address _messenger) {
messenger = IL1CrossDomainMessenger(_messenger);
}
/// @notice Send a message from L1 to a contract on L2.
/// @param l2Target The L2 contract address to call.
/// @param message The calldata to send to the L2 target.
/// @param minGasLimit Minimum gas for L2 execution. Overestimate — unused gas is NOT refunded to L1.
function sendToL2(
address l2Target,
bytes calldata message,
uint32 minGasLimit
) external payable {
messenger.sendMessage{value: msg.value}(l2Target, message, minGasLimit);
}
}
L2 → L1 Message (Withdrawal)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IL2CrossDomainMessenger {
function sendMessage(
address _target,
bytes calldata _message,
uint32 _minGasLimit
) external payable;
function xDomainMessageSender() external view returns (address);
}
contract L2Sender {
/// @dev L2CrossDomainMessenger predeploy address — same on all OP Stack chains
IL2CrossDomainMessenger public constant MESSENGER =
IL2CrossDomainMessenger(0x4200000000000000000000000000000000000007);
function sendToL1(
address l1Target,
bytes calldata message,
uint32 minGasLimit
) external payable {
MESSENGER.sendMessage{value: msg.value}(l1Target, message, minGasLimit);
}
}
Receiving Cross-Chain Messages
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ICrossDomainMessenger {
function xDomainMessageSender() external view returns (address);
}
contract L2Receiver {
ICrossDomainMessenger public constant MESSENGER =
ICrossDomainMessenger(0x4200000000000000000000000000000000000007);
address public immutable l1Sender;
constructor(address _l1Sender) {
l1Sender = _l1Sender;
}
modifier onlyFromL1Sender() {
require(
msg.sender == address(MESSENGER) &&
MESSENGER.xDomainMessageSender() == l1Sender,
"Not authorized L1 sender"
);
_;
}
function handleMessage(uint256 value) external onlyFromL1Sender {
// Process the cross-chain message
}
}
Sender Aliasing
When an L1 contract sends a message to L2, the apparent msg.sender on L2 is the aliased address:
l2Sender = l1ContractAddress + 0x1111000000000000000000000000000000001111
The CrossDomainMessenger handles un-aliasing internally. If you bypass the messenger and send directly via OptimismPortal, you must account for aliasing yourself.
Predeploy Contracts
These contracts exist at genesis on every OP Stack chain. Do not deploy them — they are already there.
| Contract | Address | Purpose |
|---|---|---|
| L2ToL1MessagePasser | 0x4200000000000000000000000000000000000016 | Initiates L2→L1 withdrawals |
| L2CrossDomainMessenger | 0x4200000000000000000000000000000000000007 | Sends/receives cross-chain messages |
| L2StandardBridge | 0x4200000000000000000000000000000000000010 | Bridges ETH and ERC20 tokens |
| L2ERC721Bridge | 0x4200000000000000000000000000000000000014 | Bridges ERC721 tokens |
| GasPriceOracle | 0x420000000000000000000000000000000000000F | L1 data fee calculation |
| L1Block | 0x4200000000000000000000000000000000000015 | Exposes L1 block info on L2 |
| WETH9 | 0x4200000000000000000000000000000000000006 | Wrapped ETH |
| L1BlockNumber | 0x4200000000000000000000000000000000000013 | L1 block number (deprecated, use L1Block) |
| SequencerFeeVault | 0x4200000000000000000000000000000000000011 | Collects sequencer fees |
| BaseFeeVault | 0x4200000000000000000000000000000000000019 | Collects base fees |
| L1FeeVault | 0x420000000000000000000000000000000000001A | Collects L1 data fees |
| GovernanceToken | 0x4200000000000000000000000000000000000042 | OP token on L2 |
Reading L1 Block Info
interface IL1Block {
function number() external view returns (uint64);
function timestamp() external view returns (uint64);
function basefee() external view returns (uint256);
function hash() external view returns (bytes32);
function batcherHash() external view returns (bytes32);
function l1FeeOverhead() external view returns (uint256);
function l1FeeScalar() external view returns (uint256);
function blobBaseFee() external view returns (uint256);
function baseFeeScalar() external view returns (uint32);
function blobBaseFeeScalar() external view returns (uint32);
}
// Usage
IL1Block constant L1_BLOCK = IL1Block(0x4200000000000000000000000000000000000015);
uint64 l1BlockNumber = L1_BLOCK.number();
uint256 l1BaseFee = L1_BLOCK.basefee();
Gas Model
Every OP Mainnet transaction pays two fees:
- L2 execution fee — Standard EVM gas, priced by L2
basefee+ optional priority fee. Calculated identically to Ethereum. - L1 data fee — Cost of posting the transaction's data to Ethereum L1 as calldata or blob data. This is the OP-specific component.
Post-Ecotone Formula (Current)
After the Ecotone upgrade (March 2024), L1 data fee uses a two-component formula based on calldata gas and blob gas:
l1DataFee = (l1BaseFeeScalar * l1BaseFee * 16 + l1BlobBaseFeeScalar * l1BlobBaseFee) * compressedTxSize / 1e6
l1BaseFee— Ethereum L1 base fee (fromL1Blockpredeploy)l1BlobBaseFee— EIP-4844 blob base fee (fromL1Blockpredeploy)l1BaseFeeScalar— System-configured scalar for calldata cost componentl1BlobBaseFeeScalar— System-configured scalar for blob cost componentcompressedTxSize— Estimated compressed size of the signed transaction
GasPriceOracle
interface IGasPriceOracle {
/// @notice Estimate L1 data fee for raw signed transaction bytes
function getL1Fee(bytes memory _data) external view returns (uint256);
/// @notice Get current L1 base fee (read from L1Block)
function l1BaseFee() external view returns (uint256);
/// @notice Ecotone: get blob base fee
function blobBaseFee() external view returns (uint256);
/// @notice Ecotone: get base fee scalar
function baseFeeScalar() external view returns (uint32);
/// @notice Ecotone: get blob base fee scalar
function blobBaseFeeScalar() external view returns (uint32);
/// @notice Check if Ecotone is active
function isEcotone() external view returns (bool);
/// @notice Check if Fjord is active
function isFjord() external view returns (bool);
/// @notice Fjord: estimate compressed size using FastLZ
function getL1GasUsed(bytes memory _data) external view returns (uint256);
}
IGasPriceOracle constant GAS_ORACLE =
IGasPriceOracle(0x420000000000000000000000000000000000000F);
Estimating Total Cost in TypeScript
import { createPublicClient, http, parseAbi } from "viem";
import { optimism } from "viem/chains";
const client = createPublicClient({
chain: optimism,
transport: http(),
});
const GAS_ORACLE = "0x420000000000000000000000000000000000000F" as const;
const gasPriceOracleAbi = parseAbi([
"function getL1Fee(bytes memory _data) external view returns (uint256)",
"function l1BaseFee() external view returns (uint256)",
"function blobBaseFee() external view returns (uint256)",
"function baseFeeScalar() external view returns (uint32)",
"function blobBaseFeeScalar() external view returns (uint32)",
]);
async function estimateTotalCost(serializedTx: `0x${string}`) {
const [l2GasEstimate, gasPrice, l1DataFee] = await Promise.all([
client.estimateGas({ data: serializedTx }),
client.getGasPrice(),
client.readContract({
address: GAS_ORACLE,
abi: gasPriceOracleAbi,
functionName: "getL1Fee",
args: [serializedTx],
}),
]);
const l2ExecutionFee = l2GasEstimate * gasPrice;
const totalFee = l2ExecutionFee + l1DataFee;
return {
l2ExecutionFee,
l1DataFee,
totalFee,
};
}
Gas Optimization Tips
- Minimize calldata: the L1 data fee scales with transaction data size. Fewer bytes = lower L1 fee.
- Use
0bytes when possible: zero bytes cost 4 gas in calldata vs 16 gas for non-zero bytes. - Batch operations: one large transaction costs less in L1 data fee overhead than many small ones.
- After Ecotone, blob pricing makes L1 data fees much cheaper and more stable than pre-Ecotone calldata pricing.
Standard Bridge
The Standard Bridge enables ETH and ERC20 transfers between L1 and L2. It is a pair of contracts: L1StandardBridge on Ethereum and L2StandardBridge (predeploy) on OP Mainnet.
Bridge ETH: L1 → L2
interface IL1StandardBridge {
/// @notice Bridge ETH to L2. Appears at recipient address on L2 after ~1-3 min.
function depositETH(uint32 _minGasLimit, bytes calldata _extraData) external payable;
/// @notice Bridge ETH to a different address on L2.
function depositETHTo(
address _to,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable;
}
Bridge ETH: L2 → L1
interface IL2StandardBridge {
/// @notice Initiate ETH withdrawal to L1. Requires prove + finalize after 7 days.
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable;
}
// Withdraw ETH from L2 to L1
// _l2Token = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000 (legacy ETH representation)
// Send ETH as msg.value, set _amount to the same value
Bridge ERC20: L1 → L2
interface IL1StandardBridge {
/// @notice Bridge ERC20 to L2. Token must have a corresponding L2 representation.
function depositERC20(
address _l1Token,
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external;
function depositERC20To(
address _l1Token,
address _l2Token,
uint256 _amount,
address _to,
uint32 _minGasLimit,
bytes calldata _extraData
) external;
}
Bridge ERC20: L2 → L1
interface IL2StandardBridge {
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable;
function withdrawTo(
address _l2Token,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
) external payable;
}
Withdrawal Lifecycle (L2 → L1)
Every L2→L1 withdrawal requires three L1 transactions:
- Initiate — Call
withdrawonL2StandardBridgeorL2CrossDomainMessenger. Produces a withdrawal hash. - Prove — After the L2 output root containing your withdrawal is proposed on L1 (~1 hour), call
proveWithdrawalTransactiononOptimismPortal. - Finalize — After the 7-day challenge period, call
finalizeWithdrawalTransactiononOptimismPortal.
import { getWithdrawals, getL2Output } from "viem/op-stack";
// After initiating withdrawal on L2, get the receipt
const l2Receipt = await publicClient.getTransactionReceipt({ hash: l2TxHash });
// Build withdrawal proof (after output root is proposed, ~1 hour)
const output = await getL2Output(l1Client, {
l2BlockNumber: l2Receipt.blockNumber,
targetChain: optimism,
});
// Prove on L1
const proveHash = await walletClient.proveWithdrawal({
output,
withdrawal: withdrawals[0],
targetChain: optimism,
});
// Wait 7 days, then finalize on L1
const finalizeHash = await walletClient.finalizeWithdrawal({
withdrawal: withdrawals[0],
targetChain: optimism,
});
SuperchainERC20
SuperchainERC20 is a cross-chain token standard enabling native token transfers between OP Stack chains in the Superchain. Tokens implementing this standard can move between chains without traditional bridge locking.
Interface
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @notice Interface for tokens that support cross-chain transfers within the Superchain.
interface ICrosschainERC20 {
/// @notice Emitted when tokens are minted via a cross-chain transfer.
event CrosschainMint(address indexed to, uint256 amount, address indexed sender);
/// @notice Emitted when tokens are burned for a cross-chain transfer.
event CrosschainBurn(address indexed from, uint256 amount, address indexed sender);
/// @notice Mint tokens on this chain as part of a cross-chain transfer.
/// @dev Only callable by the SuperchainTokenBridge.
function crosschainMint(address _to, uint256 _amount) external;
/// @notice Burn tokens on this chain to initiate a cross-chain transfer.
/// @dev Only callable by the SuperchainTokenBridge.
function crosschainBurn(address _from, uint256 _amount) external;
}
Implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ICrosschainERC20} from "./ICrosschainERC20.sol";
/// @dev SuperchainTokenBridge predeploy address — same on all OP Stack chains
address constant SUPERCHAIN_TOKEN_BRIDGE = 0x4200000000000000000000000000000000000028;
contract MySuperchainToken is ERC20, ICrosschainERC20 {
constructor() ERC20("MySuperchainToken", "MST") {
_mint(msg.sender, 1_000_000 * 1e18);
}
function crosschainMint(address _to, uint256 _amount) external override {
require(msg.sender == SUPERCHAIN_TOKEN_BRIDGE, "Only bridge");
_mint(_to, _amount);
emit CrosschainMint(_to, _amount, msg.sender);
}
function crosschainBurn(address _from, uint256 _amount) external override {
require(msg.sender == SUPERCHAIN_TOKEN_BRIDGE, "Only bridge");
_burn(_from, _amount);
emit CrosschainBurn(_from, _amount, msg.sender);
}
}
Cross-Chain Transfer Flow
- User calls
SuperchainTokenBridge.sendERC20on the source chain - Bridge calls
crosschainBurnon the token contract (burns on source) - A cross-chain message is relayed to the destination chain
- Bridge calls
crosschainMinton the destination chain's token contract (mints on destination)
OP Stack
The OP Stack is the modular, open-source framework for building L2 blockchains. OP Mainnet, Base, Zora, Mode, and others are all OP Stack chains forming the Superchain.
Key Components
| Component | Description |
|---|---|
| op-node | Consensus client — derives L2 blocks from L1 data |
| op-geth | Execution client — modified go-ethereum |
| op-batcher | Posts transaction data to L1 (calldata or blobs) |
| op-proposer | Proposes L2 output roots to L1 |
| op-challenger | Runs fault proof games to challenge invalid proposals |
Superchain
The Superchain is a network of OP Stack chains sharing:
- Bridge contracts on L1
- Sequencer coordination
- Governance via the Optimism Collective
- Interoperability messaging
Current Superchain members include OP Mainnet, Base, Zora, Mode, Fraxtal, Metal, and others. All share the same upgrade path and security model.
Building a Custom OP Chain
Use the OP Stack to launch your own chain:
# Clone the optimism monorepo
git clone https://github.com/ethereum-optimism/optimism.git
cd optimism
# Install dependencies
pnpm install
# Configure your chain (edit deploy-config)
# Deploy L1 contracts
# Start op-node, op-geth, op-batcher, op-proposer
Refer to the OP Stack Getting Started Guide for complete chain deployment.
Governance
The Optimism Collective governs the protocol through a bicameral system:
- Token House — OP token holders vote on protocol upgrades, incentive programs, and treasury allocations
- Citizens' House — Soulbound "citizen" badges vote on retroactive public goods funding (RetroPGF)
OP Token
| Property | Value |
|---|---|
| Address (L2) | 0x4200000000000000000000000000000000000042 |
| Address (L1) | 0x4200000000000000000000000000000000000042 is the L2 predeploy; L1 address is 0x4200000000000000000000000000000000000042 bridged |
| Total supply | 4,294,967,296 (2^32) |
| Type | Governance only (no fee burn or staking yield) |
Delegation
OP token holders delegate voting power to active governance participants:
import { parseAbi } from "viem";
const opTokenAbi = parseAbi([
"function delegate(address delegatee) external",
"function delegates(address account) external view returns (address)",
"function getVotes(address account) external view returns (uint256)",
]);
const OP_TOKEN = "0x4200000000000000000000000000000000000042" as const;
// Delegate voting power
const hash = await walletClient.writeContract({
address: OP_TOKEN,
abi: opTokenAbi,
functionName: "delegate",
args: [delegateAddress],
});
Key Differences from Ethereum
| Feature | Ethereum | OP Mainnet |
|---|---|---|
| Block time | 12 seconds | 2 seconds |
| Gas pricing | Single base fee | L2 execution + L1 data fee |
block.number | L1 block number | L2 block number |
| Finality | ~15 minutes (2 epochs) | 7 days for L2→L1 (challenge period) |
| Sequencing | Decentralized validators | Centralized sequencer (OP Labs) |
PREVRANDAO | Beacon chain randomness | Sequencer-set value (NOT random, do NOT use for randomness) |
PUSH0 | Supported (Shanghai+) | Supported |
block.difficulty | Always 0 post-merge | Always 0 |
Opcodes Differences
PREVRANDAO(formerlyDIFFICULTY) — Returns the sequencer-set value, NOT true randomness. Never use for on-chain randomness. Use Chainlink VRF or a commit-reveal scheme.ORIGIN/CALLER— Work normally for L2 transactions. For L1→L2 deposits, theoriginis aliased (see Sender Aliasing).- All other opcodes behave identically to Ethereum.
Unsupported Features
- No native account abstraction (EIP-4337) — Use third-party bundlers (Pimlico, Alchemy, Stackup).
- No
eth_getProofwith pending block tag — Uselatestinstead.