Docs

zkSync Era - zkEVM Layer 2 Documentation

Complete guide to zkSync Era integration with Dwellir RPC. Learn how to build on zkSync Era, access JSON-RPC methods, and optimize your dApp performance.

zkSync Era RPC

With Dwellir, you get access to our global zkSync Era network which always routes your API requests to the nearest available location, ensuring low latency and the fastest speeds.

Get your API key

Why Build on zkSync Era?

zkSync Era is the leading zero-knowledge Ethereum Virtual Machine (zkEVM), offering unparalleled scalability without compromising on security or decentralization:

Revolutionary Performance

  • Instant finality - Transactions confirmed in milliseconds
  • 99% lower costs than Ethereum mainnet
  • Zero-knowledge proofs - Mathematical security guarantees

Cryptographic Security

  • Zero-knowledge proofs - Provably secure transactions
  • Ethereum security - Inherits L1 security with ZK enhancements
  • Battle-tested - Proven technology processing millions of transactions

Developer-First Ecosystem

  • Full EVM compatibility - Deploy existing contracts without changes
  • Account abstraction - Native support for advanced wallet features
  • Growing ecosystem - Vibrant DeFi and NFT landscape

Quick Start with zkSync Era

Connect to zkSync Era in seconds with Dwellir's optimized endpoints:

zkSync Era RPC Endpoints
HTTPS
curl -sS -X POST https://api-zksync-era-mainnet-full.n.dwellir.com/<API_Keys_Are_Not_Made_for_Bots> \  -H 'Content-Type: application/json' \  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
import { JsonRpcProvider } from 'ethers';const provider = new JsonRpcProvider(  'https://api-zksync-era-mainnet-full.n.dwellir.com/<API_Keys_Are_Not_Made_for_Bots>');const latest = await provider.getBlockNumber();console.log('block', latest);
import requestsurl = 'https://api-zksync-era-mainnet-full.n.dwellir.com/<API_Keys_Are_Not_Made_for_Bots>'payload = {  'jsonrpc': '2.0', 'id': 1,  'method': 'eth_blockNumber', 'params': []}resp = requests.post(url, json=payload)print(resp.json())
package mainimport (  "bytes"  "fmt"  "io"  "net/http")func main() {  url := "https://api-zksync-era-mainnet-full.n.dwellir.com/<API_Keys_Are_Not_Made_for_Bots>"  payload := []byte(`{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}`)  resp, err := http.Post(url, "application/json",    bytes.NewBuffer(payload))  if err != nil { panic(err) }  defer resp.Body.Close()  body, _ := io.ReadAll(resp.Body)  fmt.Println(string(body))}

Installation & Setup

JavaScript
import { JsonRpcProvider } from 'ethers';

// Connect to zkSync Era mainnet
const provider = new JsonRpcProvider(
  'https://api-zksync-era-mainnet-full.n.dwellir.com/YOUR_API_KEY'
);

// Get the latest block
const block = await provider.getBlock('latest');
console.log('Latest block:', block.number);

// Query account balance
const balance = await provider.getBalance('0x000000000000000000000000000000000000800a');
console.log('Balance:', balance.toString());
JavaScript
const Web3 = require('web3');

// Connect to zkSync Era mainnet
const web3 = new Web3(
  'https://api-zksync-era-mainnet-full.n.dwellir.com/YOUR_API_KEY'
);

// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to zkSync Era:', chainId === 324);

// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
TypeScript
import { createPublicClient, http } from 'viem';
import { zkSync } from 'viem/chains';

// Create zkSync Era client
const client = createPublicClient({
  chain: zkSync,
  transport: http('https://api-zksync-era-mainnet-full.n.dwellir.com/YOUR_API_KEY'),
});

// Read USDC balance
const data = await client.readContract({
  address: '0x3355df6D4c9C3035724Fd0e3914dE96A5a83aaf4',
  abi: contractAbi,
  functionName: 'balanceOf',
  args: ['0x000000000000000000000000000000000000800a'],
});

Network Information

ParameterValueDetails
Chain ID324Mainnet
Block Time< 1 secondInstant finality
Gas TokenETHNative token
RPC StandardEthereumJSON-RPC 2.0

API Reference

zkSync Era supports the full Ethereum JSON-RPC API specification with EVM compatibility. Access all standard methods with zero-knowledge proof security.

Common Integration Patterns

Transaction Monitoring

Monitor pending and confirmed transactions with instant finality:

JavaScript
// Watch for transaction confirmation on zkSync Era
async function waitForTransaction(txHash) {
  const receipt = await provider.waitForTransaction(txHash, 1);

  // zkSync Era specific: Instant finality
  console.log('Transaction confirmed:', receipt.status === 1);
  console.log('Block number:', receipt.blockNumber);

  return receipt;
}

Gas Optimization

Optimize gas costs on zkSync Era with native account abstraction:

JavaScript
// Estimate gas for zkSync Era transaction
const gasEstimate = await provider.estimateGas(tx);

// Get current gas price
const gasPrice = await provider.getGasPrice();

// Calculate total cost (no L1 data fees on zkSync Era)
const totalCost = gasEstimate * gasPrice;

// zkSync Era supports paying fees with any ERC20 token
console.log('Total cost in ETH:', totalCost.toString());

Event Filtering

Efficiently query contract events on zkSync Era:

JavaScript
// Query events with automatic retry and pagination
async function getEvents(contract, eventName, fromBlock = 0) {
  const filter = contract.filters[eventName]();
  const events = [];
  const batchSize = 10000; // zkSync Era supports larger batch sizes

  for (let i = fromBlock; i <= currentBlock; i += batchSize) {
    const batch = await contract.queryFilter(
      filter,
      i,
      Math.min(i + batchSize - 1, currentBlock)
    );
    events.push(...batch);
  }

  return events;
}

Performance Best Practices

1. Batch Requests

Combine multiple RPC calls for optimal performance:

JavaScript
const batch = [
  { method: 'eth_blockNumber', params: [] },
  { method: 'eth_gasPrice', params: [] },
  { method: 'eth_getBalance', params: [address, 'latest'] }
];

const results = await provider.send(batch);

2. Connection Pooling

Reuse provider instances to minimize connection overhead:

JavaScript
// Singleton pattern for provider
class ZkSyncProvider {
  static instance = null;

  static getInstance() {
    if (!this.instance) {
      this.instance = new JsonRpcProvider(
        'https://api-zksync-era-mainnet-full.n.dwellir.com/YOUR_API_KEY'
      );
    }
    return this.instance;
  }
}

3. Smart Caching

Cache immutable data to reduce API calls:

JavaScript
const cache = new Map();

async function getCachedBlockData(blockNumber) {
  const key = `block_${blockNumber}`;

  if (!cache.has(key)) {
    const block = await provider.getBlock(blockNumber);
    cache.set(key, block);
  }

  return cache.get(key);
}

Troubleshooting Common Issues

Error: "Insufficient funds"

zkSync Era transactions require ETH for gas fees, but also support ERC20 fee payments:

JavaScript
// Check ETH balance for gas fees
const balance = await provider.getBalance(address);
const gasEstimate = await provider.estimateGas(tx);
const gasPrice = await provider.getGasPrice();
const totalRequired = gasEstimate * gasPrice + tx.value;

if (balance < totalRequired) {
  console.log(`Need ${totalRequired - balance} more ETH`);
  // Alternative: Use paymaster for ERC20 fee payment
}

Error: "Transaction underpriced"

zkSync Era uses dynamic gas pricing. Always use current fee data:

JavaScript
// Get current fee data
const feeData = await provider.getFeeData();

const tx = {
  to: recipient,
  value: amount,
  maxFeePerGas: feeData.maxFeePerGas,
  maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
  gasLimit: 21000n,
  type: 2 // EIP-1559 transaction
};

Error: "Rate limit exceeded"

Implement exponential backoff for resilient applications:

JavaScript
async function callWithRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.code === 429 && i < maxRetries - 1) {
        await new Promise(r => setTimeout(r, 2 ** i * 1000));
      } else {
        throw error;
      }
    }
  }
}

Migration Guide

From Ethereum Mainnet

Moving from L1 to zkSync Era requires minimal changes:

JavaScript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');

// After (zkSync Era)
const provider = new JsonRpcProvider(
  'https://api-zksync-era-mainnet-full.n.dwellir.com/YOUR_API_KEY'
);

// Smart contracts work identically (EVM compatible)
// Same tooling and libraries
// Account abstraction support
// Note: Different chain ID (324)
// Note: Separate block numbers
// Note: Zero-knowledge proof finality

Smoke Tests

Verify your zkSync Era integration with these quick tests:

JavaScript
// Test 1: Verify chain connection
const chainId = await provider.send('eth_chainId', []);
console.assert(parseInt(chainId, 16) === 324, 'Connected to zkSync Era');

// Test 2: Check latest block
const blockNumber = await provider.send('eth_blockNumber', []);
console.log('Latest block:', parseInt(blockNumber, 16));

// Test 3: Query a known contract (USDC)
const usdcBalance = await provider.send('eth_call', [{
  to: '0x3355df6D4c9C3035724Fd0e3914dE96A5a83aaf4',
  data: '0x70a08231000000000000000000000000000000000000000000000000000000000000800a'
}, 'latest']);
console.log('USDC balance call successful:', usdcBalance);

Resources & Tools

Official Resources

Developer Tools

Need Help?


Start building on zkSync Era with Dwellir's enterprise-grade RPC infrastructure. Get your API key