Comparing aptos with layerzero

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

layerzero

View full →

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/layerzero/SKILL.md

LayerZero

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

What You Probably Got Wrong

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

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

Quick Start

Installation

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

For Foundry projects:

forge install LayerZero-Labs/LayerZero-v2

Minimal OApp Contract

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

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

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

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

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

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

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

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

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

    error InsufficientFee(uint256 sent, uint256 required);
}

Client Setup (TypeScript)

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

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

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

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

Core Concepts

Architecture Overview

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

OApp

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

OFT (Omnichain Fungible Token)

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

ONFT (Omnichain Non-Fungible Token)

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

EndpointV2

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

DVN (Decentralized Verifier Network)

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

Executor

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

MessageLib

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

OApp Development

Sending Messages

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

The full send flow:

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

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

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

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

Receiving Messages

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

Peer Configuration

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

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

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

From TypeScript:

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

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

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

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

OFT (Omnichain Fungible Token)

Deploy a New OFT

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

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

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

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

OFTAdapter for Existing ERC-20s

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

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

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

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

Sending OFT Cross-Chain

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

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

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

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

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

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

OFT Shared Decimals

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

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

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

Override sharedDecimals() to change this behavior:

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

DVN & Security Configuration

Setting Required and Optional DVNs

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

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

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

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

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

Configuring via EndpointV2

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

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

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

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

Security Best Practices

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

Message Options

Building Options with OptionsBuilder

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

using OptionsBuilder for bytes;

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

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

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

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

Options Encoding in TypeScript

import { encodePacked } from "viem";

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

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

const options = buildLzReceiveOption(200_000n);

Composed Messages

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

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

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

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

Deployment Pattern

Multi-Chain Deploy Sequence

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

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

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

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

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

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

Hardhat Deploy Script

import { ethers } from "hardhat";

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

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

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

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

main().catch(console.error);

Foundry Deploy Script

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

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

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

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

Fee Estimation

Quoting Send Fees

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

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

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

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

Fee Breakdown

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

Paying with LZ Token (ZRO)

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

Error Handling

Common Reverts

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

Debugging Cross-Chain Failures

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

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

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

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

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

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

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

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

Contract Addresses

Last verified: February 2026

EndpointV2

ChaineidEndpointV2
Ethereum301010x1a44076050125825900e736c501f859c50fE728c
Arbitrum301100x1a44076050125825900e736c501f859c50fE728c
Optimism301110x1a44076050125825900e736c501f859c50fE728c
Polygon301090x1a44076050125825900e736c501f859c50fE728c
Base301840x1a44076050125825900e736c501f859c50fE728c

Send/Receive Libraries (ULN302)

ChainSendUln302ReceiveUln302
Ethereum0xbB2Ea70C9E858123480642Cf96acbcCE1372dCe10xc02Ab410f0734EFa3F14628780e6e695156024C2
Arbitrum0x975bcD720be66659e3EB3C0e4F1866a3020E493A0x7B9E184e07a6EE1aC23eAe0fe8D6Be60f4f19eF3
Base0xB5320B0B3a13cC860893E2Bd79FCd7e13484Dda20xc70AB6f32772f59fBfc23889Caf4Ba3376C84bAf
Optimism0x1322871e4ab09Bc7f5717189434f97bBD9546e950x3c4962Ff6258dcfCafD23a814237571571899985
Polygon0x6c26c61a97006888ea9E4FA36584c7df57Cd9dA30x1322871e4ab09Bc7f5717189434f97bBD9546e95

LayerZero Labs DVN

ChainAddress
Ethereum0x589dEDbD617eE7783Ae3a7427E16b13280a2C00C
Arbitrum0x2f55C492897526677C5B68fb199ea31E2c126416
Base0x9e059a54699a285714207b43B055483E78FAac25
Optimism0x6A02D83e8d433304bba74EF1c427913958187142
Polygon0x23DE2FE932d9043291f870F07B7D2Bbca42e46c6

Default Executor

ChainAddress
Ethereum0x173272739Bd7Aa6e4e214714048a9fE699453059
Arbitrum0x31CAe3B7fB82d847621859571BF619D4600e37c8
Base0x2CCA08ae69E0C44b18a57Ab36A1CCb013C54B1d3
Optimism0x2D2ea0697bdbede3F01553D2Ae4B8d0c486B666e
Polygon0xCd3F213AD101472e1713C72B1697E727C803885b

References

AI Skill Finder

Ask me what skills you need

What are you building?

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