Comparing arbitrum with pyth

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/arbitrum/SKILL.md

Arbitrum

Arbitrum is the largest Ethereum L2 by TVL, running an optimistic rollup via the Nitro execution engine. Nitro compiles a modified Geth (go-ethereum) to WASM, enabling full EVM equivalence with fraud proofs. Arbitrum One targets general-purpose DeFi, Arbitrum Nova uses AnyTrust (data availability committee) for high-throughput gaming/social, and Orbit lets teams launch custom L3s settling to Arbitrum.

What You Probably Got Wrong

AI models trained before late 2024 carry stale assumptions about Arbitrum. These corrections are critical.

  • block.number returns the L1 block number, not L2 — On Arbitrum, block.number in Solidity returns the L1 Ethereum block number at the time the sequencer processed the transaction. Use ArbSys(0x64).arbBlockNumber() for the actual L2 block number.
  • block.timestamp is the L1 timestamp — Same issue. block.timestamp reflects L1 time. For L2ley timing use ArbSys(0x64).arbBlockNumber() and correlate.
  • Arbitrum does NOT have the same gas model as Ethereum — Every Arbitrum transaction pays two gas components: (1) L2 execution gas (similar to Ethereum but cheaper), and (2) L1 data posting cost (calldata compressed and posted to Ethereum). The L1 component often dominates for data-heavy transactions. Use NodeInterface.gasEstimateComponents() to get the breakdown.
  • You need --legacy for Foundry deployments — Arbitrum's sequencer does not support EIP-1559 type-2 transactions natively in forge scripts. Use --legacy flag or your deployment will fail with a cryptic RPC error.
  • msg.sender in cross-chain calls is aliased — When an L1 contract sends a message to L2 via retryable tickets, msg.sender on L2 is NOT the L1 contract address. It is the L1 address + 0x1111000000000000000000000000000000001111 (the "address alias"). This prevents L1/L2 address collision attacks.
  • Retryable tickets can fail silently — An L1-to-L2 retryable ticket that runs out of gas on L2 does NOT revert on L1. It sits in the retry buffer for 7 days. You must monitor and manually redeem failed retryables, or your cross-chain message is lost after the TTL.
  • Withdrawals take 7 days, not minutes — L2-to-L1 messages go through the optimistic rollup challenge period. After calling ArbSys.sendTxToL1(), the user must wait ~7 days, then execute the message on L1 via the Outbox contract. There is no fast path in the native bridge.
  • There is no mempool — Arbitrum uses a centralized sequencer that orders transactions on a first-come-first-served basis. There is no traditional mempool, so MEV extraction works differently (no frontrunning via gas price bidding).

Quick Start

Chain Configuration

import { defineChain } from "viem";
import { arbitrum, arbitrumNova, arbitrumSepolia } from "viem/chains";

// Arbitrum One — mainnet
// Chain ID: 42161
// RPC: https://arb1.arbitrum.io/rpc (public, rate-limited)

// Arbitrum Nova — AnyTrust chain for gaming/social
// Chain ID: 42170
// RPC: https://nova.arbitrum.io/rpc

// Arbitrum Sepolia — testnet
// Chain ID: 421614
// RPC: https://sepolia-rollup.arbitrum.io/rpc

Client Setup

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

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

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

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

Chain Details

PropertyArbitrum OneArbitrum NovaArbitrum Sepolia
Chain ID4216142170421614
RPChttps://arb1.arbitrum.io/rpchttps://nova.arbitrum.io/rpchttps://sepolia-rollup.arbitrum.io/rpc
Explorerhttps://arbiscan.iohttps://nova.arbiscan.iohttps://sepolia.arbiscan.io
Bridgehttps://bridge.arbitrum.iohttps://bridge.arbitrum.iohttps://bridge.arbitrum.io
Native TokenETHETHETH
Block Time~0.25s~0.25s~0.25s
Finality~7 days (challenge period)~7 days~7 days

Deployment

Foundry Deployment

The --legacy flag is required — Arbitrum's sequencer does not natively support EIP-1559 type-2 transaction envelopes in forge broadcast.

# Deploy to Arbitrum One
forge create src/MyContract.sol:MyContract \
  --rpc-url $ARBITRUM_RPC_URL \
  --private-key $PRIVATE_KEY \
  --legacy

# Deploy to Arbitrum Sepolia (testnet)
forge create src/MyContract.sol:MyContract \
  --rpc-url https://sepolia-rollup.arbitrum.io/rpc \
  --private-key $PRIVATE_KEY \
  --legacy

# Using forge script
forge script script/Deploy.s.sol:DeployScript \
  --rpc-url $ARBITRUM_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --legacy

Hardhat Deployment

// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";

const config: HardhatUserConfig = {
  solidity: "0.8.24",
  networks: {
    arbitrumOne: {
      url: process.env.ARBITRUM_RPC_URL ?? "https://arb1.arbitrum.io/rpc",
      accounts: [process.env.PRIVATE_KEY!],
      chainId: 42161,
    },
    arbitrumSepolia: {
      url: "https://sepolia-rollup.arbitrum.io/rpc",
      accounts: [process.env.PRIVATE_KEY!],
      chainId: 421614,
    },
  },
  etherscan: {
    apiKey: {
      arbitrumOne: process.env.ARBISCAN_API_KEY!,
      arbitrumSepolia: process.env.ARBISCAN_API_KEY!,
    },
  },
};

export default config;

Contract Verification

# Verify on Arbiscan (Foundry)
forge verify-contract \
  --chain-id 42161 \
  --etherscan-api-key $ARBISCAN_API_KEY \
  --compiler-version v0.8.24 \
  $CONTRACT_ADDRESS \
  src/MyContract.sol:MyContract

# Verify with constructor args
forge verify-contract \
  --chain-id 42161 \
  --etherscan-api-key $ARBISCAN_API_KEY \
  --constructor-args $(cast abi-encode "constructor(address,uint256)" 0xYourAddress 1000) \
  $CONTRACT_ADDRESS \
  src/MyContract.sol:MyContract

# Verify on Sourcify
forge verify-contract \
  --chain-id 42161 \
  --verifier sourcify \
  $CONTRACT_ADDRESS \
  src/MyContract.sol:MyContract

Cross-Chain Messaging

L1 to L2: Retryable Tickets

Retryable tickets are Arbitrum's mechanism for sending messages from Ethereum L1 to Arbitrum L2. The L1 Inbox contract accepts the message and ETH for L2 gas, then the sequencer auto-executes it on L2.

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

interface IInbox {
    /// @notice Create a retryable ticket to send an L1→L2 message
    /// @param to L2 destination address
    /// @param l2CallValue ETH value to send to L2 destination
    /// @param maxSubmissionCost Max cost for L2 submission (refund if overestimated)
    /// @param excessFeeRefundAddress L2 address to refund excess fees
    /// @param callValueRefundAddress L2 address to refund call value on failure
    /// @param gasLimit L2 gas limit for execution
    /// @param maxFeePerGas Max L2 gas price
    /// @param data L2 calldata
    function createRetryableTicket(
        address to,
        uint256 l2CallValue,
        uint256 maxSubmissionCost,
        address excessFeeRefundAddress,
        address callValueRefundAddress,
        uint256 gasLimit,
        uint256 maxFeePerGas,
        bytes calldata data
    ) external payable returns (uint256);
}
// TypeScript: send L1→L2 message via retryable ticket
import { createPublicClient, createWalletClient, http, parseEther } from "viem";
import { mainnet } from "viem/chains";

const INBOX = "0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f" as const;

const inboxAbi = [
  {
    name: "createRetryableTicket",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "to", type: "address" },
      { name: "l2CallValue", type: "uint256" },
      { name: "maxSubmissionCost", type: "uint256" },
      { name: "excessFeeRefundAddress", type: "address" },
      { name: "callValueRefundAddress", type: "address" },
      { name: "gasLimit", type: "uint256" },
      { name: "maxFeePerGas", type: "uint256" },
      { name: "data", type: "bytes" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

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

const maxSubmissionCost = parseEther("0.001");
const gasLimit = 1_000_000n;
const maxFeePerGas = 100_000_000n; // 0.1 gwei

// Total ETH needed: l2CallValue + maxSubmissionCost + (gasLimit * maxFeePerGas)
const totalValue = 0n + maxSubmissionCost + gasLimit * maxFeePerGas;

const { request } = await l1PublicClient.simulateContract({
  address: INBOX,
  abi: inboxAbi,
  functionName: "createRetryableTicket",
  args: [
    "0xYourL2ContractAddress",     // to
    0n,                             // l2CallValue
    maxSubmissionCost,              // maxSubmissionCost
    account.address,                // excessFeeRefundAddress
    account.address,                // callValueRefundAddress
    gasLimit,                       // gasLimit
    maxFeePerGas,                   // maxFeePerGas
    "0x",                           // data (encoded L2 function call)
  ],
  value: totalValue,
  account: account.address,
});

const hash = await walletClient.writeContract(request);

L2 to L1: ArbSys.sendTxToL1

L2-to-L1 messages go through the 7-day challenge period before they can be executed on L1.

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

interface IArbSys {
    /// @notice Send a transaction from L2 to L1
    /// @param destination L1 destination address
    /// @param data L1 calldata
    /// @return unique message ID
    function sendTxToL1(
        address destination,
        bytes calldata data
    ) external payable returns (uint256);

    /// @notice Get the current L2 block number
    function arbBlockNumber() external view returns (uint256);
}

// ArbSys is at a fixed precompile address on all Arbitrum chains
IArbSys constant ARBSYS = IArbSys(0x0000000000000000000000000000000000000064);

contract L2ToL1Sender {
    event L2ToL1MessageSent(uint256 indexed messageId, address destination);

    function sendMessageToL1(
        address l1Target,
        bytes calldata l1Calldata
    ) external payable {
        uint256 messageId = ARBSYS.sendTxToL1{value: msg.value}(
            l1Target,
            l1Calldata
        );
        emit L2ToL1MessageSent(messageId, l1Target);
    }
}

Address Aliasing

When an L1 contract sends a retryable ticket, the msg.sender seen on L2 is the aliased address:

L2 alias = L1 address + 0x1111000000000000000000000000000000001111
// Reverse the alias to get the original L1 sender
function undoL1ToL2Alias(address l2Address) internal pure returns (address) {
    uint160 offset = uint160(0x1111000000000000000000000000000000001111);
    unchecked {
        return address(uint160(l2Address) - offset);
    }
}

// Verify an L2 call came from a specific L1 contract
modifier onlyFromL1Contract(address expectedL1Sender) {
    require(
        undoL1ToL2Alias(msg.sender) == expectedL1Sender,
        "NOT_FROM_L1_CONTRACT"
    );
    _;
}

ArbOS Precompiles

Arbitrum provides system-level functionality through precompile contracts at fixed addresses. These are available on all Arbitrum chains.

ArbSys (0x0000000000000000000000000000000000000064)

Core system functions for L2 operations.

interface IArbSys {
    function arbBlockNumber() external view returns (uint256);
    function arbBlockHash(uint256 blockNumber) external view returns (bytes32);
    function arbChainID() external view returns (uint256);
    function arbOSVersion() external view returns (uint256);
    function sendTxToL1(address dest, bytes calldata data) external payable returns (uint256);
    function withdrawEth(address dest) external payable returns (uint256);
}
const arbSysAbi = [
  {
    name: "arbBlockNumber",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "withdrawEth",
    type: "function",
    stateMutability: "payable",
    inputs: [{ name: "destination", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const ARBSYS = "0x0000000000000000000000000000000000000064" as const;

const l2BlockNumber = await publicClient.readContract({
  address: ARBSYS,
  abi: arbSysAbi,
  functionName: "arbBlockNumber",
});

ArbRetryableTx (0x000000000000000000000000000000000000006E)

Manage retryable tickets on L2.

interface IArbRetryableTx {
    /// @notice Redeem a retryable ticket that failed auto-execution
    function redeem(bytes32 ticketId) external;
    /// @notice Get the TTL for retryable tickets (default: 7 days)
    function getLifetime() external view returns (uint256);
    /// @notice Get the timeout timestamp for a specific ticket
    function getTimeout(bytes32 ticketId) external view returns (uint256);
    /// @notice Extend the lifetime of a retryable ticket
    function keepalive(bytes32 ticketId) external returns (uint256);
}

ArbGasInfo (0x000000000000000000000000000000000000006C)

Gas pricing information, especially the L1 data cost component.

interface IArbGasInfo {
    /// @notice Get gas prices: [perL2Tx, perL1CalldataUnit, perStorageAlloc, perArbGasBase, perArbGasCongestion, perArbGasTotal]
    function getPricesInWei() external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
    /// @notice Get estimated L1 base fee
    function getL1BaseFeeEstimate() external view returns (uint256);
    /// @notice Get L1 gas pricing parameters
    function getL1GasPriceEstimate() external view returns (uint256);
}
const arbGasInfoAbi = [
  {
    name: "getPricesInWei",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [
      { name: "perL2Tx", type: "uint256" },
      { name: "perL1CalldataUnit", type: "uint256" },
      { name: "perStorageAlloc", type: "uint256" },
      { name: "perArbGasBase", type: "uint256" },
      { name: "perArbGasCongestion", type: "uint256" },
      { name: "perArbGasTotal", type: "uint256" },
    ],
  },
  {
    name: "getL1BaseFeeEstimate",
    type: "function",
    stateMutability: "view",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const ARBGASINFO = "0x000000000000000000000000000000000000006C" as const;

const prices = await publicClient.readContract({
  address: ARBGASINFO,
  abi: arbGasInfoAbi,
  functionName: "getPricesInWei",
});

const l1BaseFee = await publicClient.readContract({
  address: ARBGASINFO,
  abi: arbGasInfoAbi,
  functionName: "getL1BaseFeeEstimate",
});

NodeInterface (0x00000000000000000000000000000000000000C8)

Virtual contract for gas estimation — not callable from other contracts, only via eth_call / eth_estimateGas.

interface INodeInterface {
    /// @notice Estimate gas for a retryable ticket submission
    function estimateRetryableTicket(
        address sender,
        uint256 deposit,
        address to,
        uint256 l2CallValue,
        address excessFeeRefundAddress,
        address callValueRefundAddress,
        bytes calldata data
    ) external;

    /// @notice Get gas cost breakdown: gasEstimate, gasEstimateForL1, baseFee, l1BaseFeeEstimate
    function gasEstimateComponents(
        address to,
        bool contractCreation,
        bytes calldata data
    ) external payable returns (uint64, uint64, uint256, uint256);
}
const nodeInterfaceAbi = [
  {
    name: "gasEstimateComponents",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "to", type: "address" },
      { name: "contractCreation", type: "bool" },
      { name: "data", type: "bytes" },
    ],
    outputs: [
      { name: "gasEstimate", type: "uint64" },
      { name: "gasEstimateForL1", type: "uint64" },
      { name: "baseFee", type: "uint256" },
      { name: "l1BaseFeeEstimate", type: "uint256" },
    ],
  },
] as const;

const NODE_INTERFACE = "0x00000000000000000000000000000000000000C8" as const;

// Estimate gas with L1/L2 breakdown
const result = await publicClient.simulateContract({
  address: NODE_INTERFACE,
  abi: nodeInterfaceAbi,
  functionName: "gasEstimateComponents",
  args: [
    "0xTargetContract",
    false,
    "0xEncodedCalldata",
  ],
});

const [totalGas, l1Gas, baseFee, l1BaseFee] = result.result;
// L2 gas = totalGas - l1Gas

Gas Model

Arbitrum's gas model has two components. Understanding this is critical for accurate cost estimation.

Two-Component Gas

ComponentSourceScales With
L2 execution gasArbOS computationOpcodes executed (similar to Ethereum)
L1 data posting costCalldata posted to EthereumTransaction size in bytes

The L1 data cost is computed as:

L1 cost = L1 base fee * (calldata bytes * 16 + overhead)

This L1 cost is converted to L2 gas units and added to the total gas used. For data-heavy transactions (large calldata, many storage writes that get batched), the L1 component can be 80%+ of total cost.

Gas Estimation

import { encodeFunctionData, formatEther } from "viem";

async function estimateArbitrumGas(
  publicClient: PublicClient,
  to: `0x${string}`,
  data: `0x${string}`
) {
  const nodeInterfaceAbi = [
    {
      name: "gasEstimateComponents",
      type: "function",
      stateMutability: "payable",
      inputs: [
        { name: "to", type: "address" },
        { name: "contractCreation", type: "bool" },
        { name: "data", type: "bytes" },
      ],
      outputs: [
        { name: "gasEstimate", type: "uint64" },
        { name: "gasEstimateForL1", type: "uint64" },
        { name: "baseFee", type: "uint256" },
        { name: "l1BaseFeeEstimate", type: "uint256" },
      ],
    },
  ] as const;

  const { result } = await publicClient.simulateContract({
    address: "0x00000000000000000000000000000000000000C8",
    abi: nodeInterfaceAbi,
    functionName: "gasEstimateComponents",
    args: [to, false, data],
  });

  const [totalGas, l1Gas, baseFee, l1BaseFee] = result;
  const l2Gas = totalGas - l1Gas;

  return {
    totalGas,
    l1Gas,
    l2Gas,
    baseFee,
    l1BaseFee,
    estimatedCostWei: BigInt(totalGas) * baseFee,
    estimatedCostEth: formatEther(BigInt(totalGas) * baseFee),
  };
}

Token Bridge

Bridging ETH (L1 to L2)

const INBOX = "0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f" as const;

const inboxAbi = [
  {
    name: "depositEth",
    type: "function",
    stateMutability: "payable",
    inputs: [],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// Deposit 0.1 ETH from L1 to L2 (arrives at same address on L2)
const { request } = await l1PublicClient.simulateContract({
  address: INBOX,
  abi: inboxAbi,
  functionName: "depositEth",
  value: parseEther("0.1"),
  account: account.address,
});

const hash = await l1WalletClient.writeContract(request);
const receipt = await l1PublicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("ETH deposit failed");
// ETH appears on L2 within ~10 minutes

Bridging ETH (L2 to L1)

// Withdraw ETH from L2 to L1 via ArbSys precompile
const ARBSYS = "0x0000000000000000000000000000000000000064" as const;

const arbSysAbi = [
  {
    name: "withdrawEth",
    type: "function",
    stateMutability: "payable",
    inputs: [{ name: "destination", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

const { request } = await l2PublicClient.simulateContract({
  address: ARBSYS,
  abi: arbSysAbi,
  functionName: "withdrawEth",
  args: [account.address], // L1 destination
  value: parseEther("0.1"),
  account: account.address,
});

const hash = await l2WalletClient.writeContract(request);
// After 7-day challenge period, claim on L1 via Outbox contract

Bridging ERC20 Tokens (L1 to L2)

ERC20 tokens bridge through the Gateway Router, which routes to the appropriate gateway (standard, custom, or WETH).

const GATEWAY_ROUTER = "0x72Ce9c846789fdB6fC1f34aC4AD25Dd9ef7031ef" as const;

const gatewayRouterAbi = [
  {
    name: "outboundTransfer",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "_token", type: "address" },
      { name: "_to", type: "address" },
      { name: "_amount", type: "uint256" },
      { name: "_maxGas", type: "uint256" },
      { name: "_gasPriceBid", type: "uint256" },
      { name: "_data", type: "bytes" },
    ],
    outputs: [{ name: "", type: "bytes" }],
  },
  {
    name: "getGateway",
    type: "function",
    stateMutability: "view",
    inputs: [{ name: "_token", type: "address" }],
    outputs: [{ name: "", type: "address" }],
  },
] as const;

const USDC_L1 = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" as const;

// Step 1: Approve the gateway (not the router) to spend tokens
const gateway = await l1PublicClient.readContract({
  address: GATEWAY_ROUTER,
  abi: gatewayRouterAbi,
  functionName: "getGateway",
  args: [USDC_L1],
});

// Step 2: approve gateway, then call outboundTransfer on the router
// The _data param encodes maxSubmissionCost and extra data
import { encodeAbiParameters, parseAbiParameters } from "viem";

const maxSubmissionCost = parseEther("0.001");
const extraData = encodeAbiParameters(
  parseAbiParameters("uint256, bytes"),
  [maxSubmissionCost, "0x"]
);

const bridgeAmount = 1000_000000n; // 1000 USDC (6 decimals)
const gasLimit = 300_000n;
const gasPriceBid = 100_000_000n; // 0.1 gwei

const totalValue = maxSubmissionCost + gasLimit * gasPriceBid;

const { request } = await l1PublicClient.simulateContract({
  address: GATEWAY_ROUTER,
  abi: gatewayRouterAbi,
  functionName: "outboundTransfer",
  args: [
    USDC_L1,
    account.address,
    bridgeAmount,
    gasLimit,
    gasPriceBid,
    extraData,
  ],
  value: totalValue,
  account: account.address,
});

Gateway Types

GatewayAddress (L1)Purpose
Standard ERC200xa3A7B6F88361F48403514059F1F16C8E78d60EeCDefault for most ERC20 tokens
CustomVaries per tokenTokens needing custom L1/L2 logic
WETH0xd92023E9d9911199a6711321D1277285e6d4e2dbHandles WETH unwrap/wrap across bridge

Orbit Chains

Orbit allows teams to launch custom L3 chains that settle to Arbitrum One or Nova. These are independent chains with configurable parameters.

Orbit Architecture

Ethereum L1 (settlement)
  └── Arbitrum One L2 (execution + DA)
       └── Your Orbit L3 (custom chain)

Orbit SDK Setup

import { createRollupPrepareConfig, createRollupPrepareTransactionRequest } from "@arbitrum/orbit-sdk";

// Prepare Orbit chain configuration
const config = createRollupPrepareConfig({
  chainId: BigInt(YOUR_CHAIN_ID),
  owner: "0xYourOwnerAddress",
  chainConfig: {
    // Custom gas token, data availability, etc.
    homesteadBlock: 0,
    daoForkBlock: null,
    daoForkSupport: true,
    eip150Block: 0,
    eip150Hash: "0x0000000000000000000000000000000000000000000000000000000000000000",
    eip155Block: 0,
    eip158Block: 0,
    byzantiumBlock: 0,
    constantinopleBlock: 0,
    petersburgBlock: 0,
    istanbulBlock: 0,
    muirGlacierBlock: 0,
    berlinBlock: 0,
    londonBlock: 0,
    clique: { period: 0, epoch: 0 },
    arbitrum: {
      EnableArbOS: true,
      AllowDebugPrecompiles: false,
      DataAvailabilityCommittee: false, // true for AnyTrust
      InitialArbOSVersion: 20,
      InitialChainOwner: "0xYourOwnerAddress",
      GenesisBlockNum: 0,
    },
  },
});

When to Use Orbit

Use CaseRecommendation
App-specific chain with custom gas tokenOrbit L3
High-throughput gaming with cheap DAOrbit L3 + AnyTrust
General DeFi appDeploy to Arbitrum One directly
Cross-chain interop neededDeploy to Arbitrum One (better liquidity)

Key Differences from Ethereum

BehaviorEthereumArbitrum
block.numberCurrent L1 blockL1 block number (NOT L2)
block.timestampL1 timestampL1 timestamp
L2 block numberN/AArbSys(0x64).arbBlockNumber()
Gas modelSingle gas priceL2 gas + L1 data posting cost
Transaction typeEIP-1559 (type 2)Legacy (type 0) recommended
MempoolPublic, competitiveNo mempool (FCFS sequencer)
Finality~12 seconds (1 epoch)~0.25s soft, ~7 days hard
msg.sender cross-chainSame addressAliased (+0x1111...1111 offset)
SELFDESTRUCTDeprecated (EIP-6780)Same as Ethereum post-Dencun
Contract size limit24KB (EIP-170)24KB (same)
PUSH0 opcodeSupported (Shanghai)Supported (Nitro supports it)

Contract Addresses

Last verified: February 2026

Core Contracts (Arbitrum One)

ContractAddress
Rollup0x5eF0D09d1E6204141B4d37530808eD19f60FBa35
Inbox0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f
Outbox0x0B9857ae2D4A3DBe74ffE1d7DF045bb7F96E4840
Bridge0x8315177aB297bA92A06054cE80a67Ed4DBd7ed3a
SequencerInbox0x1c479675ad559DC151F6Ec7ed3FbF8ceE79582B6
Gateway Router (L1)0x72Ce9c846789fdB6fC1f34aC4AD25Dd9ef7031ef
Standard Gateway (L1)0xa3A7B6F88361F48403514059F1F16C8E78d60EeC
WETH Gateway (L1)0xd92023E9d9911199a6711321D1277285e6d4e2db
Gateway Router (L2)0x5288c571Fd7aD117beA99bF60FE0846C4E84F933
Standard Gateway (L2)0x09e9222E96E7B4AE2a407B98d48e330053351EEe

ArbOS Precompiles

PrecompileAddress
ArbSys0x0000000000000000000000000000000000000064
ArbInfo0x0000000000000000000000000000000000000065
ArbAddressTable0x0000000000000000000000000000000000000066
ArbBLS (deprecated)0x0000000000000000000000000000000000000067
ArbFunctionTable (deprecated)0x0000000000000000000000000000000000000068
ArbosTest0x0000000000000000000000000000000000000069
ArbOwner0x0000000000000000000000000000000000000070
ArbGasInfo0x000000000000000000000000000000000000006C
ArbAggregator0x000000000000000000000000000000000000006D
ArbRetryableTx0x000000000000000000000000000000000000006E
ArbStatistics0x000000000000000000000000000000000000006F
NodeInterface0x00000000000000000000000000000000000000C8

Token Addresses (Arbitrum One)

TokenAddress
ARB0x912CE59144191C1204E64559FE8253a0e49E6548
WETH0x82aF49447D8a07e3bd95BD0d56f35241523fBab1
USDC (native)0xaf88d065e77c8cC2239327C5EDb3A432268e5831
USDC.e (bridged)0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8
USDT0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9
DAI0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1
WBTC0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f
GMX0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a

Error Handling

ErrorCauseFix
NOT_ENOUGH_FUNDSInsufficient ETH for L2 gas + L1 data costAccount for both gas components in estimation
RETRYABLE_TICKET_CREATION_FAILEDRetryable ticket underfundedIncrease maxSubmissionCost or gasLimit * maxFeePerGas
ONLY_ROLLUP_OR_OWNERCalling admin precompile without permissionThese are restricted to chain owner
NO_TICKET_WITH_IDRedeeming non-existent or expired retryableCheck ticket still exists with getTimeout()
ALREADY_REDEEMEDRetryable ticket already executedNo action needed — message was delivered
L1_MSG_NOT_CONFIRMEDTrying to execute L2→L1 message too earlyWait for the 7-day challenge period to elapse
Nonce too high/lowSequencer nonce mismatchReset nonce or wait for pending transactions

Security

Cross-Chain Message Validation

// Always verify the sender of cross-chain messages
// L1→L2: check aliased sender
modifier onlyL1Contract(address expectedL1Sender) {
    uint160 offset = uint160(0x1111000000000000000000000000000000001111);
    unchecked {
        require(
            address(uint160(msg.sender) - offset) == expectedL1Sender,
            "ONLY_L1_CONTRACT"
        );
    }
    _;
}

// L2→L1: verify via Outbox on L1
modifier onlyL2Contract(address outbox) {
    // The Outbox contract provides l2ToL1Sender() during execution
    IOutbox(outbox).l2ToL1Sender();
    _;
}

Gas Estimation Safety

  • Always use NodeInterface.gasEstimateComponents() instead of plain eth_estimateGas — the latter may not account for L1 data costs correctly in all cases.
  • Add a 20-30% buffer to gas estimates for L1 data cost fluctuations.
  • For retryable tickets, overestimate maxSubmissionCost — excess is refunded.

Retryable Ticket Monitoring

  • Monitor all retryable tickets for auto-redeem failure.
  • Failed retryables expire after 7 days — set up alerts.
  • Use the ArbRetryableTx precompile to check status and manually redeem.

References

Author

@0xinit

Stars

53

Repository

0xinit/cryptoskills

skills/pyth/SKILL.md

Pyth Network Development Guide

Pyth Network is a decentralized oracle providing real-time price feeds for cryptocurrencies, equities, forex, and commodities. This guide covers integrating Pyth price feeds into Solana applications.

Overview

Pyth Network provides:

  • Real-Time Price Feeds - 400ms update frequency with pull oracle model
  • Confidence Intervals - Statistical uncertainty bounds for each price
  • EMA Prices - Exponential moving average prices (~1 hour window)
  • Multi-Asset Support - Crypto, equities, FX, commodities, indices
  • On-Chain Integration - CPI for Solana programs
  • Off-Chain Integration - HTTP and WebSocket APIs via Hermes

Program IDs

ProgramAddressDescription
Solana Receiverrec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJPosts price updates to Solana
Price FeedpythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsTStores price feed data

Deployed on: Solana Mainnet, Devnet, Eclipse Mainnet/Testnet, Sonic networks

Popular Price Feed IDs

AssetHex Feed ID
BTC/USD0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43
ETH/USD0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace
SOL/USD0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d
USDC/USD0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a
USDT/USD0x2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b

Full list: https://pyth.network/developers/price-feed-ids

Quick Start

Installation

# TypeScript/JavaScript
npm install @pythnetwork/hermes-client @pythnetwork/pyth-solana-receiver

# Rust (add to Cargo.toml)
# pyth-solana-receiver-sdk = "0.3.0"

Fetch Price (Off-Chain)

import { HermesClient } from "@pythnetwork/hermes-client";

const client = new HermesClient("https://hermes.pyth.network");

const priceIds = [
  "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43", // BTC/USD
];

const priceUpdates = await client.getLatestPriceUpdates(priceIds);

for (const update of priceUpdates.parsed) {
  const price = update.price;
  const displayPrice = Number(price.price) * Math.pow(10, price.expo);
  console.log(`Price: $${displayPrice.toFixed(2)}`);
  console.log(`Confidence: ±${Number(price.conf) * Math.pow(10, price.expo)}`);
}

Use Price On-Chain (Rust/Anchor)

use anchor_lang::prelude::*;
use pyth_solana_receiver_sdk::price_update::PriceUpdateV2;

#[derive(Accounts)]
pub struct UsePrice<'info> {
    pub price_update: Account<'info, PriceUpdateV2>,
}

pub fn use_price(ctx: Context<UsePrice>) -> Result<()> {
    let price_update = &ctx.accounts.price_update;
    let clock = Clock::get()?;

    // Get price no older than 60 seconds
    let price = price_update.get_price_no_older_than(
        &clock,
        60, // max age in seconds
    )?;

    msg!("Price: {} × 10^{}", price.price, price.exponent);
    msg!("Confidence: ±{}", price.conf);

    Ok(())
}

Core Concepts

Price Structure

Each Pyth price contains:

FieldTypeDescription
pricei64Price value in fixed-point format
confu64Confidence interval (standard deviation)
expoi32Exponent for scaling (e.g., -8 means divide by 10^8)
publish_timei64Unix timestamp of price

Converting to display price:

const displayPrice = price * Math.pow(10, expo);
// Example: price=19405100, expo=-2 → $194,051.00

Confidence Intervals

Confidence intervals represent the uncertainty in the reported price:

// Price is $50,000 ± $50 means:
// - 68% chance true price is between $49,950 - $50,050
// - Use confidence for risk management

const price = 50000;
const confidence = 50;

// Safe lower bound (conservative)
const safeLowerBound = price - confidence;

// Safe upper bound (conservative)
const safeUpperBound = price + confidence;

Best Practice: Reject prices with confidence > 2% of price:

const maxConfidenceRatio = 0.02; // 2%
const confidenceRatio = confidence / Math.abs(price);

if (confidenceRatio > maxConfidenceRatio) {
  throw new Error("Price confidence too wide");
}

EMA Prices

Exponential Moving Average prices smooth out short-term volatility:

  • ~1 hour averaging window (5921 Solana slots)
  • Weighted by inverse confidence (tight confidence = more weight)
  • Good for: liquidations, collateral valuation
  • Available as ema_price and ema_conf
// Use EMA for less volatile applications
const emaPrice = priceUpdate.emaPrice;
const emaConf = priceUpdate.emaConf;

Off-Chain Integration

Hermes Client

Hermes is the recommended way to fetch Pyth prices off-chain.

Public Endpoint: https://hermes.pyth.network

For production, get a dedicated endpoint from a Pyth data provider.

Fetching Latest Prices

import { HermesClient } from "@pythnetwork/hermes-client";

const client = new HermesClient("https://hermes.pyth.network");

// Single price
const btcPrice = await client.getLatestPriceUpdates([
  "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43"
]);

// Multiple prices in one request
const prices = await client.getLatestPriceUpdates([
  "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43", // BTC
  "0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace", // ETH
  "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d", // SOL
]);

Streaming Real-Time Updates

import { HermesClient } from "@pythnetwork/hermes-client";

const client = new HermesClient("https://hermes.pyth.network");

const priceIds = [
  "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43"
];

// Subscribe to real-time updates via SSE
const eventSource = await client.getPriceUpdatesStream(priceIds, {
  parsed: true,
});

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Price update:", data);
};

eventSource.onerror = (error) => {
  console.error("Stream error:", error);
  eventSource.close();
};

// Close when done
// eventSource.close();

Posting Prices to Solana

import { PythSolanaReceiver } from "@pythnetwork/pyth-solana-receiver";
import { HermesClient } from "@pythnetwork/hermes-client";
import { Connection, Keypair } from "@solana/web3.js";

const connection = new Connection("https://api.mainnet-beta.solana.com");
const wallet = Keypair.fromSecretKey(/* your key */);

const hermesClient = new HermesClient("https://hermes.pyth.network");
const pythReceiver = new PythSolanaReceiver({ connection, wallet });

// Fetch price update data
const priceUpdateData = await hermesClient.getLatestPriceUpdates([
  "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43"
]);

// Build transaction to post price
const transactionBuilder = pythReceiver.newTransactionBuilder();
await transactionBuilder.addPostPriceUpdates(priceUpdateData.binary.data);

// Add your program instruction that uses the price
// transactionBuilder.addInstruction(yourInstruction);

// Send transaction
const transactions = await transactionBuilder.buildVersionedTransactions({
  computeUnitPriceMicroLamports: 50000,
});

for (const tx of transactions) {
  const sig = await connection.sendTransaction(tx);
  console.log("Transaction:", sig);
}

On-Chain Integration (Rust)

Setup

Add to Cargo.toml:

[dependencies]
pyth-solana-receiver-sdk = "0.3.0"
anchor-lang = "0.30.1"

Reading Price in Anchor Program

use anchor_lang::prelude::*;
use pyth_solana_receiver_sdk::price_update::{PriceUpdateV2, get_feed_id_from_hex};

declare_id!("YourProgramId...");

// BTC/USD price feed ID
const BTC_USD_FEED_ID: &str = "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";

#[program]
pub mod my_program {
    use super::*;

    pub fn check_price(ctx: Context<CheckPrice>) -> Result<()> {
        let price_update = &ctx.accounts.price_update;
        let clock = Clock::get()?;

        // Verify this is the correct feed
        let feed_id = get_feed_id_from_hex(BTC_USD_FEED_ID)?;

        // Get price no older than 60 seconds
        let price = price_update.get_price_no_older_than_with_custom_verification(
            &clock,
            60,
            &feed_id,
            ctx.accounts.price_update.to_account_info().owner,
        )?;

        msg!("BTC/USD Price: {} × 10^{}", price.price, price.exponent);
        msg!("Confidence: ±{}", price.conf);

        Ok(())
    }
}

#[derive(Accounts)]
pub struct CheckPrice<'info> {
    #[account(
        constraint = price_update.to_account_info().owner == &pyth_solana_receiver_sdk::ID
    )]
    pub price_update: Account<'info, PriceUpdateV2>,
}

Using Price for Calculations

pub fn swap_with_oracle(
    ctx: Context<SwapWithOracle>,
    amount_in: u64,
) -> Result<()> {
    let price_update = &ctx.accounts.price_update;
    let clock = Clock::get()?;

    // Get price with staleness check
    let price = price_update.get_price_no_older_than(&clock, 30)?;

    // Validate confidence (max 1% of price)
    let conf_ratio = (price.conf as u128 * 10000) / (price.price.unsigned_abs() as u128);
    require!(conf_ratio <= 100, ErrorCode::ConfidenceTooWide);

    // Convert price to usable format
    // price.price is in fixed-point with price.exponent
    let price_scaled = if price.exponent >= 0 {
        (price.price as u128) * 10_u128.pow(price.exponent as u32)
    } else {
        (price.price as u128) / 10_u128.pow((-price.exponent) as u32)
    };

    // Calculate output amount using oracle price
    let amount_out = (amount_in as u128)
        .checked_mul(price_scaled)
        .ok_or(ErrorCode::MathOverflow)?
        / 1_000_000; // Adjust for decimals

    msg!("Swap {} -> {} using price {}", amount_in, amount_out, price_scaled);

    Ok(())
}

#[error_code]
pub enum ErrorCode {
    #[msg("Price confidence interval too wide")]
    ConfidenceTooWide,
    #[msg("Math overflow")]
    MathOverflow,
}

Multiple Price Feeds

#[derive(Accounts)]
pub struct Liquidation<'info> {
    #[account(
        constraint = collateral_price.to_account_info().owner == &pyth_solana_receiver_sdk::ID
    )]
    pub collateral_price: Account<'info, PriceUpdateV2>,

    #[account(
        constraint = debt_price.to_account_info().owner == &pyth_solana_receiver_sdk::ID
    )]
    pub debt_price: Account<'info, PriceUpdateV2>,
}

pub fn check_liquidation(ctx: Context<Liquidation>) -> Result<bool> {
    let clock = Clock::get()?;

    let collateral = ctx.accounts.collateral_price
        .get_price_no_older_than(&clock, 60)?;
    let debt = ctx.accounts.debt_price
        .get_price_no_older_than(&clock, 60)?;

    // Normalize to same exponent for comparison
    let collateral_value = normalize_price(collateral.price, collateral.exponent);
    let debt_value = normalize_price(debt.price, debt.exponent);

    // Check if undercollateralized
    let is_liquidatable = collateral_value < debt_value * 150 / 100; // 150% ratio

    Ok(is_liquidatable)
}

fn normalize_price(price: i64, expo: i32) -> i128 {
    let target_expo = -8; // Normalize to 8 decimals
    let adjustment = expo - target_expo;

    if adjustment >= 0 {
        (price as i128) * 10_i128.pow(adjustment as u32)
    } else {
        (price as i128) / 10_i128.pow((-adjustment) as u32)
    }
}

Best Practices

1. Always Check Staleness

// Don't use old prices - set appropriate max age
let max_age_seconds = 60;
let price = price_update.get_price_no_older_than(&clock, max_age_seconds)?;

2. Validate Confidence Intervals

// Reject prices with wide confidence (high uncertainty)
const MAX_CONF_BPS: u64 = 200; // 2%

let conf_bps = (price.conf as u128 * 10000) / (price.price.unsigned_abs() as u128);
require!(conf_bps <= MAX_CONF_BPS as u128, ErrorCode::ConfidenceTooWide);

3. Verify Account Ownership

// Always verify the price account is owned by Pyth
#[account(
    constraint = price_update.to_account_info().owner == &pyth_solana_receiver_sdk::ID
)]
pub price_update: Account<'info, PriceUpdateV2>,

4. Use EMA for Sensitive Operations

// For liquidations, use EMA to avoid manipulation
let ema_price = price_update.get_ema_price_no_older_than(&clock, 60)?;

5. Handle Price Unavailability

try {
  const price = await client.getLatestPriceUpdates([feedId]);
  // Use price
} catch (error) {
  // Fallback behavior or reject transaction
  console.error("Price unavailable:", error);
}

6. Consider Frontrunning

  • Adversaries may see price updates before your transaction
  • Don't design logic that races against price updates
  • Use appropriate slippage tolerances

Price Feed Types

Fixed Price Feed Accounts

  • Maintained continuously by Pyth
  • Fixed address per feed
  • Always has most recent price
  • Shared by all users (potential congestion)

Ephemeral Price Update Accounts

  • Created per transaction
  • Can specify shard ID for parallelization
  • Rent can be recovered after use
  • Better for high-throughput applications
// Use shard ID to avoid congestion
const transactionBuilder = pythReceiver.newTransactionBuilder({
  shardId: Math.floor(Math.random() * 65536), // Random shard
});

Resources

Official Documentation

GitHub Repositories

NPM Packages

Rust Crates


Skill Structure

pyth/
├── SKILL.md                          # This file
├── resources/
│   ├── program-addresses.md          # All program IDs and feed IDs
│   └── api-reference.md              # SDK API reference
├── examples/
│   ├── price-feeds/
│   │   ├── fetch-price.ts            # Basic price fetching
│   │   └── multiple-prices.ts        # Multiple price feeds
│   ├── on-chain/
│   │   ├── anchor-integration.rs     # Anchor program example
│   │   └── price-validation.rs       # Price validation patterns
│   └── streaming/
│       └── real-time-updates.ts      # WebSocket streaming
├── templates/
│   ├── pyth-client.ts                # TypeScript client template
│   └── anchor-oracle.rs              # Anchor program template
└── docs/
    └── troubleshooting.md            # Common issues and solutions

Pyth on EVM Chains

This skill covers Pyth integration for Solana applications using Anchor CPI. For EVM chain integration (Ethereum, Arbitrum, Base, Optimism, Polygon, and 50+ other chains), see the pyth-evm skill.

Key differences between Pyth Solana and Pyth EVM:

AspectPyth Solana (this skill)Pyth EVM (pyth-evm skill)
Contract interfaceAnchor CPI to Pyth programSolidity IPyth interface
Price updatePull from Pyth accumulator accountSubmit bytes[] via updatePriceFeeds
Contract addressSingle Pyth program on SolanaVaries per EVM chain
Gas/computeCompute units~120-150K gas per feed update
SDK@pythnetwork/pyth-solana-receiver@pythnetwork/hermes-client v3.1.0

Price feed IDs (bytes32) are the same across all chains — a BTC/USD feed ID works on both Solana and Ethereum.

Related Skills

  • pyth-evm — Pyth oracle integration for EVM chains (Solidity + TypeScript)
  • chainlink — Push oracle alternative on EVM chains
  • redstone — Another pull oracle for EVM chains

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.