Comparing curve with layerzero

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/curve/SKILL.md

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 pass i (sell token index) and j (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. Use get_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() vs exchange_underlying() — Plain pools use exchange(). Meta pools use exchange_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.

PoolAddressCoinsIndices
3pool0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7DAI, USDC, USDT0, 1, 2
stETH/ETH0xDC24316b9AE028F1497c275EB9192a3Ea0f67022ETH, stETH0, 1
frxETH/ETH0xa1F8A6807c402E4A15ef4EBa36528A3FED24E577ETH, frxETH0, 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, so 4000000 = 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.

PoolAddressCoins
tricrypto20xD51a44d3FaE010294C616388b506AcdA1bfAAE46USDT, 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.

ContractEthereum
3pool0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7
stETH/ETH0xDC24316b9AE028F1497c275EB9192a3Ea0f67022
Tricrypto20xD51a44d3FaE010294C616388b506AcdA1bfAAE46
CRV Token0xD533a949740bb3306d119CC777fa900bA034cd52
veCRV0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2
Curve Router0xF0d4c12A5768D806021F80a262B4d39d26C58b8D
MetaRegistry0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC
crvUSD0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E

Error Handling

ErrorCauseFix
Exchange resulted in fewer coins than expectedOutput below min_dyIncrease slippage tolerance or re-quote
Exceeds allowancePool not approved to spend tokenCall approve() with sufficient amount
Insufficient fundsBalance below swap amountCheck balanceOf before calling exchange
Empty revert (Vyper)Wrong function signature or invalid indexVerify ABI matches pool type, check coin indices
dev: exceeds allowanceVyper dev error for allowance checkApprove token to the correct pool address
Lock expiredTrying to increase amount on expired veCRV lockWithdraw first, then create new lock
Withdraw old tokens firstCreating veCRV lock when one already existsCall 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_dy on 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

layerzero

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/layerzero/SKILL.md

LayerZero

LayerZero V2 is an immutable, censorship-resistant messaging protocol for cross-chain communication. It enables smart contracts on different blockchains to send arbitrary messages to each other through a modular security stack of Decentralized Verifier Networks (DVNs). The core primitive is the OApp (Omnichain Application) — a contract that inherits OApp.sol and implements _lzSend / _lzReceive to send and receive cross-chain messages through EndpointV2.

What You Probably Got Wrong

AI agents trained before mid-2024 confuse V1 and V2 architecture. These are the critical corrections.

  • V2 is NOT V1 — completely different architecture. V1 used LZApp, ILayerZeroEndpoint, and a monolithic oracle+relayer model. V2 uses OApp, EndpointV2, and modular DVNs+Executors. Do NOT import @layerzerolabs/solidity-examples — that is V1. Use @layerzerolabs/oapp-evm for V2.
  • OFT burns on source, mints on destination — NOT a lock/mint bridge. The Omnichain Fungible Token standard burns tokens on the source chain and mints equivalent tokens on the destination. For existing ERC-20s that cannot add burn/mint, use OFTAdapter which locks on source and mints an OFT representation on destination.
  • DVNs replace the V1 oracle+relayer model. V1 had a single Oracle and Relayer operated by LayerZero Labs. V2 decouples verification into configurable DVN sets — you choose which DVNs must verify your messages and set quorum thresholds.
  • _lzSend requires proper fee estimation via quoteSend() or _quote(). You must call the quote function first to determine the exact MessagingFee (native + lzToken), then pass that fee as msg.value. Underpaying reverts.
  • Peer addresses must be set on BOTH chains. Calling setPeer(dstEid, bytes32(peerAddress)) on chain A is not enough. You must also call setPeer(srcEid, bytes32(chainAAddress)) on chain B. Unset peers cause NoPeer reverts.
  • Message ordering is NOT guaranteed unless you configure ordered delivery. V2 delivers messages in a nonce-based system, but by default the executor can deliver messages out of order. Use the OrderedNonce enforcement option if strict ordering matters.
  • eid (Endpoint ID) is NOT the chain ID. LayerZero uses its own Endpoint ID system. Ethereum mainnet is eid 30101, Arbitrum is 30110, Base is 30184, Optimism is 30111, Polygon is 30109. Using chain IDs instead of eids is the most common integration mistake.
  • Peer addresses are bytes32, not address. All peer addresses are stored as bytes32 to support non-EVM chains. For EVM addresses, left-pad with zeros: bytes32(uint256(uint160(addr))). Passing a raw address to setPeer will fail.
  • The Executor is separate from DVNs. DVNs verify messages, but the Executor actually calls lzReceive on the destination. You can configure a custom Executor or use the LayerZero default. If you set gas limits too low in message options, the Executor will run out of gas on the destination.

Quick Start

Installation

npm install @layerzerolabs/oapp-evm @layerzerolabs/lz-evm-protocol-v2 @openzeppelin/contracts

For Foundry projects:

forge install LayerZero-Labs/LayerZero-v2

Minimal OApp Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

import {OApp, Origin, MessagingFee} from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyOApp is OApp {
    event MessageSent(uint32 dstEid, bytes payload, uint256 nativeFee);
    event MessageReceived(uint32 srcEid, bytes32 sender, bytes payload);

    constructor(
        address _endpoint,
        address _delegate
    ) OApp(_endpoint, _delegate) Ownable(_delegate) {}

    /// @notice Sends a message to a destination chain
    /// @param _dstEid Destination endpoint ID
    /// @param _payload Arbitrary bytes payload
    /// @param _options Message execution options (gas, value)
    function sendMessage(
        uint32 _dstEid,
        bytes calldata _payload,
        bytes calldata _options
    ) external payable {
        MessagingFee memory fee = _quote(_dstEid, _payload, _options, false);
        if (msg.value < fee.nativeFee) revert InsufficientFee(msg.value, fee.nativeFee);

        _lzSend(_dstEid, _payload, _options, fee, payable(msg.sender));

        emit MessageSent(_dstEid, _payload, fee.nativeFee);
    }

    /// @notice Quotes the fee for sending a message
    /// @param _dstEid Destination endpoint ID
    /// @param _payload Arbitrary bytes payload
    /// @param _options Message execution options
    /// @return fee The messaging fee breakdown
    function quote(
        uint32 _dstEid,
        bytes calldata _payload,
        bytes calldata _options
    ) external view returns (MessagingFee memory fee) {
        return _quote(_dstEid, _payload, _options, false);
    }

    /// @dev Called by EndpointV2 when a message arrives from a source chain
    function _lzReceive(
        Origin calldata _origin,
        bytes32 /*_guid*/,
        bytes calldata _payload,
        address /*_executor*/,
        bytes calldata /*_extraData*/
    ) internal override {
        emit MessageReceived(_origin.srcEid, _origin.sender, _payload);
    }

    error InsufficientFee(uint256 sent, uint256 required);
}

Client Setup (TypeScript)

import { createPublicClient, createWalletClient, http, parseAbi, 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),
});

Core Concepts

Architecture Overview

Source Chain                          Destination Chain
+-----------+                        +-----------+
|  Your     |  _lzSend()             |  Your     |
|  OApp     | -----> EndpointV2      |  OApp     |
+-----------+        |               +-----------+
                     |                     ^
                     v                     | lzReceive()
              +------------+         +------------+
              |  MessageLib |         | EndpointV2 |
              +------------+         +------------+
                     |                     ^
                     v                     |
              +------+------+        +-----+-----+
              | DVN 1 | DVN 2|       | Executor  |
              +------+------+        +-----------+
                     |                     ^
                     +---------------------+
                     (off-chain verification & relay)

OApp

The base contract for all cross-chain applications. Inherits from OAppSender and OAppReceiver. Manages peer addresses and delegates message send/receive through EndpointV2.

OFT (Omnichain Fungible Token)

An ERC-20 that natively supports cross-chain transfers. Burns on source, mints on destination. For existing tokens, OFTAdapter wraps them.

ONFT (Omnichain Non-Fungible Token)

ERC-721 that supports cross-chain transfers. Locks on source, mints on destination.

EndpointV2

The immutable on-chain entry point. One per chain. Handles message dispatching, DVN verification, and executor relay. Cannot be upgraded.

DVN (Decentralized Verifier Network)

Off-chain verifiers that attest to cross-chain message validity. Each OApp configures which DVNs must verify its messages. Multiple DVNs can be required for higher security.

Executor

Calls lzReceive() on the destination contract. The default LayerZero Executor is used unless overridden. Executors are paid via the messaging fee.

MessageLib

Handles message serialization, DVN verification, and nonce tracking. V2 uses UltraLightNodeV2 (ULN302) as the default send/receive library.

OApp Development

Sending Messages

// _lzSend is inherited from OAppSender
function _lzSend(
    uint32 _dstEid,          // destination endpoint ID
    bytes memory _message,    // encoded payload
    bytes memory _options,    // execution options (gas, value)
    MessagingFee memory _fee, // fee from _quote()
    address payable _refundAddress
) internal returns (MessagingReceipt memory receipt);

The full send flow:

function sendPing(uint32 _dstEid) external payable {
    bytes memory payload = abi.encode("ping", block.timestamp);

    // Build options: 200k gas for lzReceive on destination
    bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200_000, 0);

    MessagingFee memory fee = _quote(_dstEid, payload, options, false);
    if (msg.value < fee.nativeFee) revert InsufficientFee(msg.value, fee.nativeFee);

    _lzSend(_dstEid, payload, options, fee, payable(msg.sender));
}

Receiving Messages

// Override _lzReceive to handle incoming messages
function _lzReceive(
    Origin calldata _origin,   // srcEid, sender (bytes32), nonce
    bytes32 _guid,             // globally unique message ID
    bytes calldata _payload,   // the message bytes
    address _executor,         // executor that delivered this
    bytes calldata _extraData  // additional data from executor
) internal override {
    (string memory message, uint256 timestamp) = abi.decode(_payload, (string, uint256));
    // Process the message
}

Peer Configuration

Peers must be set bidirectionally. The peer address is bytes32-encoded.

// On Ethereum OApp — register Arbitrum peer
oapp.setPeer(
    30110, // Arbitrum eid
    bytes32(uint256(uint160(arbitrumOAppAddress)))
);

// On Arbitrum OApp — register Ethereum peer
oapp.setPeer(
    30101, // Ethereum eid
    bytes32(uint256(uint160(ethereumOAppAddress)))
);

From TypeScript:

const oappAbi = parseAbi([
  "function setPeer(uint32 eid, bytes32 peer) external",
]);

function addressToBytes32(addr: Address): `0x${string}` {
  return `0x${addr.slice(2).padStart(64, "0")}` as `0x${string}`;
}

const { request } = await publicClient.simulateContract({
  address: ethereumOApp,
  abi: oappAbi,
  functionName: "setPeer",
  args: [30110, addressToBytes32(arbitrumOApp)],
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("setPeer reverted");

OFT (Omnichain Fungible Token)

Deploy a New OFT

For new tokens that do not already exist on any chain:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

import {OFT} from "@layerzerolabs/oft-evm/contracts/OFT.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyToken is OFT {
    constructor(
        string memory _name,
        string memory _symbol,
        address _lzEndpoint,
        address _delegate
    ) OFT(_name, _symbol, _lzEndpoint, _delegate) Ownable(_delegate) {
        // Mint initial supply to deployer
        _mint(_delegate, 1_000_000 * 10 ** decimals());
    }
}

OFTAdapter for Existing ERC-20s

If an ERC-20 already exists and cannot be modified, deploy OFTAdapter on the token's home chain. It locks the original token and coordinates minting on remote chains.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

import {OFTAdapter} from "@layerzerolabs/oft-evm/contracts/OFTAdapter.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyTokenAdapter is OFTAdapter {
    constructor(
        address _token,       // existing ERC-20 address
        address _lzEndpoint,
        address _delegate
    ) OFTAdapter(_token, _lzEndpoint, _delegate) Ownable(_delegate) {}
}

Sending OFT Cross-Chain

const oftAbi = parseAbi([
  "function send((uint32 dstEid, bytes32 to, uint256 amountLD, uint256 minAmountLD, bytes extraOptions, bytes composeMsg, bytes oftCmd) calldata sendParam, (uint256 nativeFee, uint256 lzTokenFee) calldata fee, address refundAddress) payable returns ((bytes32 guid, uint64 nonce, (uint256 nativeFee, uint256 lzTokenFee) fee) receipt)",
  "function quoteSend((uint32 dstEid, bytes32 to, uint256 amountLD, uint256 minAmountLD, bytes extraOptions, bytes composeMsg, bytes oftCmd) calldata sendParam, bool payInLzToken) view returns ((uint256 nativeFee, uint256 lzTokenFee) fee)",
]);

const DST_EID = 30110; // Arbitrum
const AMOUNT = 1000_000000000000000000n; // 1000 tokens (18 decimals)

const sendParam = {
  dstEid: DST_EID,
  to: addressToBytes32(account.address),
  amountLD: AMOUNT,
  minAmountLD: (AMOUNT * 995n) / 1000n, // 0.5% slippage
  extraOptions: "0x" as `0x${string}`,
  composeMsg: "0x" as `0x${string}`,
  oftCmd: "0x" as `0x${string}`,
};

// Quote the fee
const fee = await publicClient.readContract({
  address: oftAddress,
  abi: oftAbi,
  functionName: "quoteSend",
  args: [sendParam, false],
});

// Execute the send
const { request } = await publicClient.simulateContract({
  address: oftAddress,
  abi: oftAbi,
  functionName: "send",
  args: [sendParam, fee, account.address],
  value: fee.nativeFee,
  account: account.address,
});

const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("OFT send reverted");

OFT Shared Decimals

OFT uses a concept of "shared decimals" to normalize precision across chains. The default shared decimals is 6. Tokens with more than 6 decimals will have dust removed during transfers.

Local Decimals: 18 (standard ERC-20)
Shared Decimals: 6 (LayerZero default)
Dust removed: 12 decimal places

Sending 1.123456789012345678 tokens
Actually transferred: 1.123456000000000000 tokens
Dust lost: 0.000000789012345678 tokens

Override sharedDecimals() to change this behavior:

function sharedDecimals() public pure override returns (uint8) {
    return 8; // higher precision cross-chain
}

DVN & Security Configuration

Setting Required and Optional DVNs

Each OApp configures its security stack through the EndpointV2's delegate (typically the OApp owner).

import {SetConfigParam} from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol";

struct UlnConfig {
    uint64 confirmations;         // block confirmations before DVN can verify
    uint8 requiredDVNCount;       // DVNs that MUST verify (all required)
    uint8 optionalDVNCount;       // DVNs from optional pool
    uint8 optionalDVNThreshold;   // how many optional DVNs must verify
    address[] requiredDVNs;       // addresses of required DVNs
    address[] optionalDVNs;       // addresses of optional DVNs
}

Example configuration — require LayerZero Labs DVN and one of two optional DVNs:

UlnConfig memory ulnConfig = UlnConfig({
    confirmations: 15,                  // 15 block confirmations
    requiredDVNCount: 1,
    optionalDVNCount: 2,
    optionalDVNThreshold: 1,            // 1 of 2 optional must verify
    requiredDVNs: [LZ_DVN_ADDRESS],
    optionalDVNs: [GOOGLE_DVN_ADDRESS, POLYHEDRA_DVN_ADDRESS]
});

Configuring via EndpointV2

const endpointAbi = parseAbi([
  "function setConfig(address oapp, address lib, (uint32 eid, uint32 configType, bytes config)[] calldata params) external",
]);

// ULN config type for send library
const CONFIG_TYPE_ULN = 2;

// Encode the ULN config
// confirmations(uint64) + requiredDVNCount(uint8) + optionalDVNCount(uint8)
// + optionalDVNThreshold(uint8) + requiredDVNs(address[]) + optionalDVNs(address[])
import { encodeAbiParameters, parseAbiParameters } from "viem";

const ulnConfigEncoded = encodeAbiParameters(
  parseAbiParameters("uint64, uint8, uint8, uint8, address[], address[]"),
  [
    15n,                                // confirmations
    1,                                  // requiredDVNCount
    2,                                  // optionalDVNCount
    1,                                  // optionalDVNThreshold
    [LZ_DVN],                           // requiredDVNs
    [GOOGLE_DVN, POLYHEDRA_DVN],        // optionalDVNs
  ]
);

Security Best Practices

  • Always set at least one required DVN. The default config uses the LayerZero Labs DVN. For production, add at least one additional DVN (Google Cloud, Polyhedra, etc.).
  • Set block confirmations appropriate to the chain. Ethereum: 15+, L2s (Arbitrum, Base, Optimism): 5+. Higher confirmations reduce reorg risk.
  • Configure BOTH send and receive libraries. Security config applies per-direction. A message sent from Ethereum to Arbitrum uses Ethereum's send config AND Arbitrum's receive config. Configure both.

Message Options

Building Options with OptionsBuilder

import {OptionsBuilder} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol";

using OptionsBuilder for bytes;

// Gas limit for lzReceive execution on destination
bytes memory options = OptionsBuilder.newOptions()
    .addExecutorLzReceiveOption(200_000, 0);

// Gas limit + native airdrop to recipient on destination
bytes memory optionsWithDrop = OptionsBuilder.newOptions()
    .addExecutorLzReceiveOption(200_000, 0)
    .addExecutorNativeDropOption(1 ether, receiverAddress);

// Composed message — triggers lzCompose after lzReceive
bytes memory composedOptions = OptionsBuilder.newOptions()
    .addExecutorLzReceiveOption(200_000, 0)
    .addExecutorLzComposeOption(0, 100_000, 0); // index, gas, value

// Ordered delivery — enforce nonce ordering
bytes memory orderedOptions = OptionsBuilder.newOptions()
    .addExecutorLzReceiveOption(200_000, 0)
    .addExecutorOrderedExecutionOption();

Options Encoding in TypeScript

import { encodePacked } from "viem";

// Option type constants
const EXECUTOR_WORKER_ID = 1;
const OPTION_TYPE_LZRECEIVE = 1;
const OPTION_TYPE_NATIVE_DROP = 2;

// Encode lzReceive option: 200k gas, 0 value
// Format: workerID(uint8) + optionLength(uint16) + optionType(uint8) + gas(uint128) + value(uint128)
function buildLzReceiveOption(gasLimit: bigint, value: bigint = 0n): `0x${string}` {
  // Options V2 encoding
  const TYPE_3 = "0x0003" as `0x${string}`;
  const workerIdAndOption = encodePacked(
    ["uint8", "uint16", "uint8", "uint128", "uint128"],
    [EXECUTOR_WORKER_ID, 34, OPTION_TYPE_LZRECEIVE, gasLimit, value]
  );
  return `${TYPE_3}${workerIdAndOption.slice(2)}` as `0x${string}`;
}

const options = buildLzReceiveOption(200_000n);

Composed Messages

Composed messages allow an OApp to trigger follow-up logic after the initial lzReceive. The destination contract receives the message in lzReceive, then the Executor calls lzCompose separately.

// In your OApp
function _lzReceive(
    Origin calldata _origin,
    bytes32 _guid,
    bytes calldata _payload,
    address _executor,
    bytes calldata _extraData
) internal override {
    // Decode and store state from the message

    // Queue a composed message for follow-up execution
    endpoint.sendCompose(
        address(this), // composeTo — typically self
        _guid,
        0,             // compose index
        _payload       // data for lzCompose
    );
}

// Called by the Executor after lzReceive completes
function lzCompose(
    address _from,
    bytes32 _guid,
    bytes calldata _message,
    address _executor,
    bytes calldata _extraData
) external payable {
    require(msg.sender == address(endpoint), "Only endpoint");
    // Execute follow-up logic (swap, stake, etc.)
}

Deployment Pattern

Multi-Chain Deploy Sequence

  1. Deploy OApp on each chain (with that chain's EndpointV2 address)
  2. Set peers bidirectionally between every chain pair
  3. Configure DVNs for each pathway
  4. Verify with a test message
const ENDPOINT_V2: Record<number, Address> = {
  30101: "0x1a44076050125825900e736c501f859c50fE728c", // Ethereum
  30110: "0x1a44076050125825900e736c501f859c50fE728c", // Arbitrum
  30184: "0x1a44076050125825900e736c501f859c50fE728c", // Base
  30111: "0x1a44076050125825900e736c501f859c50fE728c", // Optimism
  30109: "0x1a44076050125825900e736c501f859c50fE728c", // Polygon
};

// After deploying OApp on each chain, set peers pairwise
async function setPeers(
  deployments: Map<number, Address>,
  walletClients: Map<number, typeof walletClient>,
  publicClients: Map<number, typeof publicClient>,
) {
  const eids = [...deployments.keys()];

  for (const srcEid of eids) {
    for (const dstEid of eids) {
      if (srcEid === dstEid) continue;

      const oapp = deployments.get(srcEid)!;
      const peer = deployments.get(dstEid)!;
      const client = walletClients.get(srcEid)!;
      const pub = publicClients.get(srcEid)!;

      const { request } = await pub.simulateContract({
        address: oapp,
        abi: oappAbi,
        functionName: "setPeer",
        args: [dstEid, addressToBytes32(peer)],
        account: account.address,
      });

      const hash = await client.writeContract(request);
      const receipt = await pub.waitForTransactionReceipt({ hash });
      if (receipt.status !== "success") {
        throw new Error(`setPeer failed: ${srcEid} -> ${dstEid}`);
      }
    }
  }
}

Hardhat Deploy Script

import { ethers } from "hardhat";

async function main() {
  const [deployer] = await ethers.getSigners();
  const endpointV2 = "0x1a44076050125825900e736c501f859c50fE728c";

  const MyOApp = await ethers.getContractFactory("MyOApp");
  const oapp = await MyOApp.deploy(endpointV2, deployer.address);
  await oapp.waitForDeployment();

  const address = await oapp.getAddress();
  console.log(`MyOApp deployed at: ${address}`);

  // Verify on explorer
  await run("verify:verify", {
    address,
    constructorArguments: [endpointV2, deployer.address],
  });
}

main().catch(console.error);

Foundry Deploy Script

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

import {Script, console} from "forge-std/Script.sol";
import {MyOApp} from "../src/MyOApp.sol";

contract DeployOApp is Script {
    function run() external {
        uint256 deployerKey = vm.envUint("PRIVATE_KEY");
        address endpoint = 0x1a44076050125825900e736c501f859c50fE728c;
        address delegate = vm.addr(deployerKey);

        vm.startBroadcast(deployerKey);
        MyOApp oapp = new MyOApp(endpoint, delegate);
        console.log("MyOApp deployed:", address(oapp));
        vm.stopBroadcast();
    }
}

Fee Estimation

Quoting Send Fees

Always quote before sending. The fee depends on payload size, message options (gas, native drop), DVN configuration, and destination chain gas prices.

const oappAbi = parseAbi([
  "function quote(uint32 dstEid, bytes calldata payload, bytes calldata options) view returns ((uint256 nativeFee, uint256 lzTokenFee) fee)",
]);

const fee = await publicClient.readContract({
  address: oappAddress,
  abi: oappAbi,
  functionName: "quote",
  args: [30110, payload, options],
});

// fee.nativeFee — amount of ETH/native token to send as msg.value
// fee.lzTokenFee — if paying with ZRO token (usually 0)

Fee Breakdown

ComponentDetermines
DVN feesCost of DVN verification (based on DVN count and destination)
Executor feeGas cost of calling lzReceive on destination + native drop
Treasury feeProtocol fee paid to LayerZero treasury

Paying with LZ Token (ZRO)

// To pay with ZRO instead of native:
// 1. Approve ZRO token to EndpointV2
// 2. Pass payInLzToken = true in quote
// 3. lzTokenFee will be non-zero, nativeFee reduced
MessagingFee memory fee = _quote(_dstEid, _payload, _options, true);
// fee.lzTokenFee > 0, fee.nativeFee may be lower

Error Handling

Common Reverts

ErrorCauseFix
NoPeerPeer not set for destination eidCall setPeer(dstEid, peerBytes32) on source
OnlyPeerMessage from unregistered senderSet peer on the receiving chain
InvalidEndpointCallDirect call instead of via endpointOnly EndpointV2 can call lzReceive
InsufficientFeemsg.value less than quoted feeCall _quote() or quoteSend() first, pass exact fee
LzTokenUnavailableTrying to pay with ZRO when not enabledPass false for payInLzToken parameter
InvalidOptionsMalformed options bytesUse OptionsBuilder to construct options
SlippageExceededOFT minAmountLD check failedIncrease minAmountLD tolerance or retry
InvalidAmountOFT amount below shared decimal minimumSend larger amount; dust below shared decimals is removed
UnauthorizedCaller is not the delegate/ownerCheck OApp ownership and delegate settings
InvalidEidEndpoint ID does not existUse correct eid from LayerZero docs (NOT chain ID)

Debugging Cross-Chain Failures

  1. Check source chain transaction. If it reverted, the message was never sent. Fix the source-side issue (fee, peer, options).

  2. Use LayerZero Scan. Go to layerzeroscan.com and enter the source tx hash. It shows message status: Sent, Verifying, Verified, Delivered, or Failed.

  3. Check DVN verification status. If stuck at "Verifying", DVNs have not confirmed yet. Wait for block confirmations, or check if your DVN config is valid.

  4. Check executor delivery. If verified but not delivered, the Executor may have failed. Common cause: insufficient gas in options. Increase lzReceiveOption gas limit.

  5. Retry failed messages. If lzReceive reverted on destination, the message is stored and can be retried:

const endpointAbi = parseAbi([
  "function retryPayload(uint32 srcEid, bytes32 sender, uint64 nonce, bytes calldata payload) external payable",
]);
  1. Common debugging commands:
# Check if peer is set
cast call <oapp_address> "peers(uint32)(bytes32)" 30110 --rpc-url $RPC_URL

# Check endpoint delegate
cast call <oapp_address> "endpoint()(address)" --rpc-url $RPC_URL

# Verify contract has code
cast code <oapp_address> --rpc-url $RPC_URL

Contract Addresses

Last verified: February 2026

EndpointV2

ChaineidEndpointV2
Ethereum301010x1a44076050125825900e736c501f859c50fE728c
Arbitrum301100x1a44076050125825900e736c501f859c50fE728c
Optimism301110x1a44076050125825900e736c501f859c50fE728c
Polygon301090x1a44076050125825900e736c501f859c50fE728c
Base301840x1a44076050125825900e736c501f859c50fE728c

Send/Receive Libraries (ULN302)

ChainSendUln302ReceiveUln302
Ethereum0xbB2Ea70C9E858123480642Cf96acbcCE1372dCe10xc02Ab410f0734EFa3F14628780e6e695156024C2
Arbitrum0x975bcD720be66659e3EB3C0e4F1866a3020E493A0x7B9E184e07a6EE1aC23eAe0fe8D6Be60f4f19eF3
Base0xB5320B0B3a13cC860893E2Bd79FCd7e13484Dda20xc70AB6f32772f59fBfc23889Caf4Ba3376C84bAf
Optimism0x1322871e4ab09Bc7f5717189434f97bBD9546e950x3c4962Ff6258dcfCafD23a814237571571899985
Polygon0x6c26c61a97006888ea9E4FA36584c7df57Cd9dA30x1322871e4ab09Bc7f5717189434f97bBD9546e95

LayerZero Labs DVN

ChainAddress
Ethereum0x589dEDbD617eE7783Ae3a7427E16b13280a2C00C
Arbitrum0x2f55C492897526677C5B68fb199ea31E2c126416
Base0x9e059a54699a285714207b43B055483E78FAac25
Optimism0x6A02D83e8d433304bba74EF1c427913958187142
Polygon0x23DE2FE932d9043291f870F07B7D2Bbca42e46c6

Default Executor

ChainAddress
Ethereum0x173272739Bd7Aa6e4e214714048a9fE699453059
Arbitrum0x31CAe3B7fB82d847621859571BF619D4600e37c8
Base0x2CCA08ae69E0C44b18a57Ab36A1CCb013C54B1d3
Optimism0x2D2ea0697bdbede3F01553D2Ae4B8d0c486B666e
Polygon0xCd3F213AD101472e1713C72B1697E727C803885b

References

AI Skill Finder

Ask me what skills you need

What are you building?

Tell me what you're working on and I'll find the best agent skills for you.