Comparing curve with monad
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
monad
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Monad L1 Development
Chain Configuration
Mainnet
| Property | Value |
|---|---|
| Chain ID | 143 |
| Currency | MON (18 decimals) |
| EVM Version | Pectra fork |
| Block Time | 400ms |
| Finality | 800ms (2 slots) |
| Block Gas Limit | 200M |
| Tx Gas Limit | 30M |
| Gas Throughput | 500M gas/sec |
| Min Base Fee | 100 MON-gwei |
| Node Version | v0.12.7 / MONAD_EIGHT |
RPC Endpoints (Mainnet)
| URL | Provider | Rate Limit | Batch | Notes |
|---|---|---|---|---|
https://rpc.monad.xyz / wss://rpc.monad.xyz | QuickNode | 25 rps | 100 | Default |
https://rpc1.monad.xyz / wss://rpc1.monad.xyz | Alchemy | 15 rps | 100 | No debug/trace |
https://rpc2.monad.xyz / wss://rpc2.monad.xyz | Goldsky Edge | 300/10s | 10 | Historical state |
https://rpc3.monad.xyz / wss://rpc3.monad.xyz | Ankr | 300/10s | 10 | No debug |
https://rpc-mainnet.monadinfra.com / wss://rpc-mainnet.monadinfra.com | MF | 20 rps | 1 | Historical state |
Block Explorers
| Explorer | URL |
|---|---|
| MonadVision | https://monadvision.com |
| Monadscan | https://monadscan.com |
| Socialscan | https://monad.socialscan.io |
| Visualization | https://gmonads.com |
| Traces | Phalcon Explorer, Tenderly |
| UserOps | Jiffyscan |
Testnet
| Property | Value |
|---|---|
| Chain ID | 10143 |
| RPC | https://testnet-rpc.monad.xyz |
| WebSocket | wss://testnet-rpc.monad.xyz |
| Explorer | https://testnet.monadexplorer.com |
| Faucet | https://testnet.monad.xyz |
Key Differences from Ethereum
| Feature | Ethereum | Monad |
|---|---|---|
| Block time | 12s | 400ms |
| Finality | ~12-18 min | 800ms (2 slots) |
| Throughput | ~10 TPS | 10,000+ TPS |
| Gas charging | Gas used | Gas limit |
| Max contract size | 24.5 KB | 128 KB |
| Blob txns (EIP-4844) | Supported | Not supported |
| Global mempool | Yes | No (leader-based forwarding) |
| Account cold access | 2,600 gas | 10,100 gas |
| Storage cold access | 2,100 gas | 8,100 gas |
| Reserve balance | None | ~10 MON per account |
TIMESTAMP granularity | 1 per block | 2-3 blocks share same second |
| Precompile 0x0100 | N/A | EIP-7951 secp256r1 (P256) |
| EIP-7702 min balance | None | 10 MON for delegated EOAs |
| EIP-7702 CREATE/CREATE2 | Allowed | Banned for delegated EOAs |
| Tx types supported | 0,1,2,3,4 | 0,1,2,4 (no type 3) |
Gas Limit Charging Model
Monad charges gas_limit * price_per_gas, NOT gas_used * price_per_gas. This enables asynchronous execution — execution happens after consensus, so gas used isn't known at inclusion time.
gas_paid = gas_limit * price_per_gas
price_per_gas = min(base_price_per_gas + priority_price_per_gas, max_price_per_gas)
Set gas limits explicitly for fixed-cost operations (e.g., 21000 for transfers) to avoid overpaying.
Reserve Balance
Every account maintains a ~10 MON reserve for gas across the next 3 blocks. Transactions that would reduce balance below this threshold are rejected. This prevents DoS during asynchronous execution.
Block Lifecycle & Finality
Proposed → Voted (speculative finality, T+1) → Finalized (T+2) → Verified/state root (T+5)
| Phase | Latency | When to Use |
|---|---|---|
| Voted | 400ms | UI updates, most dApps |
| Finalized | 800ms | Conservative apps |
| Verified | ~2s | Exchanges, bridges, stablecoins |
Quick Start: viem Chain Definition
import { defineChain } from "viem";
export const monad = defineChain({
id: 143,
name: "Monad",
nativeCurrency: { name: "MON", symbol: "MON", decimals: 18 },
rpcUrls: {
default: { http: ["https://rpc.monad.xyz"], webSocket: ["wss://rpc.monad.xyz"] },
},
blockExplorers: {
default: { name: "MonadVision", url: "https://monadvision.com" },
monadscan: { name: "Monadscan", url: "https://monadscan.com" },
},
});
export const monadTestnet = defineChain({
id: 10143,
name: "Monad Testnet",
nativeCurrency: { name: "MON", symbol: "MON", decimals: 18 },
rpcUrls: {
default: { http: ["https://testnet-rpc.monad.xyz"], webSocket: ["wss://testnet-rpc.monad.xyz"] },
},
blockExplorers: {
default: { name: "Monad Explorer", url: "https://testnet.monadexplorer.com" },
},
testnet: true,
});
Quick Start: Foundry Setup
Install Monad Foundry Fork
curl -L https://raw.githubusercontent.com/category-labs/foundry/monad/foundryup/install | bash
foundryup --network monad
Project Init
forge init --template monad-developers/foundry-monad my-project
foundry.toml
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
evm_version = "prague"
[rpc_endpoints]
monad = "https://rpc.monad.xyz"
monad_testnet = "https://testnet-rpc.monad.xyz"
[etherscan]
monad = { key = "${ETHERSCAN_API_KEY}", chain = 143, url = "https://api.etherscan.io/v2/api?chainid=143" }
monad_testnet = { key = "${ETHERSCAN_API_KEY}", chain = 10143, url = "https://api.etherscan.io/v2/api?chainid=10143" }
Quick Start: Hardhat Configuration (v2)
const config: HardhatUserConfig = {
solidity: {
version: "0.8.28",
settings: {
evmVersion: "prague",
metadata: { bytecodeHash: "ipfs" },
},
},
networks: {
monadTestnet: {
url: "https://testnet-rpc.monad.xyz",
chainId: 10143,
accounts: [process.env.PRIVATE_KEY!],
},
monadMainnet: {
url: "https://rpc.monad.xyz",
chainId: 143,
accounts: [process.env.PRIVATE_KEY!],
},
},
etherscan: {
customChains: [{
network: "monadMainnet",
chainId: 143,
urls: {
apiURL: "https://api.etherscan.io/v2/api?chainid=143",
browserURL: "https://monadscan.com",
},
}],
},
sourcify: {
enabled: true,
apiUrl: "https://sourcify-api-monad.blockvision.org",
browserUrl: "https://monadvision.com",
},
};
Deployment
Foundry Deploy (Keystore)
cast wallet import monad-deployer --private-key $(cast wallet new | grep 'Private key:' | awk '{print $3}')
forge create src/MyContract.sol:MyContract \
--account monad-deployer \
--rpc-url https://rpc.monad.xyz \
--broadcast
forge create src/MyToken.sol:MyToken \
--account monad-deployer \
--rpc-url https://rpc.monad.xyz \
--constructor-args "MyToken" "MTK" 18 \
--broadcast
Foundry Deploy (Script)
forge script script/Deploy.s.sol \
--account monad-deployer \
--rpc-url https://rpc.monad.xyz \
--broadcast \
--slow
Hardhat Deploy
npx hardhat ignition deploy ignition/modules/Counter.ts --network monadMainnet
npx hardhat ignition deploy ignition/modules/Counter.ts --network monadMainnet --reset
Verification
MonadVision (Sourcify)
forge verify-contract <address> <ContractName> \
--chain 143 \
--verifier sourcify \
--verifier-url https://sourcify-api-monad.blockvision.org/
Monadscan (Etherscan)
forge verify-contract <address> <ContractName> \
--chain 143 \
--verifier etherscan \
--etherscan-api-key $ETHERSCAN_API_KEY \
--watch
Socialscan
forge verify-contract <address> <ContractName> \
--chain 143 \
--verifier etherscan \
--etherscan-api-key $SOCIALSCAN_API_KEY \
--verifier-url https://api.socialscan.io/monad-mainnet/v1/explorer/command_api/contract \
--watch
Hardhat Verify
npx hardhat verify <address> --network monadMainnet
For testnet verification, replace --chain 143 with --chain 10143 and use testnet RPC/explorer URLs.
Opcode Repricing Summary
Cold state access is ~4x more expensive on Monad than Ethereum. Warm access is identical.
| Access Type | Ethereum | Monad |
|---|---|---|
| Account (cold) | 2,600 | 10,100 |
| Storage slot (cold) | 2,100 | 8,100 |
| Account (warm) | 100 | 100 |
| Storage slot (warm) | 100 | 100 |
Selected precompile repricing:
| Precompile | Ethereum | Monad | Multiplier |
|---|---|---|---|
| ecRecover (0x01) | 3,000 | 6,000 | 2x |
| ecMul (0x07) | 6,000 | 30,000 | 5x |
| ecPairing (0x08) | 45,000 | 225,000 | 5x |
| point evaluation (0x0a) | 50,000 | 200,000 | 4x |
Monad-specific precompile: secp256r1 (P256) at 0x0100 for WebAuthn/passkey signature verification (EIP-7951).
EIP-1559 Parameters
| Parameter | Value |
|---|---|
| Block gas limit | 200M |
| Block gas target | 160M (80% of limit) |
| Per-transaction gas limit | 30M |
| Min base fee | 100 MON-gwei |
| Base fee max step size | 1/28 |
| Base fee decay factor | 0.96 |
The base fee controller increases slower and decreases faster than Ethereum's to prevent blockspace underutilization on a high-throughput chain.
Gas Optimization Tips
- Warm your storage — cold reads are 4x more expensive; use access lists (type 1/2 txns) for known slots
- Set explicit gas limits — you're charged for the limit, not usage
- Batch operations — high throughput means batching is less critical, but still saves gas limit overhead
- Avoid unnecessary cold precompile calls — ecPairing is 5x more expensive than Ethereum
- Design for parallel execution — per-user mappings over global counters where possible
- No blob transactions — use calldata for data availability
Parallel Execution
Monad executes transactions concurrently with optimistic conflict detection. No Solidity changes needed.
- Multiple virtual executors process transactions simultaneously
- Each generates "pending results" (inputs: SLOADs, outputs: SSTOREs)
- Serial commitment validates each result's inputs remain valid
- Conflict detected -> re-execute the affected transaction
- Results committed in original transaction order
Every transaction executes at most twice. Most transactions don't conflict, achieving near-linear speedup.
Parallel-Friendly Contract Design
| Pattern | Parallelizes Well | Why |
|---|---|---|
| Per-user mappings | Yes | Independent state per user |
| ERC-20 transfers between different pairs | Yes | Different storage slots |
| Global counter increment | No | All txns write same slot |
| AMM swaps on same pool | No | Same reserves storage |
| Independent NFT mints (incremental ID) | Partially | tokenId counter serializes |
Staking Precompile
Address: 0x0000000000000000000000000000000000001000
Only standard CALL is allowed. STATICCALL, DELEGATECALL, and CALLCODE are not permitted.
Core Functions
| Function | Selector | Gas Cost |
|---|---|---|
delegate(uint64) | 0x84994fec | 260,850 |
undelegate(uint64,uint256,uint8) | 0x5cf41514 | 147,750 |
compound(uint64) | 0xb34fea67 | 285,050 |
claimRewards(uint64) | 0xa76e2ca5 | 155,375 |
withdraw(uint64,uint8) | 0xaed2ee73 | 68,675 |
Delegate (Solidity)
address constant STAKING = 0x0000000000000000000000000000000000001000;
function delegateToValidator(uint64 validatorId) external payable {
(bool success,) = STAKING.call{value: msg.value}(
abi.encodeWithSelector(0x84994fec, validatorId)
);
require(success, "Delegation failed");
}
Delegate (viem)
import { encodeFunctionData } from "viem";
const STAKING_ADDRESS = "0x0000000000000000000000000000000000001000";
const hash = await walletClient.sendTransaction({
to: STAKING_ADDRESS,
value: parseEther("100"),
data: encodeFunctionData({
abi: [{ name: "delegate", type: "function", inputs: [{ name: "validatorId", type: "uint64" }], outputs: [] }],
functionName: "delegate",
args: [1n],
}),
});
EIP-7702 on Monad
Allows EOAs to gain smart contract capabilities via code delegation.
| Restriction | Detail |
|---|---|
| Minimum balance | Delegated EOAs cannot drop below 10 MON |
| CREATE/CREATE2 | Banned when delegated EOAs execute as smart contracts |
| Clearing delegation | Send type 0x04 pointing to address(0) |
import { walletClient } from "./client";
const authorization = await walletClient.signAuthorization({
account,
contractAddress: "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2",
});
const hash = await walletClient.sendTransaction({
authorizationList: [authorization],
data: "0xdeadbeef",
to: walletClient.account.address,
});
WebSocket Subscriptions
Standard eth_subscribe plus Monad-specific extensions:
newHeads — standard new block headers
logs — standard log filtering
monadNewHeads — Monad-specific block headers with extra fields
monadLogs — Monad-specific log events
Execution Events (Advanced)
For ultra-low-latency data consumption, Monad exposes execution events via shared-memory ring buffers. Consumer runs on same host as node. ~1 microsecond latency. Supported in C, C++, and Rust only.
Use execution events when JSON-RPC can't keep up with 10,000 TPS throughput. For most dApps, standard WebSocket subscriptions are sufficient.
Canonical Contracts
| Contract | Address |
|---|---|
| Wrapped MON (WMON) | 0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A |
| Staking Precompile | 0x0000000000000000000000000000000000001000 |
| Multicall3 | 0xcA11bde05977b3631167028862bE2a173976CA11 |
| USDC | 0x754704Bc059F8C67012fEd69BC8A327a5aafb603 |
| USDT0 | 0xe7cd86e13AC4309349F30B3435a9d337750fC82D |
| WETH | 0xEE8c0E9f1BFFb4Eb878d8f15f368A02a35481242 |
| WBTC | 0x0555E30da8f98308EdB960aa94C0Db47230d2B9c |
| ERC-4337 EntryPoint v0.7 | 0x0000000071727De22E5E9d8BAf0edAc6f37da032 |
| Safe | 0x69f4D1788e39c87893C980c06EdF4b7f686e2938 |
Supported Transaction Types
| Type | Name | Supported | Notes |
|---|---|---|---|
| 0 | Legacy | Yes | Pre-EIP-155 allowed but discouraged |
| 1 | EIP-2930 (access list) | Yes | |
| 2 | EIP-1559 (dynamic fee) | Yes | Recommended |
| 3 | EIP-4844 (blob) | No | Not supported on Monad |
| 4 | EIP-7702 (delegation) | Yes | With Monad-specific restrictions |
Smart Contract Tips
- Gas optimization still matters — even with cheap gas, optimize for users
- Same security model — all Solidity best practices (CEI, reentrancy guards) apply
- Parallel-friendly design — contracts with per-user mappings parallelize better than global counters
- 128 KB contract limit — larger contracts are possible but still optimize for gas
- No code changes needed for parallelism — it's at the runtime level
block.timestamp— 2-3 blocks may share the same second; don't rely on sub-second granularity- No blob transactions — EIP-4844 type 3 txns are not supported
Required Tooling Versions
| Tool | Minimum Version |
|---|---|
| Foundry | Monad fork (foundryup --network monad) |
| viem | 2.40.0+ |
| alloy-chains | 0.2.20+ |
| Hardhat Solidity | evmVersion: "prague" |
Pre-Deployment Checklist
- Using Monad Foundry fork or Hardhat with
evmVersion: "prague" - Correct chain ID (143 mainnet / 10143 testnet)
- Account funded with MON (remember ~10 MON reserve)
- Gas limit set explicitly for predictable cost (gas limit is charged, not gas used)
- Private key in env var, not hardcoded
- Contract size under 128 KB
- No EIP-4844 blob transactions (type 3 not supported)
- Verified on at least one explorer after deploy
Additional Reference
| File | Contents |
|---|---|
docs/architecture.md | MonadBFT consensus, parallel execution, deferred execution, MonadDb, JIT, RaptorCast |
docs/deployment.md | Foundry + Hardhat deploy/verify step-by-step guides |
docs/gas-and-opcodes.md | Gas pricing model, opcode repricing tables, precompile costs |
docs/staking.md | Staking precompile ABI, functions, events, epoch mechanics |
docs/ecosystem.md | Token addresses, bridges, oracles, indexers, canonical contracts |
docs/troubleshooting.md | Common issues and fixes for Monad development |
resources/contract-addresses.md | Key Monad contract addresses |
templates/deploy-monad.sh | Shell script for deploying to Monad |