Logo
RPC Assistant

Optimism API: What It Is and How to Use It for OP Mainnet

Summary

The Optimism API is the set of JSON-RPC endpoints that let applications read and write data on OP Mainnet, an Ethereum Layer 2 built with optimistic rollups. It follows the same JSON-RPC standard as Ethereum, so you can use familiar libraries like ethers or viem to interact with the chain. This article explains what the Optimism API is, how it differs from Ethereum's API, and how to choose the right endpoint provider for your project.

Quick Answer: What Is the Optimism API?

The Optimism API is the set of JSON-RPC endpoints that let applications read and write data on OP Mainnet, an Ethereum Layer 2 (L2) scaling solution built with optimistic rollups. Because OP Mainnet is EVM-compatible, the Optimism API supports the same standard Ethereum JSON-RPC methods, such as eth_blockNumber, eth_getBalance, and eth_sendRawTransaction. This means you can use familiar libraries like ethers, viem, or web3.js to interact with the chain without learning a new interface.

If you're building on OP Mainnet, you'll need an Optimism API endpoint to connect your dApp to the network. You can run your own node, use a public endpoint, or rely on a managed RPC provider. The right choice depends on your workload, reliability requirements, and budget.

Decision Guide: How to Choose the Right Optimism API Endpoint

Before diving into the technical details, it helps to decide which type of endpoint fits your project. Here's a quick breakdown:

  • Public endpoints are free and easy to use, but they often have rate limits and are not designed for production workloads. They are fine for development, testing, or low-traffic prototypes.
  • Managed RPC providers like OnFinality offer reliable, scalable endpoints with features like WebSocket support, archive data, and dedicated nodes. They are a good fit for production dApps, analytics platforms, and high-traffic applications.
  • Running your own node gives you full control and avoids third-party dependencies, but it requires significant operational effort: you need to maintain the node, handle sync issues, and ensure high availability.

For most production use cases, a managed RPC provider is the pragmatic choice. It lets you focus on your application while the provider handles infrastructure reliability. OnFinality offers RPC pricing that scales with your usage, and you can check the supported RPC networks to see if OP Mainnet is covered.

Optimism API vs. Ethereum API: What's Different?

Because OP Mainnet is an optimistic rollup, its API is almost identical to Ethereum's, but there are a few important differences:

  • Transaction fees: OP Mainnet uses a fee model that includes an L1 data fee, which is the cost of posting transaction data to Ethereum. You can estimate fees using eth_gasPrice or the op-stack specific methods.
  • Finality: Transactions on OP Mainnet are considered final after a challenge period (about 7 days), but for most applications, you can treat a transaction as confirmed once it's included in a block.
  • Chain ID: The chain ID for OP Mainnet is 10, and for Optimism Sepolia testnet it's 11155420. Make sure your wallet and application use the correct chain ID.
  • Additional methods: The Optimism API may include OP-Stack specific methods, such as optimism_syncStatus or eth_getBlockByNumber with L1 attributes, but the core Ethereum methods remain the same.

Setting Up Your Optimism API Connection

To start using the Optimism API, you need an endpoint URL. OnFinality provides a public endpoint for OP Mainnet: https://optimism.api.onfinality.io/public. For the Optimism Sepolia testnet, use https://optimism-sepolia.api.onfinality.io/public. These endpoints support both HTTP and WebSocket transports.

Here's how to connect using viem:

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

const client = createPublicClient({
  chain: optimism,
  transport: http('https://optimism.api.onfinality.io/public'),
});

const blockNumber = await client.getBlockNumber();
console.log('Current block number:', blockNumber);

If you're using ethers v6:

import { ethers } from 'ethers';

const provider = new ethers.JsonRpcProvider('https://optimism.api.onfinality.io/public');
const blockNumber = await provider.getBlockNumber();
console.log('Current block number:', blockNumber);

For a production app, you'll likely want a dedicated endpoint with higher rate limits. OnFinality offers dedicated nodes that give you a private endpoint with configurable capacity.

Optimism API Methods: What You Can Call

The Optimism API supports all standard Ethereum JSON-RPC methods. Here are the most common ones you'll use:

MethodDescriptionExample Use Case
eth_blockNumberGet the latest block numberCheck chain sync status
eth_getBalanceGet the balance of an addressDisplay user balances
eth_callExecute a read-only contract callQuery on-chain data
eth_sendRawTransactionBroadcast a signed transactionSubmit user transactions
eth_getTransactionReceiptGet the receipt of a transactionConfirm transaction status
eth_getLogsFetch event logsIndex smart contract events
eth_estimateGasEstimate gas for a transactionShow gas estimates to users

In addition to these, you may need archive data for historical queries. Archive nodes store the full state history, which is essential for analytics platforms or dApps that need to query past balances. OnFinality supports archive data on OP Mainnet; check the network page for details.

Using WebSocket for Real-Time Updates

If your application needs real-time data, such as pending transactions or new blocks, you can use a WebSocket endpoint. OnFinality's Optimism endpoint supports WebSocket at wss://optimism.api.onfinality.io/public (note: the public URL may differ; check the network page for the exact WebSocket URL).

Here's an example of subscribing to new block headers using viem:

import { createPublicClient, webSocket } from 'viem';
import { optimism } from 'viem/chains';

const client = createPublicClient({
  chain: optimism,
  transport: webSocket('wss://optimism.api.onfinality.io/public'),
});

const unwatch = client.watchBlockNumber({
  onBlockNumber: (blockNumber) => {
    console.log('New block:', blockNumber);
  },
});

WebSocket connections are more resource-intensive, so ensure your provider supports them and that you handle reconnection logic in your application.

Optimism Sepolia Testnet: Testing Your dApp

Before deploying to OP Mainnet, you should test your application on the Optimism Sepolia testnet. The testnet uses the same API but with a different chain ID (11155420) and a different endpoint: https://optimism-sepolia.api.onfinality.io/public. You can get test ETH from a faucet to fund your test transactions.

Here's how to configure your wallet for Optimism Sepolia:

{
  "chainId": 11155420,
  "chainName": "OP Sepolia Testnet",
  "nativeCurrency": {
    "name": "Sepolia Ether",
    "symbol": "ETH",
    "decimals": 18
  },
  "rpcUrls": ["https://optimism-sepolia.api.onfinality.io/public"],
  "blockExplorerUrls": ["https://sepolia-optimism.etherscan.io"]
}

Testing on Sepolia helps you catch issues before they affect real users and lets you validate your integration without spending real ETH.

Common Pitfalls and Troubleshooting

Even with a reliable API, you may encounter issues. Here are some common problems and how to resolve them:

  • Rate limiting: If you're hitting rate limits, consider upgrading to a paid plan or using a dedicated node. OnFinality's RPC pricing offers tiers for different workloads.
  • Incorrect chain ID: Make sure your application uses chain ID 10 for OP Mainnet and 11155420 for Sepolia. Using the wrong chain ID can cause transactions to fail.
  • WebSocket disconnections: WebSocket connections can drop. Implement reconnection logic and handle errors gracefully.
  • Archive data missing: If you need historical data, ensure your provider offers archive nodes. Not all providers do.
  • Transaction finality: Remember that OP Mainnet has a challenge period. For most use cases, you can treat a transaction as final once it's included in a block, but for high-value transactions, you may want to wait for the challenge period to pass.

Key Takeaways

  • The Optimism API is JSON-RPC based and EVM-compatible, so you can use standard Ethereum tools.
  • Choose between public endpoints, managed providers, or self-hosted nodes based on your needs.
  • OnFinality provides reliable Optimism endpoints for both mainnet and testnet, with HTTP and WebSocket support.
  • Use the Optimism Sepolia testnet to test your dApp before deploying to production.
  • Be aware of rate limits, chain IDs, and archive data requirements when building your application.

Frequently Asked Questions

What is the Optimism API?

The Optimism API is a set of JSON-RPC endpoints that allow applications to interact with OP Mainnet, an Ethereum Layer 2 network. It supports standard Ethereum methods, making it easy for developers to build on Optimism.

Is the Optimism API the same as the Ethereum API?

Yes, the Optimism API is largely the same as the Ethereum API because OP Mainnet is EVM-compatible. There are minor differences in fee structure and finality, but the core methods are identical.

How do I get an Optimism API endpoint?

You can use a public endpoint like https://optimism.api.onfinality.io/public or sign up for a managed RPC provider like OnFinality to get a dedicated endpoint with higher limits.

What is the chain ID for Optimism?

OP Mainnet uses chain ID 10, and Optimism Sepolia testnet uses chain ID 11155420.

Does OnFinality support Optimism?

Yes, OnFinality supports OP Mainnet and Optimism Sepolia. You can find more details on the Optimism network page and the Optimism Sepolia page.

RPC Knowledge Base

Related RPC details

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started