Comparing aptos with optimism

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/aptos/SKILL.md

Aptos Move L1 Development

Aptos is a Layer 1 blockchain built on Move, the language originally developed for Meta's Diem project. It achieves high throughput via Block-STM, a parallel execution engine that processes transactions optimistically and re-executes on conflicts. Smart contracts are called modules, and data is stored as resources at account addresses in a global storage model.

What You Probably Got Wrong

AI agents trained on Sui Move or Solidity make critical errors when generating Aptos Move code. Fix these first.

  • Aptos Move uses global storage, NOT Sui's object model — Resources are stored at addresses using move_to, move_from, borrow_global, and borrow_global_mut. There is no object::ObjectID or sui::object::UID. When you want to store data, you move_to<T>(signer, resource) to place it at the signer's address. To read it, you borrow_global<T>(address).

  • Resource accounts are NOT regular accounts — A resource account is a special account with no private key, controlled by its creating module. You create one with account::create_resource_account(origin, seed). The module publishes to the resource account's address. This is how protocols deploy immutable, admin-less contracts.

  • Token V1 is deprecated — use Token V2 (Digital Assets) — The aptos_token module (V1) is legacy. Use aptos_token_objects (V2), which uses the Move Object model. V2 tokens are stored as objects at their own addresses, not in a creator's TokenStore. Collections and tokens are first-class objects.

  • @aptos-labs/ts-sdk replaces the old aptos package — The npm package aptos is deprecated. Use @aptos-labs/ts-sdk. The entry point is new Aptos(new AptosConfig({ network: Network.MAINNET })). Do not import from aptos.

  • Coin standard is NOT ERC-20 — Aptos uses aptos_framework::coin with generics. A coin type is Coin<CoinType> where CoinType is a phantom type parameter defined by the deploying module. There is no approval/allowance pattern — coins are moved directly.

  • signer is not msg.sender — In Aptos Move, the signer is passed as a function parameter. A function must explicitly accept &signer to access the caller's address and perform operations on their account. Use signer::address_of(account) to get the address.

  • View functions are explicit — You must annotate functions with #[view] to make them callable off-chain without a transaction. They cannot modify state. They are called via the /view API endpoint, not through transaction submission.

  • u256 exists but u64 is standard for amounts — Unlike Solidity's uint256 default, Aptos uses u64 for coin amounts and most counters. u256 exists but is rarely used. APT has 8 decimals (not 18). 1 APT = 100,000,000 octas.

Chain Configuration

Mainnet

PropertyValue
Chain ID1
CurrencyAPT (8 decimals)
Block Time~100-300ms (sub-second)
Finality~900ms
Max Gas Unit2,000,000
Gas Unit PriceMin 100 octas
VMMove VM with Block-STM
ConsensusAptosBFT (DiemBFT v4)

RPC Endpoints

URLProviderNotes
https://fullnode.mainnet.aptoslabs.com/v1Aptos LabsDefault REST API
https://mainnet.aptoslabs.com/v1Aptos LabsAlternative
https://aptos-mainnet.nodereal.io/v1NodeRealRate-limited

Block Explorers

ExplorerURL
Aptos Explorerhttps://explorer.aptoslabs.com
Aptscanhttps://aptscan.ai

Testnet

PropertyValue
Chain ID2
RPChttps://fullnode.testnet.aptoslabs.com/v1
Faucethttps://faucet.testnet.aptoslabs.com
Explorerhttps://explorer.aptoslabs.com/?network=testnet

Devnet

PropertyValue
Chain IDvaries (resets frequently)
RPChttps://fullnode.devnet.aptoslabs.com/v1
Faucethttps://faucet.devnet.aptoslabs.com

Quick Start

Install Aptos CLI

# macOS
brew install aptos

# Linux / manual
curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3

# Verify
aptos --version

Create a New Move Project

# Initialize a new Move package
aptos move init --name my_module

# Project structure:
# my_module/
# ├── Move.toml
# └── sources/
#     └── my_module.move

Move.toml Configuration

[package]
name = "my_module"
version = "0.1.0"

[addresses]
my_addr = "_"

[dependencies]
AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework", rev = "mainnet" }
AptosTokenObjects = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-token-objects", rev = "mainnet" }

TypeScript SDK Setup

npm install @aptos-labs/ts-sdk
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({ network: Network.MAINNET });
const aptos = new Aptos(config);

Move Module Development

Module Structure

module my_addr::counter {
    use std::signer;

    struct Counter has key {
        value: u64,
    }

    /// Initialize a counter resource at the signer's address
    public entry fun initialize(account: &signer) {
        let counter = Counter { value: 0 };
        move_to(account, counter);
    }

    /// Increment the counter stored at the signer's address
    public entry fun increment(account: &signer) acquires Counter {
        let addr = signer::address_of(account);
        let counter = borrow_global_mut<Counter>(addr);
        counter.value = counter.value + 1;
    }

    /// Read the counter value at any address
    #[view]
    public fun get_count(addr: address): u64 acquires Counter {
        borrow_global<Counter>(addr).value
    }
}

Key Move Concepts

Global Storage Operations

// Store a resource at signer's address (signer must not already have one)
move_to<T>(signer, resource);

// Remove and return a resource from an address
let resource = move_from<T>(addr);

// Immutable reference to resource at address
let ref = borrow_global<T>(addr);

// Mutable reference to resource at address
let ref_mut = borrow_global_mut<T>(addr);

// Check if a resource exists at address
let exists = exists<T>(addr);

Abilities

// has copy — value can be copied
// has drop — value can be dropped (destroyed implicitly)
// has store — value can be stored inside another struct
// has key — value can be stored as a top-level resource in global storage

struct Coin has store {
    value: u64,
}

struct CoinStore has key {
    coin: Coin,
}

Access Control Pattern

module my_addr::admin {
    use std::signer;

    struct AdminConfig has key {
        admin: address,
    }

    const E_NOT_ADMIN: u64 = 1;
    const E_ALREADY_INITIALIZED: u64 = 2;

    public entry fun initialize(account: &signer) {
        let addr = signer::address_of(account);
        assert!(!exists<AdminConfig>(addr), E_ALREADY_INITIALIZED);
        move_to(account, AdminConfig { admin: addr });
    }

    public entry fun admin_only_action(account: &signer, config_addr: address) acquires AdminConfig {
        let config = borrow_global<AdminConfig>(config_addr);
        assert!(signer::address_of(account) == config.admin, E_NOT_ADMIN);
        // perform privileged action
    }
}

Events

module my_addr::events_example {
    use aptos_framework::event;

    #[event]
    struct TransferEvent has drop, store {
        from: address,
        to: address,
        amount: u64,
    }

    public entry fun transfer(from: &signer, to: address, amount: u64) {
        // ... transfer logic ...
        event::emit(TransferEvent {
            from: signer::address_of(from),
            to,
            amount,
        });
    }
}

Resource Accounts

module my_addr::resource_account_example {
    use std::signer;
    use aptos_framework::account;
    use aptos_framework::resource_account;

    struct ModuleData has key {
        resource_signer_cap: account::SignerCapability,
    }

    /// Called once during module publication to a resource account.
    /// The resource account's signer capability is stored for later use.
    fun init_module(resource_signer: &signer) {
        let resource_signer_cap = resource_account::retrieve_resource_account_cap(
            resource_signer,
            @source_addr
        );
        move_to(resource_signer, ModuleData {
            resource_signer_cap,
        });
    }

    /// Use the stored signer capability to act as the resource account
    public entry fun do_something(caller: &signer) acquires ModuleData {
        let module_data = borrow_global<ModuleData>(@my_addr);
        let resource_signer = account::create_signer_with_capability(
            &module_data.resource_signer_cap
        );
        // resource_signer can now sign transactions on behalf of the resource account
    }
}

Coin Standard

Creating a Custom Coin

module my_addr::my_coin {
    use std::signer;
    use std::string;
    use aptos_framework::coin;

    /// Phantom type marker for the coin — defines the coin type globally
    struct MyCoin {}

    struct CoinCapabilities has key {
        burn_cap: coin::BurnCapability<MyCoin>,
        freeze_cap: coin::FreezeCapability<MyCoin>,
        mint_cap: coin::MintCapability<MyCoin>,
    }

    const E_NOT_ADMIN: u64 = 1;

    public entry fun initialize(account: &signer) {
        let (burn_cap, freeze_cap, mint_cap) = coin::initialize<MyCoin>(
            account,
            string::utf8(b"My Coin"),
            string::utf8(b"MYC"),
            8, // decimals
            true, // monitor_supply
        );
        move_to(account, CoinCapabilities {
            burn_cap,
            freeze_cap,
            mint_cap,
        });
    }

    public entry fun mint(
        account: &signer,
        to: address,
        amount: u64,
    ) acquires CoinCapabilities {
        let addr = signer::address_of(account);
        let caps = borrow_global<CoinCapabilities>(addr);
        let coins = coin::mint(amount, &caps.mint_cap);
        coin::deposit(to, coins);
    }

    public entry fun burn(
        account: &signer,
        amount: u64,
    ) acquires CoinCapabilities {
        let addr = signer::address_of(account);
        let caps = borrow_global<CoinCapabilities>(addr);
        let coins = coin::withdraw<MyCoin>(account, amount);
        coin::burn(coins, &caps.burn_cap);
    }
}

Registering for a Coin

// Before receiving any coin type, an account must register for it
public entry fun register_coin<CoinType>(account: &signer) {
    coin::register<CoinType>(account);
}

Token V2 — Digital Assets

Creating a Collection and Token

module my_addr::nft {
    use std::signer;
    use std::string::{Self, String};
    use std::option;
    use aptos_token_objects::collection;
    use aptos_token_objects::token;

    struct TokenRefs has key {
        burn_ref: token::BurnRef,
        transfer_ref: option::Option<object::TransferRef>,
        mutator_ref: token::MutatorRef,
    }

    public entry fun create_collection(creator: &signer) {
        collection::create_unlimited_collection(
            creator,
            string::utf8(b"Collection description"),
            string::utf8(b"My Collection"),
            option::none(), // no royalty
            string::utf8(b"https://example.com/collection"),
        );
    }

    public entry fun mint_token(creator: &signer) {
        let constructor_ref = token::create_named_token(
            creator,
            string::utf8(b"My Collection"),
            string::utf8(b"Token description"),
            string::utf8(b"Token #1"),
            option::none(), // no royalty
            string::utf8(b"https://example.com/token/1"),
        );

        let token_signer = object::generate_signer(&constructor_ref);
        let burn_ref = token::generate_burn_ref(&constructor_ref);
        let mutator_ref = token::generate_mutator_ref(&constructor_ref);

        move_to(&token_signer, TokenRefs {
            burn_ref,
            transfer_ref: option::none(),
            mutator_ref,
        });
    }
}

TypeScript SDK (@aptos-labs/ts-sdk)

Client Initialization

import {
  Aptos,
  AptosConfig,
  Network,
  Account,
  Ed25519PrivateKey,
  AccountAddress,
} from "@aptos-labs/ts-sdk";

// Mainnet
const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET }));

// Testnet
const aptosTestnet = new Aptos(new AptosConfig({ network: Network.TESTNET }));

// Custom node
const aptosCustom = new Aptos(
  new AptosConfig({
    fullnode: "https://my-node.example.com/v1",
    indexer: "https://my-indexer.example.com/v1/graphql",
  })
);

Account Management

// Generate a new account
const account = Account.generate();
console.log("Address:", account.accountAddress.toString());
console.log("Private key:", account.privateKey.toString());

// From existing private key
const privateKey = new Ed25519PrivateKey("0x...");
const existingAccount = Account.fromPrivateKey({ privateKey });

// Fund on testnet
const aptosTestnet = new Aptos(new AptosConfig({ network: Network.TESTNET }));
await aptosTestnet.fundAccount({
  accountAddress: account.accountAddress,
  amount: 100_000_000, // 1 APT = 100,000,000 octas
});

Transfer APT

async function transferAPT(
  aptos: Aptos,
  sender: Account,
  recipientAddress: string,
  amountOctas: number
): Promise<string> {
  const transaction = await aptos.transaction.build.simple({
    sender: sender.accountAddress,
    data: {
      function: "0x1::aptos_account::transfer",
      functionArguments: [AccountAddress.from(recipientAddress), amountOctas],
    },
  });

  const pendingTx = await aptos.signAndSubmitTransaction({
    signer: sender,
    transaction,
  });

  const committedTx = await aptos.waitForTransaction({
    transactionHash: pendingTx.hash,
  });

  return committedTx.hash;
}

View Functions

async function getBalance(aptos: Aptos, address: string): Promise<bigint> {
  const result = await aptos.view({
    payload: {
      function: "0x1::coin::balance",
      typeArguments: ["0x1::aptos_coin::AptosCoin"],
      functionArguments: [AccountAddress.from(address)],
    },
  });
  return BigInt(result[0] as string);
}

Read Account Resources

async function getCoinStore(aptos: Aptos, address: string) {
  return aptos.getAccountResource({
    accountAddress: AccountAddress.from(address),
    resourceType: "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
  });
}

Multi-Agent Transactions

// Multi-agent: multiple signers for one transaction
async function multiAgentTransfer(
  aptos: Aptos,
  sender: Account,
  secondSigner: Account
) {
  const transaction = await aptos.transaction.build.multiAgent({
    sender: sender.accountAddress,
    secondarySignerAddresses: [secondSigner.accountAddress],
    data: {
      function: "0xmodule::my_module::multi_signer_action",
      functionArguments: [],
    },
  });

  const senderAuth = aptos.transaction.sign({
    signer: sender,
    transaction,
  });

  const secondAuth = aptos.transaction.sign({
    signer: secondSigner,
    transaction,
  });

  const pendingTx = await aptos.transaction.submit.multiAgent({
    transaction,
    senderAuthenticator: senderAuth,
    additionalSignersAuthenticators: [secondAuth],
  });

  return aptos.waitForTransaction({ transactionHash: pendingTx.hash });
}

Gas Estimation

async function estimateGas(aptos: Aptos, sender: Account) {
  const transaction = await aptos.transaction.build.simple({
    sender: sender.accountAddress,
    data: {
      function: "0x1::aptos_account::transfer",
      functionArguments: [
        AccountAddress.from("0xrecipient"),
        100_000_000,
      ],
    },
  });

  // Simulate to get gas estimate
  const simulation = await aptos.transaction.simulate.simple({
    signerPublicKey: sender.publicKey,
    transaction,
  });

  const gasUsed = BigInt(simulation[0].gas_used);
  const gasUnitPrice = BigInt(simulation[0].gas_unit_price);
  const totalCost = gasUsed * gasUnitPrice;

  return { gasUsed, gasUnitPrice, totalCost };
}

Compile and Deploy

Compile Module

# Compile
aptos move compile --named-addresses my_addr=default

# Run tests
aptos move test --named-addresses my_addr=default

# Publish to testnet (requires funded account)
aptos move publish --named-addresses my_addr=default --profile testnet

CLI Account Setup

# Initialize a new profile (generates keypair, funds on devnet/testnet)
aptos init --profile testnet --network testnet

# Initialize with existing private key
aptos init --profile mainnet --private-key 0x... --network mainnet

# Check account balance
aptos account balance --profile testnet

See examples/deploy-module/ for full SDK deployment code.

Testing Move Modules

#[test_only]
module my_addr::counter_tests {
    use std::signer;
    use my_addr::counter;

    #[test(account = @0x1)]
    fun test_initialize(account: &signer) {
        counter::initialize(account);
        let addr = signer::address_of(account);
        assert!(counter::get_count(addr) == 0, 0);
    }

    #[test(account = @0x1)]
    fun test_increment(account: &signer) {
        counter::initialize(account);
        counter::increment(account);
        let addr = signer::address_of(account);
        assert!(counter::get_count(addr) == 1, 0);
    }

    #[test(account = @0x1)]
    #[expected_failure(abort_code = 0x60001, location = aptos_framework::account)]
    fun test_double_initialize(account: &signer) {
        counter::initialize(account);
        counter::initialize(account); // should fail: resource already exists
    }
}

Block-STM Parallel Execution

Aptos uses Block-STM for optimistic parallel execution. Transactions within a block execute concurrently. If two transactions conflict (read/write to the same resource), one is re-executed.

What This Means for Developers

  • Independent transactions run in parallel — Transactions touching different accounts or resources execute simultaneously.
  • Contention on hot resources serializes execution — If your contract uses a single global counter that every transaction increments, Block-STM will detect the conflict and serialize those transactions. Performance degrades to sequential.
  • Design for parallelism — Use per-user resources instead of global state when possible. Example: instead of a global TotalDeposits counter, track deposits per-user and aggregate off-chain.

Anti-Pattern: Global Hot Resource

// BAD: Every deposit transaction conflicts on the same resource
struct GlobalState has key {
    total_deposits: u64,
}

public entry fun deposit(account: &signer, amount: u64) acquires GlobalState {
    let state = borrow_global_mut<GlobalState>(@module_addr);
    state.total_deposits = state.total_deposits + amount;
    // every deposit serializes here
}

Pattern: Per-User State

// GOOD: Each user's deposit is independent — parallel-friendly
struct UserDeposit has key {
    amount: u64,
}

public entry fun deposit(account: &signer, amount: u64) acquires UserDeposit {
    let addr = signer::address_of(account);
    if (exists<UserDeposit>(addr)) {
        let deposit = borrow_global_mut<UserDeposit>(addr);
        deposit.amount = deposit.amount + amount;
    } else {
        move_to(account, UserDeposit { amount });
    };
}

Move Object Model

The Move Object model (used by Token V2) creates objects at deterministic addresses. Objects are distinct from resources stored at user addresses.

module my_addr::object_example {
    use aptos_framework::object::{Self, Object, ConstructorRef};
    use std::signer;

    struct MyObject has key {
        value: u64,
    }

    /// Create a named object at a deterministic address
    public entry fun create(creator: &signer) {
        let constructor_ref = object::create_named_object(
            creator,
            b"my_object_seed",
        );
        let object_signer = object::generate_signer(&constructor_ref);
        move_to(&object_signer, MyObject { value: 42 });
    }

    /// Transfer ownership of an object
    public entry fun transfer_object(
        owner: &signer,
        obj: Object<MyObject>,
        to: address,
    ) {
        object::transfer(owner, obj, to);
    }

    #[view]
    public fun get_value(obj: Object<MyObject>): u64 acquires MyObject {
        let obj_addr = object::object_address(&obj);
        borrow_global<MyObject>(obj_addr).value
    }
}

Common Patterns

Table Storage (Key-Value Map)

use aptos_std::table::{Self, Table};

struct Registry has key {
    entries: Table<address, u64>,
}

public entry fun add_entry(account: &signer, key: address, value: u64) acquires Registry {
    let registry = borrow_global_mut<Registry>(signer::address_of(account));
    table::upsert(&mut registry.entries, key, value);
}

#[view]
public fun get_entry(registry_addr: address, key: address): u64 acquires Registry {
    let registry = borrow_global<Registry>(registry_addr);
    *table::borrow(&registry.entries, key)
}

Timestamp

use aptos_framework::timestamp;

public fun is_expired(deadline: u64): bool {
    timestamp::now_seconds() > deadline
}

Indexer and GraphQL

Aptos provides a GraphQL indexer for querying historical data, events, and token ownership.

NetworkIndexer URL
Mainnethttps://indexer.mainnet.aptoslabs.com/v1/graphql
Testnethttps://indexer.testnet.aptoslabs.com/v1/graphql

Key tables: current_token_ownerships_v2 (NFT ownership), current_token_datas_v2 (token metadata), coin_activities (transfer history), account_transactions (transaction history).

See examples/read-resources/ for full GraphQL query patterns.

Reference Links

Last verified: 2025-12-01

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.