Comparing chainlink with optimism

chainlink

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/chainlink/SKILL.md

Chainlink

Chainlink provides decentralized oracle infrastructure: price feeds for DeFi pricing, VRF for provably fair randomness, Automation for scheduled/conditional on-chain execution, and CCIP for cross-chain messaging and token transfers.

What You Probably Got Wrong

  • latestRoundData() returns int256, not uint256 — Price can be negative (e.g., oil futures in 2020). Always check answer > 0 before casting.
  • Decimals vary per feed — ETH/USD has 8 decimals, ETH/BTC has 18 decimals, USDC/USD has 8. Always call decimals() or hardcode per known feed. Never assume 8.
  • VRF v2 is deprecated — use VRF v2.5 — VRF v2.5 supports both LINK and native payment, uses requestRandomWords() with a struct parameter, and has a different coordinator interface. Most LLM training data references VRF v2.
  • Staleness is not optional — A price feed can return a stale answer if the oracle network stops updating. You must check updatedAt against a heartbeat threshold. Feeds without staleness checks have caused protocol-draining exploits.
  • roundId can be zero on L2s — On Arbitrum/Optimism sequencer feeds, round semantics differ. Do not rely on roundId for ordering on L2 feeds.
  • CCIP is not Chainlink VRF — They are separate products. CCIP handles cross-chain messaging; VRF handles randomness. Different contracts, different billing.
  • Automation renamed from Keepers — The product is now called Chainlink Automation, not Keepers. The interface names changed: KeeperCompatibleInterface is now AutomationCompatibleInterface.

Price Feeds

AggregatorV3Interface

The core interface for reading Chainlink price data on-chain.

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

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal immutable priceFeed;

    // ETH/USD heartbeat: 3600s on mainnet, 86400s on Arbitrum
    uint256 private constant STALENESS_THRESHOLD = 3600;

    constructor(address feedAddress) {
        priceFeed = AggregatorV3Interface(feedAddress);
    }

    function getLatestPrice() public view returns (int256 price, uint8 feedDecimals) {
        (
            uint80 roundId,
            int256 answer,
            /* uint256 startedAt */,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        if (answer <= 0) revert InvalidPrice();
        if (updatedAt == 0) revert RoundNotComplete();
        if (block.timestamp - updatedAt > STALENESS_THRESHOLD) revert StalePrice();
        if (answeredInRound < roundId) revert StaleRound();

        return (answer, priceFeed.decimals());
    }

    /// @notice Normalize a feed answer to 18 decimals
    function normalizeToWad(int256 answer, uint8 feedDecimals) public pure returns (uint256) {
        if (answer <= 0) revert InvalidPrice();
        if (feedDecimals <= 18) {
            return uint256(answer) * 10 ** (18 - feedDecimals);
        }
        return uint256(answer) / 10 ** (feedDecimals - 18);
    }

    error InvalidPrice();
    error RoundNotComplete();
    error StalePrice();
    error StaleRound();
}

Reading Price Feeds with TypeScript (viem)

import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";

const AGGREGATOR_V3_ABI = parseAbi([
  "function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)",
  "function decimals() external view returns (uint8)",
  "function description() external view returns (string)",
]);

// ETH/USD on Ethereum mainnet
const ETH_USD_FEED = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" as const;
const STALENESS_THRESHOLD = 3600n;

const client = createPublicClient({
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

async function getPrice(feedAddress: `0x${string}`) {
  const [roundData, feedDecimals] = await Promise.all([
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "latestRoundData",
    }),
    client.readContract({
      address: feedAddress,
      abi: AGGREGATOR_V3_ABI,
      functionName: "decimals",
    }),
  ]);

  const [roundId, answer, , updatedAt, answeredInRound] = roundData;

  if (answer <= 0n) throw new Error("Invalid price: non-positive");
  if (updatedAt === 0n) throw new Error("Round not complete");

  const now = BigInt(Math.floor(Date.now() / 1000));
  if (now - updatedAt > STALENESS_THRESHOLD) {
    throw new Error(`Stale price: ${now - updatedAt}s old`);
  }
  if (answeredInRound < roundId) {
    throw new Error("Stale round: answeredInRound < roundId");
  }

  // Normalize to 18 decimals
  const normalized =
    feedDecimals <= 18
      ? answer * 10n ** (18n - BigInt(feedDecimals))
      : answer / 10n ** (BigInt(feedDecimals) - 18n);

  return {
    raw: answer,
    decimals: feedDecimals,
    normalized,
    updatedAt,
  };
}

// Usage
const ethPrice = await getPrice(ETH_USD_FEED);
console.log(`ETH/USD: $${Number(ethPrice.raw) / 10 ** ethPrice.decimals}`);

L2 Sequencer Uptime Feed

On L2s, check the sequencer uptime feed before trusting price data. If the sequencer was recently restarted, prices may be stale while oracles catch up.

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

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract L2PriceConsumer {
    AggregatorV3Interface internal immutable sequencerUptimeFeed;
    AggregatorV3Interface internal immutable priceFeed;

    // Grace period after sequencer comes back online
    uint256 private constant GRACE_PERIOD = 3600;

    constructor(address _sequencerFeed, address _priceFeed) {
        sequencerUptimeFeed = AggregatorV3Interface(_sequencerFeed);
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

    function getPrice() external view returns (int256) {
        (, int256 sequencerAnswer, , uint256 sequencerUpdatedAt, ) =
            sequencerUptimeFeed.latestRoundData();

        // answer == 0 means sequencer is up, answer == 1 means down
        if (sequencerAnswer != 0) revert SequencerDown();
        if (block.timestamp - sequencerUpdatedAt < GRACE_PERIOD) revert GracePeriodNotOver();

        (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        if (price <= 0) revert InvalidPrice();
        if (block.timestamp - updatedAt > 86400) revert StalePrice();

        return price;
    }

    error SequencerDown();
    error GracePeriodNotOver();
    error InvalidPrice();
    error StalePrice();
}

VRF v2.5

Chainlink VRF v2.5 provides provably fair, verifiable randomness. It uses subscription-based billing and supports payment in LINK or native token.

Requesting Randomness

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

import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";

contract RandomConsumer is VRFConsumerBaseV2Plus {
    uint256 public immutable subscriptionId;
    bytes32 public immutable keyHash;

    // 200k gas covers most callbacks; increase for complex logic
    uint32 private constant CALLBACK_GAS_LIMIT = 200_000;
    uint16 private constant REQUEST_CONFIRMATIONS = 3;
    uint32 private constant NUM_WORDS = 1;

    mapping(uint256 => address) public requestToSender;
    mapping(address => uint256) public results;

    event RandomnessRequested(uint256 indexed requestId, address indexed requester);
    event RandomnessFulfilled(uint256 indexed requestId, uint256 randomWord);

    constructor(
        uint256 _subscriptionId,
        address _vrfCoordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2Plus(_vrfCoordinator) {
        subscriptionId = _subscriptionId;
        keyHash = _keyHash;
    }

    function requestRandom() external returns (uint256 requestId) {
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: keyHash,
                subId: subscriptionId,
                requestConfirmations: REQUEST_CONFIRMATIONS,
                callbackGasLimit: CALLBACK_GAS_LIMIT,
                numWords: NUM_WORDS,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    // false = pay with LINK, true = pay with native
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );

        requestToSender[requestId] = msg.sender;
        emit RandomnessRequested(requestId, msg.sender);
    }

    function fulfillRandomWords(
        uint256 requestId,
        uint256[] calldata randomWords
    ) internal override {
        address requester = requestToSender[requestId];
        results[requester] = randomWords[0];
        emit RandomnessFulfilled(requestId, randomWords[0]);
    }
}

VRF Subscription Management (TypeScript)

import { createWalletClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const VRF_COORDINATOR_ABI = parseAbi([
  "function createSubscription() external returns (uint256 subId)",
  "function addConsumer(uint256 subId, address consumer) external",
  "function removeConsumer(uint256 subId, address consumer) external",
  "function getSubscription(uint256 subId) external view returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address subOwner, address[] consumers)",
  "function fundSubscriptionWithNative(uint256 subId) external payable",
]);

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);

const walletClient = createWalletClient({
  account,
  chain: mainnet,
  transport: http(process.env.RPC_URL),
});

// Ethereum mainnet VRF Coordinator v2.5
const VRF_COORDINATOR = "0xD7f86b4b8Cae7D942340FF628F82735b7a20893a" as const;

async function createSubscription() {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "createSubscription",
  });
  console.log("Subscription created, tx:", hash);
  return hash;
}

async function addConsumer(subId: bigint, consumerAddress: `0x${string}`) {
  const hash = await walletClient.writeContract({
    address: VRF_COORDINATOR,
    abi: VRF_COORDINATOR_ABI,
    functionName: "addConsumer",
    args: [subId, consumerAddress],
  });
  console.log("Consumer added, tx:", hash);
  return hash;
}

Automation (Keepers)

Chainlink Automation executes on-chain functions when conditions are met. Your contract implements checkUpkeep (off-chain simulation) and performUpkeep (on-chain execution).

AutomationCompatible Contract

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

import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol";

contract AutomatedCounter is AutomationCompatibleInterface {
    uint256 public counter;
    uint256 public lastTimestamp;
    uint256 public immutable interval;

    event CounterIncremented(uint256 indexed newValue, uint256 timestamp);

    constructor(uint256 _interval) {
        interval = _interval;
        lastTimestamp = block.timestamp;
    }

    /// @notice Called off-chain by Automation nodes to check if upkeep is needed
    /// @dev Must NOT modify state. Gas cost does not matter (simulated off-chain).
    function checkUpkeep(bytes calldata)
        external
        view
        override
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = (block.timestamp - lastTimestamp) >= interval;
        performData = abi.encode(counter);
    }

    /// @notice Called on-chain when checkUpkeep returns true
    /// @dev Re-validate the condition — checkUpkeep result may be stale
    function performUpkeep(bytes calldata) external override {
        if ((block.timestamp - lastTimestamp) < interval) revert UpkeepNotNeeded();

        lastTimestamp = block.timestamp;
        counter += 1;
        emit CounterIncremented(counter, block.timestamp);
    }

    error UpkeepNotNeeded();
}

Log-Triggered Automation

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

import {ILogAutomation, Log} from "@chainlink/contracts/src/v0.8/automation/interfaces/ILogAutomation.sol";

contract LogTriggeredUpkeep is ILogAutomation {
    event ActionPerformed(address indexed sender, uint256 amount);

    /// @notice Called when a matching log event is detected
    function checkLog(Log calldata log, bytes memory)
        external
        pure
        returns (bool upkeepNeeded, bytes memory performData)
    {
        upkeepNeeded = true;
        performData = log.data;
    }

    function performUpkeep(bytes calldata performData) external {
        (address sender, uint256 amount) = abi.decode(performData, (address, uint256));
        emit ActionPerformed(sender, amount);
    }
}

CCIP (Cross-Chain Interoperability Protocol)

CCIP enables sending arbitrary messages and tokens between supported chains.

Sending a Cross-Chain Message

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

import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract CCIPSender {
    IRouterClient public immutable router;
    IERC20 public immutable linkToken;

    event MessageSent(bytes32 indexed messageId, uint64 indexed destinationChain);

    constructor(address _router, address _link) {
        router = IRouterClient(_router);
        linkToken = IERC20(_link);
    }

    function sendMessage(
        uint64 destinationChainSelector,
        address receiver,
        bytes calldata data
    ) external returns (bytes32 messageId) {
        Client.EVM2AnyMessage memory message = Client.EVM2AnyMessage({
            receiver: abi.encode(receiver),
            data: data,
            tokenAmounts: new Client.EVMTokenAmount[](0),
            extraArgs: Client._argsToBytes(
                Client.EVMExtraArgsV2({gasLimit: 200_000, allowOutOfOrderExecution: true})
            ),
            feeToken: address(linkToken)
        });

        uint256 fees = router.getFee(destinationChainSelector, message);
        linkToken.approve(address(router), fees);

        messageId = router.ccipSend(destinationChainSelector, message);
        emit MessageSent(messageId, destinationChainSelector);
    }
}

Receiving a Cross-Chain Message

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

import {CCIPReceiver} from "@chainlink/contracts-ccip/src/v0.8/ccip/applications/CCIPReceiver.sol";
import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol";

contract CCIPReceiverExample is CCIPReceiver {
    // Allowlist source chains and senders to prevent unauthorized messages
    mapping(uint64 => mapping(address => bool)) public allowlistedSenders;
    address public owner;

    event MessageReceived(
        bytes32 indexed messageId,
        uint64 indexed sourceChainSelector,
        address sender,
        bytes data
    );

    constructor(address _router) CCIPReceiver(_router) {
        owner = msg.sender;
    }

    function allowlistSender(
        uint64 chainSelector,
        address sender,
        bool allowed
    ) external {
        if (msg.sender != owner) revert Unauthorized();
        allowlistedSenders[chainSelector][sender] = allowed;
    }

    function _ccipReceive(Client.Any2EVMMessage memory message) internal override {
        address sender = abi.decode(message.sender, (address));
        if (!allowlistedSenders[message.sourceChainSelector][sender]) {
            revert SenderNotAllowlisted();
        }

        emit MessageReceived(
            message.messageId,
            message.sourceChainSelector,
            sender,
            message.data
        );
    }

    error Unauthorized();
    error SenderNotAllowlisted();
}

Contract Addresses

Last verified: 2025-05-01

Price Feeds

PairEthereum MainnetArbitrum OneBase
ETH/USD0x5f4eC3Df9cbd43714FE2740f5E3616155c5b84190x639Fe6ab55C921f74e7fac1ee960C0B6293ba6120x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70
BTC/USD0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c0x6ce185860a4963106506C203335A2910413708e90x64c911996D3c6aC71f9b455B1E8E7M1BbDC942BAe
USDC/USD0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f60x50834F3163758fcC1Df9973b6e91f0F0F0434aD30x7e860098F58bBFC8648a4311b374B1D669a2bc6B
LINK/USD0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c0x86E53CF1B870786351Da77A57575e79CB55812CB0x17CAb8FE31cA45e4684E33E3D258F20E88B8fD8B

Sequencer Uptime Feeds

ChainAddress
Arbitrum0xFdB631F5EE196F0ed6FAa767959853A9F217697D
Base0xBCF85224fc0756B9Fa45aAb7d2257eC1673570EF
Optimism0x371EAD81c9102C9BF4874A9075FFFf170F2Ee389

VRF v2.5 Coordinators

ChainCoordinator
Ethereum0xD7f86b4b8Cae7D942340FF628F82735b7a20893a
Arbitrum0x3C0Ca683b403E37668AE3DC4FB62F4B29B6f7a3e
Base0xd5D517aBE5cF79B7e95eC98dB0f0277788aFF634

CCIP Routers

ChainRouterChain Selector
Ethereum0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D5009297550715157269
Arbitrum0x141fa059441E0ca23ce184B6A78bafD2A517DdE84949039107694359620
Base0x881e3A65B4d4a04dD529061dd0071cf975F58bCD15971525489660198786

LINK Token

ChainAddress
Ethereum0x514910771AF9Ca656af840dff83E8264EcF986CA
Arbitrum0xf97f4df75117a78c1A5a0DBb814Af92458539FB4
Base0x88Fb150BDc53A65fe94Dea0c9BA0a6dAf8C6e196

Error Handling

Error / SymptomCauseFix
answer <= 0 from price feedFeed returning invalid/negative priceCheck answer > 0 before using; revert or use fallback oracle
block.timestamp - updatedAt > thresholdOracle stopped updating (network congestion, feed deprecation)Implement staleness check with per-feed heartbeat threshold
answeredInRound < roundIdAnswer is from a previous roundReject stale round data
VRF callback revertscallbackGasLimit too low for your fulfillRandomWords logicIncrease callbackGasLimit; test gas usage on fork
VRF request pending indefinitelySubscription underfunded, consumer not added, or wrong keyHashFund subscription, verify consumer is registered, use correct key hash for your chain
Automation performUpkeep not firingcheckUpkeep returns false, upkeep underfunded, or gas price too highDebug checkUpkeep locally; fund upkeep; check min balance requirements
CCIP InsufficientFeeTokenAmountNot enough LINK approved for feesCall router.getFee() first, then approve that amount + buffer
CCIP message not deliveredDestination contract reverts, sender not allowlisted, or chain selector wrongCheck receiver contract, verify allowlist, confirm chain selectors from docs

Security Considerations

Price Feed Safety

  1. Always check staleness — Every latestRoundData() call must validate updatedAt against the feed's heartbeat. ETH/USD on mainnet has a 3600s heartbeat; on Arbitrum it is 86400s. Check Chainlink's feed page for per-feed heartbeats.

  2. Sanity-bound oracle prices — If a feed reports ETH at $0.01 or $1,000,000, something is wrong. Add upper and lower bounds based on reasonable price ranges and revert or pause if breached.

uint256 private constant MIN_ETH_PRICE = 100e8;       // $100
uint256 private constant MAX_ETH_PRICE = 100_000e8;    // $100,000

function getSafePrice(AggregatorV3Interface feed) internal view returns (uint256) {
    (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
    if (answer <= 0) revert InvalidPrice();
    if (block.timestamp - updatedAt > 3600) revert StalePrice();
    if (uint256(answer) < MIN_ETH_PRICE || uint256(answer) > MAX_ETH_PRICE) {
        revert PriceOutOfBounds();
    }
    return uint256(answer);
}
  1. L2 sequencer check — On Arbitrum, Base, and Optimism, always check the sequencer uptime feed. A sequencer outage means oracle updates are delayed; using stale prices during recovery has caused exploits.

  2. Decimal normalization — Never assume 8 decimals. Always call feed.decimals() or use known constants per feed. When combining two feeds (e.g., TOKEN/ETH and ETH/USD), handle decimals carefully to avoid overflow or truncation.

  3. Multi-oracle fallback — For critical DeFi protocols, use Chainlink as primary but have a fallback (e.g., Uniswap TWAP or Pyth) to prevent single oracle dependency from freezing your protocol.

VRF Safety

  • Never use block values (block.timestamp, block.prevrandao) as randomness — they are manipulable by validators.
  • Store the requestId -> user mapping before the callback. The callback is asynchronous and you need to know who requested it.
  • Set callbackGasLimit high enough for your logic but not excessively — you pay for unused gas.

Automation Safety

  • Always re-validate conditions in performUpkeep. The checkUpkeep result may be stale by the time performUpkeep executes on-chain.
  • checkUpkeep runs off-chain in simulation — it cannot modify state. Any state changes will be reverted.

CCIP Safety

  • Always allowlist source chains and sender addresses on your receiver contract. Without this, anyone on any supported chain can send messages to your contract.
  • Handle message failures gracefully. If _ccipReceive reverts, the message can be manually executed later, but your contract should not end up in an inconsistent state from partial execution.

Alternative Oracles

For use cases where Chainlink's push model isn't optimal, consider these alternatives:

Pyth Network (pyth-evm skill) — Pull oracle model where consumers fetch and submit price updates on-demand. Best for: sub-second price freshness (~400ms on Pythnet), confidence intervals (statistical uncertainty bounds), MEV-protected liquidations via Express Relay, and non-EVM chains (Solana, Sui, Aptos). Trade-off: consumers pay gas for price updates (~120-150K gas per feed).

When to use Chainlink vs Pyth:

  • Chainlink: Zero-cost reads (DON sponsors updates), broadest EVM feed coverage (1000+), VRF/CCIP/Automation ecosystem, well-established data quality
  • Pyth: Sub-second freshness, confidence intervals, historical price verification, MEV protection, 50+ EVM chains + non-EVM

See also: redstone skill for another pull oracle alternative.

References

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/optimism/SKILL.md

Optimism

Optimism is an EVM-equivalent Layer 2 using optimistic rollups. Transactions execute on L2 with data posted to Ethereum L1 for security. The OP Stack is the modular framework powering OP Mainnet, Base, Zora, Mode, and the broader Superchain. Smart contracts deploy identically to Ethereum — no custom compiler, no special opcodes.

What You Probably Got Wrong

  • OP Mainnet IS EVM-equivalent, not just EVM-compatible — Your Solidity contracts deploy without modification. No --legacy flag, no custom compiler. forge create and hardhat deploy work identically to Ethereum. If someone tells you to change your Solidity for "OP compatibility", they are wrong.
  • Gas has two components, not one — Every transaction pays L2 execution gas AND an L1 data fee for posting calldata/blobs to Ethereum. If you only estimate L2 gas via eth_estimateGas, your cost estimate will be wrong. The L1 data fee often dominates total cost. Use the GasPriceOracle predeploy at 0x420000000000000000000000000000000000000F.
  • L2→L1 withdrawals take 7 days, not minutes — L1→L2 deposits finalize in ~1-3 minutes. L2→L1 withdrawals require a 7-day challenge period (the "fault proof window"). Users must prove the withdrawal, wait 7 days, then finalize. Three separate transactions on L1. If your UX assumes instant bridging both ways, it is broken.
  • block.number returns the L2 block number, not L1 — On OP Mainnet, block.number is the L2 block number. To get the L1 block number, read the L1Block predeploy at 0x4200000000000000000000000000000000000015. L2 blocks are produced every 2 seconds.
  • msg.sender works normally — there is no tx.origin aliasing on L2 — Cross-domain messages from L1 to L2 alias the sender address (add 0x1111000000000000000000000000000000001111). But for normal L2 transactions, msg.sender behaves exactly like Ethereum. Only worry about aliasing when receiving L1→L2 messages in your contract.
  • Predeploy contracts live at fixed addresses starting with 0x4200... — These are NOT deployed by you. They exist at genesis. L2CrossDomainMessenger, L2StandardBridge, GasPriceOracle, L1Block, and others all live at hardcoded addresses in the 0x4200... range. Do not try to deploy them.
  • The sequencer is centralized but cannot steal funds — The sequencer orders transactions and proposes state roots. If it goes down, you cannot submit new transactions until it recovers (or until permissionless fault proofs allow forced inclusion). But the sequencer cannot forge invalid state — the fault proof system protects withdrawals.
  • EIP-4844 blob data changed the gas model — After the Ecotone upgrade (March 2024), OP Mainnet posts data using EIP-4844 blobs instead of calldata. This reduced L1 data fees by ~10-100x. The GasPriceOracle methods changed. If you are reading pre-Ecotone documentation, the fee formulas are outdated.
  • SuperchainERC20 is not a standard ERC20 — It is a cross-chain token standard for OP Stack chains that enables native interop between Superchain members. Tokens must implement ICrosschainERC20 with crosschainMint and crosschainBurn. Do not assume a regular ERC20 works across chains.

Quick Start

Chain Configuration

import { defineChain } from "viem";
import { optimism, optimismSepolia } from "viem/chains";

// OP Mainnet is built-in
// Chain ID: 10
// RPC: https://mainnet.optimism.io
// Explorer: https://optimistic.etherscan.io

// OP Sepolia is also built-in
// Chain ID: 11155420
// RPC: https://sepolia.optimism.io
// Explorer: https://sepolia-optimistic.etherscan.io

Environment Setup

# .env
PRIVATE_KEY=your_private_key_here
OP_MAINNET_RPC=https://mainnet.optimism.io
OP_SEPOLIA_RPC=https://sepolia.optimism.io
ETHERSCAN_API_KEY=your_optimistic_etherscan_api_key

Viem Client Setup

import { createPublicClient, createWalletClient, http } from "viem";
import { optimism } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(`0x${process.env.PRIVATE_KEY}`);

const publicClient = createPublicClient({
  chain: optimism,
  transport: http(process.env.OP_MAINNET_RPC),
});

const walletClient = createWalletClient({
  account,
  chain: optimism,
  transport: http(process.env.OP_MAINNET_RPC),
});

Chain Configuration

PropertyOP MainnetOP Sepolia
Chain ID1011155420
CurrencyETHETH
RPChttps://mainnet.optimism.iohttps://sepolia.optimism.io
Explorerhttps://optimistic.etherscan.iohttps://sepolia-optimistic.etherscan.io
Block time2 seconds2 seconds
Withdrawal period7 days~12 seconds (testnet)

Alternative RPCs

ProviderEndpoint
Alchemyhttps://opt-mainnet.g.alchemy.com/v2/<KEY>
Infurahttps://optimism-mainnet.infura.io/v3/<KEY>
QuickNodeCustom endpoint per project
Conduithttps://rpc.optimism.io

Deployment

OP Mainnet is EVM-equivalent. Deploy exactly as you would to Ethereum.

Foundry

# Deploy to OP Mainnet
forge create src/MyContract.sol:MyContract \
  --rpc-url $OP_MAINNET_RPC \
  --private-key $PRIVATE_KEY \
  --broadcast

# Deploy with constructor args
forge create src/MyToken.sol:MyToken \
  --rpc-url $OP_MAINNET_RPC \
  --private-key $PRIVATE_KEY \
  --constructor-args "MyToken" "MTK" 18 \
  --broadcast

# Deploy via script
forge script script/Deploy.s.sol:DeployScript \
  --rpc-url $OP_MAINNET_RPC \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify \
  --etherscan-api-key $ETHERSCAN_API_KEY

Hardhat

// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

const config: HardhatUserConfig = {
  solidity: "0.8.24",
  networks: {
    optimism: {
      url: process.env.OP_MAINNET_RPC || "https://mainnet.optimism.io",
      accounts: [process.env.PRIVATE_KEY!],
    },
    optimismSepolia: {
      url: process.env.OP_SEPOLIA_RPC || "https://sepolia.optimism.io",
      accounts: [process.env.PRIVATE_KEY!],
    },
  },
  etherscan: {
    apiKey: {
      optimisticEthereum: process.env.ETHERSCAN_API_KEY!,
      optimisticSepolia: process.env.ETHERSCAN_API_KEY!,
    },
  },
};

export default config;
npx hardhat run scripts/deploy.ts --network optimism

Verification

Foundry

# Verify after deployment
forge verify-contract <DEPLOYED_ADDRESS> src/MyContract.sol:MyContract \
  --chain-id 10 \
  --etherscan-api-key $ETHERSCAN_API_KEY

# Verify with constructor args
forge verify-contract <DEPLOYED_ADDRESS> src/MyToken.sol:MyToken \
  --chain-id 10 \
  --etherscan-api-key $ETHERSCAN_API_KEY \
  --constructor-args $(cast abi-encode "constructor(string,string,uint8)" "MyToken" "MTK" 18)

Hardhat

npx hardhat verify --network optimism <DEPLOYED_ADDRESS> "MyToken" "MTK" 18

Blockscout

OP Mainnet also has a Blockscout explorer at https://optimism.blockscout.com. Verification works via the standard Blockscout API — set the verifier URL in Foundry:

forge verify-contract <DEPLOYED_ADDRESS> src/MyContract.sol:MyContract \
  --verifier blockscout \
  --verifier-url https://optimism.blockscout.com/api/

Cross-Chain Messaging

The CrossDomainMessenger is the canonical way to send arbitrary messages between L1 and L2. It handles replay protection, sender authentication, and gas forwarding.

Architecture

L1 → L2 (Deposits):
  User → L1CrossDomainMessenger → OptimismPortal → L2CrossDomainMessenger → Target

L2 → L1 (Withdrawals):
  User → L2CrossDomainMessenger → L2ToL1MessagePasser → [7 day wait] → OptimismPortal → L1CrossDomainMessenger → Target

L1 → L2 Message (Deposit)

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

interface IL1CrossDomainMessenger {
    function sendMessage(
        address _target,
        bytes calldata _message,
        uint32 _minGasLimit
    ) external payable;
}

contract L1Sender {
    IL1CrossDomainMessenger public immutable messenger;

    constructor(address _messenger) {
        messenger = IL1CrossDomainMessenger(_messenger);
    }

    /// @notice Send a message from L1 to a contract on L2.
    /// @param l2Target The L2 contract address to call.
    /// @param message The calldata to send to the L2 target.
    /// @param minGasLimit Minimum gas for L2 execution. Overestimate — unused gas is NOT refunded to L1.
    function sendToL2(
        address l2Target,
        bytes calldata message,
        uint32 minGasLimit
    ) external payable {
        messenger.sendMessage{value: msg.value}(l2Target, message, minGasLimit);
    }
}

L2 → L1 Message (Withdrawal)

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

interface IL2CrossDomainMessenger {
    function sendMessage(
        address _target,
        bytes calldata _message,
        uint32 _minGasLimit
    ) external payable;

    function xDomainMessageSender() external view returns (address);
}

contract L2Sender {
    /// @dev L2CrossDomainMessenger predeploy address — same on all OP Stack chains
    IL2CrossDomainMessenger public constant MESSENGER =
        IL2CrossDomainMessenger(0x4200000000000000000000000000000000000007);

    function sendToL1(
        address l1Target,
        bytes calldata message,
        uint32 minGasLimit
    ) external payable {
        MESSENGER.sendMessage{value: msg.value}(l1Target, message, minGasLimit);
    }
}

Receiving Cross-Chain Messages

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

interface ICrossDomainMessenger {
    function xDomainMessageSender() external view returns (address);
}

contract L2Receiver {
    ICrossDomainMessenger public constant MESSENGER =
        ICrossDomainMessenger(0x4200000000000000000000000000000000000007);

    address public immutable l1Sender;

    constructor(address _l1Sender) {
        l1Sender = _l1Sender;
    }

    modifier onlyFromL1Sender() {
        require(
            msg.sender == address(MESSENGER) &&
            MESSENGER.xDomainMessageSender() == l1Sender,
            "Not authorized L1 sender"
        );
        _;
    }

    function handleMessage(uint256 value) external onlyFromL1Sender {
        // Process the cross-chain message
    }
}

Sender Aliasing

When an L1 contract sends a message to L2, the apparent msg.sender on L2 is the aliased address:

l2Sender = l1ContractAddress + 0x1111000000000000000000000000000000001111

The CrossDomainMessenger handles un-aliasing internally. If you bypass the messenger and send directly via OptimismPortal, you must account for aliasing yourself.

Predeploy Contracts

These contracts exist at genesis on every OP Stack chain. Do not deploy them — they are already there.

ContractAddressPurpose
L2ToL1MessagePasser0x4200000000000000000000000000000000000016Initiates L2→L1 withdrawals
L2CrossDomainMessenger0x4200000000000000000000000000000000000007Sends/receives cross-chain messages
L2StandardBridge0x4200000000000000000000000000000000000010Bridges ETH and ERC20 tokens
L2ERC721Bridge0x4200000000000000000000000000000000000014Bridges ERC721 tokens
GasPriceOracle0x420000000000000000000000000000000000000FL1 data fee calculation
L1Block0x4200000000000000000000000000000000000015Exposes L1 block info on L2
WETH90x4200000000000000000000000000000000000006Wrapped ETH
L1BlockNumber0x4200000000000000000000000000000000000013L1 block number (deprecated, use L1Block)
SequencerFeeVault0x4200000000000000000000000000000000000011Collects sequencer fees
BaseFeeVault0x4200000000000000000000000000000000000019Collects base fees
L1FeeVault0x420000000000000000000000000000000000001ACollects L1 data fees
GovernanceToken0x4200000000000000000000000000000000000042OP token on L2

Reading L1 Block Info

interface IL1Block {
    function number() external view returns (uint64);
    function timestamp() external view returns (uint64);
    function basefee() external view returns (uint256);
    function hash() external view returns (bytes32);
    function batcherHash() external view returns (bytes32);
    function l1FeeOverhead() external view returns (uint256);
    function l1FeeScalar() external view returns (uint256);
    function blobBaseFee() external view returns (uint256);
    function baseFeeScalar() external view returns (uint32);
    function blobBaseFeeScalar() external view returns (uint32);
}

// Usage
IL1Block constant L1_BLOCK = IL1Block(0x4200000000000000000000000000000000000015);
uint64 l1BlockNumber = L1_BLOCK.number();
uint256 l1BaseFee = L1_BLOCK.basefee();

Gas Model

Every OP Mainnet transaction pays two fees:

  1. L2 execution fee — Standard EVM gas, priced by L2 basefee + optional priority fee. Calculated identically to Ethereum.
  2. L1 data fee — Cost of posting the transaction's data to Ethereum L1 as calldata or blob data. This is the OP-specific component.

Post-Ecotone Formula (Current)

After the Ecotone upgrade (March 2024), L1 data fee uses a two-component formula based on calldata gas and blob gas:

l1DataFee = (l1BaseFeeScalar * l1BaseFee * 16 + l1BlobBaseFeeScalar * l1BlobBaseFee) * compressedTxSize / 1e6
  • l1BaseFee — Ethereum L1 base fee (from L1Block predeploy)
  • l1BlobBaseFee — EIP-4844 blob base fee (from L1Block predeploy)
  • l1BaseFeeScalar — System-configured scalar for calldata cost component
  • l1BlobBaseFeeScalar — System-configured scalar for blob cost component
  • compressedTxSize — Estimated compressed size of the signed transaction

GasPriceOracle

interface IGasPriceOracle {
    /// @notice Estimate L1 data fee for raw signed transaction bytes
    function getL1Fee(bytes memory _data) external view returns (uint256);

    /// @notice Get current L1 base fee (read from L1Block)
    function l1BaseFee() external view returns (uint256);

    /// @notice Ecotone: get blob base fee
    function blobBaseFee() external view returns (uint256);

    /// @notice Ecotone: get base fee scalar
    function baseFeeScalar() external view returns (uint32);

    /// @notice Ecotone: get blob base fee scalar
    function blobBaseFeeScalar() external view returns (uint32);

    /// @notice Check if Ecotone is active
    function isEcotone() external view returns (bool);

    /// @notice Check if Fjord is active
    function isFjord() external view returns (bool);

    /// @notice Fjord: estimate compressed size using FastLZ
    function getL1GasUsed(bytes memory _data) external view returns (uint256);
}

IGasPriceOracle constant GAS_ORACLE =
    IGasPriceOracle(0x420000000000000000000000000000000000000F);

Estimating Total Cost in TypeScript

import { createPublicClient, http, parseAbi } from "viem";
import { optimism } from "viem/chains";

const client = createPublicClient({
  chain: optimism,
  transport: http(),
});

const GAS_ORACLE = "0x420000000000000000000000000000000000000F" as const;

const gasPriceOracleAbi = parseAbi([
  "function getL1Fee(bytes memory _data) external view returns (uint256)",
  "function l1BaseFee() external view returns (uint256)",
  "function blobBaseFee() external view returns (uint256)",
  "function baseFeeScalar() external view returns (uint32)",
  "function blobBaseFeeScalar() external view returns (uint32)",
]);

async function estimateTotalCost(serializedTx: `0x${string}`) {
  const [l2GasEstimate, gasPrice, l1DataFee] = await Promise.all([
    client.estimateGas({ data: serializedTx }),
    client.getGasPrice(),
    client.readContract({
      address: GAS_ORACLE,
      abi: gasPriceOracleAbi,
      functionName: "getL1Fee",
      args: [serializedTx],
    }),
  ]);

  const l2ExecutionFee = l2GasEstimate * gasPrice;
  const totalFee = l2ExecutionFee + l1DataFee;

  return {
    l2ExecutionFee,
    l1DataFee,
    totalFee,
  };
}

Gas Optimization Tips

  • Minimize calldata: the L1 data fee scales with transaction data size. Fewer bytes = lower L1 fee.
  • Use 0 bytes when possible: zero bytes cost 4 gas in calldata vs 16 gas for non-zero bytes.
  • Batch operations: one large transaction costs less in L1 data fee overhead than many small ones.
  • After Ecotone, blob pricing makes L1 data fees much cheaper and more stable than pre-Ecotone calldata pricing.

Standard Bridge

The Standard Bridge enables ETH and ERC20 transfers between L1 and L2. It is a pair of contracts: L1StandardBridge on Ethereum and L2StandardBridge (predeploy) on OP Mainnet.

Bridge ETH: L1 → L2

interface IL1StandardBridge {
    /// @notice Bridge ETH to L2. Appears at recipient address on L2 after ~1-3 min.
    function depositETH(uint32 _minGasLimit, bytes calldata _extraData) external payable;

    /// @notice Bridge ETH to a different address on L2.
    function depositETHTo(
        address _to,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external payable;
}

Bridge ETH: L2 → L1

interface IL2StandardBridge {
    /// @notice Initiate ETH withdrawal to L1. Requires prove + finalize after 7 days.
    function withdraw(
        address _l2Token,
        uint256 _amount,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external payable;
}

// Withdraw ETH from L2 to L1
// _l2Token = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000 (legacy ETH representation)
// Send ETH as msg.value, set _amount to the same value

Bridge ERC20: L1 → L2

interface IL1StandardBridge {
    /// @notice Bridge ERC20 to L2. Token must have a corresponding L2 representation.
    function depositERC20(
        address _l1Token,
        address _l2Token,
        uint256 _amount,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external;

    function depositERC20To(
        address _l1Token,
        address _l2Token,
        uint256 _amount,
        address _to,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external;
}

Bridge ERC20: L2 → L1

interface IL2StandardBridge {
    function withdraw(
        address _l2Token,
        uint256 _amount,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external payable;

    function withdrawTo(
        address _l2Token,
        address _to,
        uint256 _amount,
        uint32 _minGasLimit,
        bytes calldata _extraData
    ) external payable;
}

Withdrawal Lifecycle (L2 → L1)

Every L2→L1 withdrawal requires three L1 transactions:

  1. Initiate — Call withdraw on L2StandardBridge or L2CrossDomainMessenger. Produces a withdrawal hash.
  2. Prove — After the L2 output root containing your withdrawal is proposed on L1 (~1 hour), call proveWithdrawalTransaction on OptimismPortal.
  3. Finalize — After the 7-day challenge period, call finalizeWithdrawalTransaction on OptimismPortal.
import { getWithdrawals, getL2Output } from "viem/op-stack";

// After initiating withdrawal on L2, get the receipt
const l2Receipt = await publicClient.getTransactionReceipt({ hash: l2TxHash });

// Build withdrawal proof (after output root is proposed, ~1 hour)
const output = await getL2Output(l1Client, {
  l2BlockNumber: l2Receipt.blockNumber,
  targetChain: optimism,
});

// Prove on L1
const proveHash = await walletClient.proveWithdrawal({
  output,
  withdrawal: withdrawals[0],
  targetChain: optimism,
});

// Wait 7 days, then finalize on L1
const finalizeHash = await walletClient.finalizeWithdrawal({
  withdrawal: withdrawals[0],
  targetChain: optimism,
});

SuperchainERC20

SuperchainERC20 is a cross-chain token standard enabling native token transfers between OP Stack chains in the Superchain. Tokens implementing this standard can move between chains without traditional bridge locking.

Interface

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @notice Interface for tokens that support cross-chain transfers within the Superchain.
interface ICrosschainERC20 {
    /// @notice Emitted when tokens are minted via a cross-chain transfer.
    event CrosschainMint(address indexed to, uint256 amount, address indexed sender);

    /// @notice Emitted when tokens are burned for a cross-chain transfer.
    event CrosschainBurn(address indexed from, uint256 amount, address indexed sender);

    /// @notice Mint tokens on this chain as part of a cross-chain transfer.
    /// @dev Only callable by the SuperchainTokenBridge.
    function crosschainMint(address _to, uint256 _amount) external;

    /// @notice Burn tokens on this chain to initiate a cross-chain transfer.
    /// @dev Only callable by the SuperchainTokenBridge.
    function crosschainBurn(address _from, uint256 _amount) external;
}

Implementation

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ICrosschainERC20} from "./ICrosschainERC20.sol";

/// @dev SuperchainTokenBridge predeploy address — same on all OP Stack chains
address constant SUPERCHAIN_TOKEN_BRIDGE = 0x4200000000000000000000000000000000000028;

contract MySuperchainToken is ERC20, ICrosschainERC20 {
    constructor() ERC20("MySuperchainToken", "MST") {
        _mint(msg.sender, 1_000_000 * 1e18);
    }

    function crosschainMint(address _to, uint256 _amount) external override {
        require(msg.sender == SUPERCHAIN_TOKEN_BRIDGE, "Only bridge");
        _mint(_to, _amount);
        emit CrosschainMint(_to, _amount, msg.sender);
    }

    function crosschainBurn(address _from, uint256 _amount) external override {
        require(msg.sender == SUPERCHAIN_TOKEN_BRIDGE, "Only bridge");
        _burn(_from, _amount);
        emit CrosschainBurn(_from, _amount, msg.sender);
    }
}

Cross-Chain Transfer Flow

  1. User calls SuperchainTokenBridge.sendERC20 on the source chain
  2. Bridge calls crosschainBurn on the token contract (burns on source)
  3. A cross-chain message is relayed to the destination chain
  4. Bridge calls crosschainMint on the destination chain's token contract (mints on destination)

OP Stack

The OP Stack is the modular, open-source framework for building L2 blockchains. OP Mainnet, Base, Zora, Mode, and others are all OP Stack chains forming the Superchain.

Key Components

ComponentDescription
op-nodeConsensus client — derives L2 blocks from L1 data
op-gethExecution client — modified go-ethereum
op-batcherPosts transaction data to L1 (calldata or blobs)
op-proposerProposes L2 output roots to L1
op-challengerRuns fault proof games to challenge invalid proposals

Superchain

The Superchain is a network of OP Stack chains sharing:

  • Bridge contracts on L1
  • Sequencer coordination
  • Governance via the Optimism Collective
  • Interoperability messaging

Current Superchain members include OP Mainnet, Base, Zora, Mode, Fraxtal, Metal, and others. All share the same upgrade path and security model.

Building a Custom OP Chain

Use the OP Stack to launch your own chain:

# Clone the optimism monorepo
git clone https://github.com/ethereum-optimism/optimism.git
cd optimism

# Install dependencies
pnpm install

# Configure your chain (edit deploy-config)
# Deploy L1 contracts
# Start op-node, op-geth, op-batcher, op-proposer

Refer to the OP Stack Getting Started Guide for complete chain deployment.

Governance

The Optimism Collective governs the protocol through a bicameral system:

  • Token House — OP token holders vote on protocol upgrades, incentive programs, and treasury allocations
  • Citizens' House — Soulbound "citizen" badges vote on retroactive public goods funding (RetroPGF)

OP Token

PropertyValue
Address (L2)0x4200000000000000000000000000000000000042
Address (L1)0x4200000000000000000000000000000000000042 is the L2 predeploy; L1 address is 0x4200000000000000000000000000000000000042 bridged
Total supply4,294,967,296 (2^32)
TypeGovernance only (no fee burn or staking yield)

Delegation

OP token holders delegate voting power to active governance participants:

import { parseAbi } from "viem";

const opTokenAbi = parseAbi([
  "function delegate(address delegatee) external",
  "function delegates(address account) external view returns (address)",
  "function getVotes(address account) external view returns (uint256)",
]);

const OP_TOKEN = "0x4200000000000000000000000000000000000042" as const;

// Delegate voting power
const hash = await walletClient.writeContract({
  address: OP_TOKEN,
  abi: opTokenAbi,
  functionName: "delegate",
  args: [delegateAddress],
});

Key Differences from Ethereum

FeatureEthereumOP Mainnet
Block time12 seconds2 seconds
Gas pricingSingle base feeL2 execution + L1 data fee
block.numberL1 block numberL2 block number
Finality~15 minutes (2 epochs)7 days for L2→L1 (challenge period)
SequencingDecentralized validatorsCentralized sequencer (OP Labs)
PREVRANDAOBeacon chain randomnessSequencer-set value (NOT random, do NOT use for randomness)
PUSH0Supported (Shanghai+)Supported
block.difficultyAlways 0 post-mergeAlways 0

Opcodes Differences

  • PREVRANDAO (formerly DIFFICULTY) — Returns the sequencer-set value, NOT true randomness. Never use for on-chain randomness. Use Chainlink VRF or a commit-reveal scheme.
  • ORIGIN / CALLER — Work normally for L2 transactions. For L1→L2 deposits, the origin is aliased (see Sender Aliasing).
  • All other opcodes behave identically to Ethereum.

Unsupported Features

  • No native account abstraction (EIP-4337) — Use third-party bundlers (Pimlico, Alchemy, Stackup).
  • No eth_getProof with pending block tag — Use latest instead.

Useful Links

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.