The OP Stack is a collaborative, decentralized development stack that only gets more powerful as more people contribute. Code for the OP Stack should follow the stack’s [design principles](./understand/design-principles.md), which means it should be entirely open source and accessible for people to hack on, contribute to, and extend. The Optimism Collective wins when it works together. ♥️✨
Whether you’re a budding protocol developer, dapp developer, bounty hunter, documentation editor, content creator, or anything in between, the OP Stack always has something for you to contribute to. Every contribution makes a difference — no contribution is too small.
If you’re looking to find a way to contribute, check out one of the following contributor pathways below. Come make your first contribution today!
## Component contributions
The OP Stack is a decentralized development stack. Anyone can contribute components that can be considered part of the OP Stack as long as as those components fit [the stack’s design principles and goals](./understand/design-principles.md). To start contributing components to the stack, check out some of [these useful ideas](https://github.com/ethereum-optimism/optimism-project-ideas) and get to building! And don’t forget that projects can also receive funding from the Collective via RetroPGF.
If you’d like to contribute to existing OP Stack code, rather than creating new components, check out [the current release of the OP Stack](./releases/README.md#current-release). Any contributions to existing OP Stack components are highly appreciated. If you’re looking for a good way to make your first contribution, check out the [Good First Issues](https://github.com/ethereum-optimism/optimism/contribute) on the Optimism Monorepo.
## Bounty hunting
The OP Stack needs YOU (yes you!) to help review the codebase for bugs and vulnerabilities. If you’re interested in bounty hunting, check out our Security Policy, Vulnerability Reporting, and Bug Bounties page.
## Documentation help
Spot a typo in these docs? See something that could be a little clearer? Head over to the Optimism Monorepo where the OP Stack docs are hosted and make a pull request. No contribution is too small!
## Community contributions
If you’re looking for other ways to get involved, here are a few options:
- Grab an idea from the [project ideas list](https://github.com/ethereum-optimism/optimism-project-ideas) to and building
- Suggest a new idea for the [project ideas list](https://github.com/ethereum-optimism/optimism-project-ideas)
- Improve the [Optimism Community Hub](https://community.optimism.io/)[documentation](https://github.com/ethereum-optimism/community-hub) or [tutorials](https://github.com/ethereum-optimism/optimism-tutorial)
- Become an Optimism Ambassador, Support Nerd, and more in the [Optimism Discord](https://discord-gateway.optimism.io/)
The OP Stack is the decentralized development stack that powers Optimism. The current release of the OP Stack (named “Bedrock”) was designed to facilitate the creation of L2 blockchains that can interoperate with the proposed [Optimism Superchain](https://optimism.mirror.xyz/fLk5UGjZDiXFuvQh6R_HscMQuuY9ABYNF7PI76-qJYs). The Superchain is a proposed network of rollups that share a security model, communication protocols, and a common development stack (the OP Stack itself). **The best way to get started building with the OP Stack today is to launch your own Bedrock-based Rollup by following our guide to [Getting started with an OP Stack chain](./build/getting-started.md)**. Bedrock Rollups will be compatible with the Superchain.
## Blog posts
-[Introducing the OP Stack (Oct. 17, 2022)](https://optimism.mirror.xyz/fLk5UGjZDiXFuvQh6R_HscMQuuY9ABYNF7PI76-qJYs)
<!--
## Videos
- Karl’s Dev Bogota talk (Oct. 14, 2022)
<iframewidth="560"height="315"src="[https://www.youtube.com/embed/HiU-g8XHi5s](https://www.youtube.com/embed/HiU-g8XHi5s)"title="YouTube video player"frameborder="0"allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"allowfullscreen></iframe>
The OP Stack is the decentralized development stack that powers Optimism. The current release of the OP Stack (named “Bedrock”) was designed to facilitate the creation of L2 blockchains that can interoperate with the proposed [Optimism Superchain](https://optimism.mirror.xyz/fLk5UGjZDiXFuvQh6R_HscMQuuY9ABYNF7PI76-qJYs). The Superchain is a proposed network of rollups that share a security model, communication protocols, and a common development stack (the OP Stack itself). **The best way to get started building with the OP Stack today is to launch your own Bedrock-based Rollup by following our guide to [Running a Bedrock Rollup](./getting-started.md)**. Bedrock Rollups will be compatible with the Superchain.
You can also experiment with the OP Stack by making modifications to its various components. The OP Stack, as of the Bedrock release, is not explicitly designed to handle any significant modifications out of the box. By modifying the components of the OP Stack, you will likely no longer be compatible with the Superchain. Please also note that there is limited developer support available for modifications to the OP Stack. Have fun, but modify the stack at your own risk!
The OP Stack is a flexible platform with various configuration values that you can tweak to fit your specific needs. If you’re looking to fine-tune your deployment, look no further.
::: warning 🚧 Work in Progress
OP Stack configuration is an active work in progress and will likely evolve significantly as time goes on. If something isn’t working about your configuration, check back with this page to see if anything has changed.
:::
## New Blockchain Configuration
New OP Stack blockchains are currently configured with a JSON file inside the Optimism repository. The file is `<optimism repository>/packages/contracts-bedrock/deploy-config/<chain name>.json`. For example, [this is the configuration file for the tutorial blockchain](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/deploy-config/getting-started.json).
### Admin accounts
| Key | Type | Description | Default / Recommended value |
| --- | --- | --- | --- |
| `finalSystemOwner` | L1 Address | Address that will own all ownable contracts on L1 once the deployment is finished, including the `ProxyAdmin` contract. | It is recommended to have a single admin account to retain a common security model. |
| `controller` | L1 Address | Address that will own the `SystemDictator` contract and can therefore control the flow of the deployment or upgrade. | It is recommended to have a single admin account to retain a common security model. |
| `proxyAdminOwner` | L2 Address | Address that will own the `ProxyAdmin` contract on L2. The L2 `ProxyAdmin` contract owns all of the `Proxy` contracts for every predeployed contract in the range `0x42...0000` to `0x42..2048`. This makes predeployed contracts easily upgradeable. | It is recommended to have a single admin account to retain a common security model. |
### Fee recipients
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `baseFeeVaultRecipient` | L1 Address | L1 address that the base fees from all transactions on the L2 can be withdrawn to. | It is recommended to have a single admin account to retain a common security model. |
| `l1FeeVaultRecipient` | L1 Address | L1 address that the L1 data fees from all transactions on the L2 can be withdrawn to. | It is recommended to have a single admin account to retain a common security model. |
| `sequencerFeeVaultRecipient` | L1 Address | L1 address that the tip fees from all transactions on the L2 can be withdrawn to. | It is recommended to have a single admin account to retain a common security model. |
### Misc.
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `numDeployConfirmations` | Number of blocks | Number of confirmations to wait when deploying smart contracts to L1. | 1 |
| `l1StartingBlockTag` | Block hash | Block tag for the L1 block where the L2 chain will begin syncing from. Generally recommended to use a finalized block to avoid issues with reorgs. | |
| `l1ChainID` | Number | Chain ID of the L1 chain. | 1 for L1 Ethereum mainnet, <br> 5 for the Goerli test network. <br>[See here for other blockchains](https://chainlist.org/?testnets=true). |
| `l2ChainID` | Number | Chain ID of the L2 chain. | 42069 |
### Blocks
These fields apply to L2 blocks: Their timing, when do they need to be written to L1, and how they get written.
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `l2BlockTime` | Number of seconds | Number of seconds between each L2 block. | 2 |
| `maxSequencerDrift` | Number of seconds | How far the L2 timestamp can differ from the actual L1 timestamp | 600 (10 minutes) |
| `sequencerWindowSize` | Number of blocks | Maximum number of L1 blocks that a Sequencer can wait to incorporate the information in a specific L1 block. For example, if the window is `10` then the information in L1 block `n` must be incorporated by L1 block `n+10`. | 3600 (12 hours) |
| `channelTimeout` | Number of blocks | Maximum number of L1 blocks that a transaction channel frame can be considered valid. A transaction channel frame is a chunk of a compressed batch of transactions. After the timeout, the frame is dropped. | 300 (1 hour) |
| `p2pSequencerAddress` | L1 Address | Address of the key that the Sequencer uses to sign blocks on the p2p network. | Sequencer, an address for which you own the private key |
| `batchInboxAddress` | L1 Address | Address that Sequencer transaction batches are sent to on L1. | 0xff00…0042069 |
| `batchSenderAddress` | L1 Address | Address of the account that nodes will filter for when searching for Sequencer transaction batches being sent to the `batchInboxAddress`. Can be updated later via the `SystemConfig` contract on L1. | Batcher, an address for which you own the private key |
### Proposal fields
These fields apply to output root proposals.
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `l2OutputOracleStartingBlockNumber` | Number | Block number of the first OP Stack block. Typically this should be zero, but this may be non-zero for networks that have been upgraded from a legacy system (like Optimism Mainnet). Will be removed with the addition of permissionless proposals. | 0 |
| `l2OutputOracleStartingTimestamp` | Number | Timestamp of the first OP Stack block. This MUST be the timestamp corresponding to the block defined by the `l1StartingBlockTag`. Will be removed with the addition of permissionless proposals. | |
| `l2OutputOracleSubmissionInterval` | Number of blocks | Number of blocks between proposals to the `L2OutputOracle`. Will be removed with the addition of permissionless proposals. | 120 (24 minutes) |
| `finalizationPeriodSeconds` | Number of seconds | Number of seconds that a proposal must be available to challenge before it is considered finalized by the `OptimismPortal` contract. | We recommend 12 on test networks, seven days on production ones |
| `l2OutputOracleProposer` | L1 Address | Address that is allowed to submit output proposals to the `L2OutputOracle` contract. Will be removed when we have permissionless proposals. | |
| `l2OutputOracleChallenger` | L1 Address | Address that is allowed to challenge output proposals submitted to the `L2OutputOracle`. Will be removed when we have permissionless challenges. | It is recommended to have a single admin account to retain a common security model. |
### L1 data fee
These fields apply to the cost of the [L1 data fee](https://community.optimism.io/docs/developers/build/transaction-fees/#the-l1-data-fee) for L2 transactions.
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `gasPriceOracleOverhead` | Number | Fixed L1 gas overhead per transaction. Default value will likely be adjusted with more information from the Optimism Goerli deployment. | 2100 |
| `gasPriceOracleScalar` | Number | Dynamic L1 gas overhead per transaction, given in 6 decimals. Default value of 1000000 implies a dynamic gas overhead of exactly 1x (no overhead). | 1000000 |
### EIP 1559 gas algorithm
These fields apply to [the EIP 1559 algorithm](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md) used for the [L2 execution costs](https://community.optimism.io/docs/developers/build/transaction-fees/#the-l2-execution-fee) of transactions on the blockchain.
| Key | Type | Description | Default value | Value on L1 Ethereum |
| --- | --- | --- | --- | --- |
| `eip1559Denominator` | Number | Denominator used for the [EIP1559 gas pricing mechanism on L2](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). A larger denominator decreases the amount by which the base fee can change in a single block. | 50 | 8 |
| `eip1559Elasticity` | Number | Elasticity for the [EIP1559 gas pricing mechanism on L2](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md). A larger elasticity increases the maximum allowable gas limit per block. | 10 | 2 |
| `l2GenesisBlockGasLimit` | String | Initial block gas limit, represented as a hex string. Default is 25m, implying a 2.5m target when combined with a 10x elasticity. | 0x17D7840 | |
| `l2GenesisBlockBaseFeePerGas` | String | Initial base fee, used to avoid an unstable EIP1559 calculation out of the gate. Initial value is 1 gwei. | 0x3b9aca00 | |
### Governance token
The governance token is a side-effect of use of the OP Stack in the Optimism Mainnet network. It may not be included by default in future releases.
| Key | Type | Description | Default value |
| --- | --- | --- | --- |
| `governanceTokenOwner` | L2 Address | Address that will own the token contract deployed by default to every OP Stack based chain. | |
| `governanceTokenSymbol` | String | Symbol for the token deployed by default to each OP Stack chain. | OP |
| `governanceTokenName` | String | Name for the token deployed by default to each OP Stack chain. | Optimism |
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
## Overview
The Data Availability Layer is responsible for the *ordering* and *storage* of the raw input data that forms the backbone of an OP Stack based chain (transactions, state roots, calls from other blockchains, etc.). You can conceptually think of this as an array of inputs — the ordering of this array should remain stable and the contents of this array should remain available. Unstable ordering of inputs will lead to reorgs of the OP Stack chain, while unavailable inputs will cause the OP Stack chain to halt entirely.
## Default
The default Data Availability Layer module for an OP Stack chain is the Ethereum DA module. When using the Ethereum DA module, all raw input data is expected to be found on Ethereum. Any data that is accessible on Ethereum can be queried when using this module, including calldata, events, and other block data.
## Security
OP Stack based chains are functions of the raw input data found on the Data Availability Layer module(s) used. If a required piece of data is not available, nodes will not be able to properly sync the chain. This also means that these nodes will not be able to dispute any invalid state proposals made to a Settlement Layer module. An OP Stack based chain cannot be safer than the Data Availability module.
You should be careful to understand the security properties of any Data Availability module(s) that you use. The standard Ethereum DA module generally provides the best security guarantees at the cost of higher transaction fees. Alternative DA modules may be appropriate depending on your particular use-case and risk tolerance.
## Modding
### Alternative EVM DA
A simple modification is to use an EVM-based blockchain other than Ethereum as the Data Availability Layer. Doing so simply requires using an L1 RPC other than Ethereum.
### EVM-Ordered Alternative DA
A more involved modification to the Data Availability Layer is an "EVM-Ordered" Alternative DA module. This involves using an EVM-based chain to maintain the *ordering* of transaction data while using a different data storage system to host the underlying data. Generally, ordering is maintained by publishing hashes of the data to the EVM-based chain while publishing the preimages to those hashes to the alternative data source.
An EVM-Ordered Alternative DA module significantly reduces costs by only publishing hashes and not full input data to the EVM chain. Using an EVM chain for ordering also reduces the number of changes that must be made to the standard Rollup configuration to achieve this result.
An example of an EVM-Ordered Alternative DA module can be found within [this modification to the OP Stack](https://github.com/celestiaorg/optimism/pull/3) that uses the Celestia blockchain as a third-party data availability provider.
### Non-EVM DA
A non-EVM DA module uses a chain not based on the EVM to manage both the ordering and storage of raw input data. Such a modification would require relatively significant modifications to the [derivation portion](https://github.com/ethereum-optimism/optimism/tree/develop/op-node/rollup/derive) of the `op-node`. No such fully-independent DA modules have been developed yet — be the first!
### Multiple DA
It is possible to use multiple Data Availability Layer modules at the same time. For instance, one could source data from two EVM-based chains simultaneously in order to form a bridge between the two chains. When using multiple Data Availability Layer modules, it is imperative to establish a global ordering between the two chains. One option for establishing this ordering is to use the timestamps of blocks from each chain.
Like a non-EVM DA module, a system with multiple Data Availability modules would need to make significant modifications to the [derivation portion](https://github.com/ethereum-optimism/optimism/tree/develop/op-node/rollup/derive) of the `op-node`. No such projects have been constructed yet.
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
## Overview
The Derivation layer is responsible for parsing the raw inputs from the Data Availability layer and converting them into [Engine API](https://github.com/ethereum/execution-apis/tree/main/src/engine) payloads to be sent to the Execution layer. The Derivation Layer is generally tightly coupled to the Data Availability layer because it must understand both the APIs for the Data Availability layer module(s) of choice and the format of the raw data published to the chosen module(s).
## Default
The default Derivation layer module is the Rollup module. This module derives transactions from three sources: Sequencer transactions, user deposits, and L1 blocks. The Rollup module also enforces certain ordering properties that, for example, guarantee that user deposits are always included in the L2 chain within a certain configurable amount of time.
## Security
Modifying the Derivation layer can have unintended consequences. For example, removing or extending the time window in which user deposits must be included can allow a Sequencer to censor the L2 chain. Because of the flexibility of the Derivation layer, the exact impact of any change is likely to be unique to the specifics of the change. The negative impacts of any modifications should be carefully considered on a case-by-case basis.
## Modding
### EVM Event-Triggered Transactions
The default Rollup configuration of the OP Stack includes “deposited” transactions that are triggered whenever a specific event is emitted by the `OptimismPortal` contract on L1. Using the same principle, an OP Stack chain can derive transactions from events emitted by *any* contract on an EVM-based DA. Refer to [attributes.go](https://github.com/ethereum-optimism/optimism/blob/e468b66efedc5f47f4e04dc1acc803d4db2ce383/op-node/rollup/derive/attributes.go#L70) to understand how deposited transactions are derived and how custom transactions can be created.
### EVM Block-Triggered Transactions
Like with events, transactions on an OP Stack chain can be triggered whenever a new block is published on an EVM-based DA. The default Rollup configuration of the OP Stack already includes a block-triggered transaction in the form of [the “L1 info” transaction](https://github.com/ethereum-optimism/optimism/blob/e468b66efedc5f47f4e04dc1acc803d4db2ce383/op-node/rollup/derive/attributes.go#L103) that relays information like the latest block hash, timestamp, and base fee into L2. The Getting Started guide demonstrates the addition of a new block-triggered transaction in the form of a new transaction that reports the amount of gas burned via the base fee on L1.
### And much, much more…
The Derivation layer is one of the most flexible layers of the stack. Transactions can be generated from all sorts of raw input data and can be triggered from all sorts of conditions. You can derive transactions from any piece of data that can be found in the Data Availability layer modules!
[Tutorial: Adding attributes to the derivation function](./tutorials/add-attr.md).
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
## Overview
The Execution Layer is responsible for defining the format of state and the state transition function on L2. It is expected to trigger the state transition function when it receives a payload via the [Engine API](https://github.com/ethereum/execution-apis/tree/main/src/engine). Although the default Execution Layer module is the EVM, you can replace the EVM with any alternative VM as long as it sits behind the Engine API.
## Default
The default Execution Layer module is the Rollup EVM module. The Rollup EVM module utilizes a very lightly modified EVM that adds support for transactions that are triggered by smart contracts on L1 and introduces an L1 data fee to each transaction that accounts for the cost of publishing user transactions to L1. You can find the full set of differences between the standard EVM and the Rollup EVM [on this page](https://op-geth.optimism.io/).
## Security
As with modifications to the Derivation Layer, modifications to the Execution Layer can have unintended consequences. For instance, modifications to the EVM may break existing tooling or may open the door to denial of service attacks. Consider the impact of each modification carefully on a case-by-case basis.
## Modding
### EVM Tweaks
The default Execution Layer module is the EVM. It’s possible to modify the EVM in many different ways like adding new precompiles or inserting predeployed smart contracts into the genesis state. Precompiles can help make common smart contract operations cheaper and can therefore further reduce the cost of execution for your specific use-case. These modifications should be made directly to [the execution client](https://github.com/ethereum-optimism/op-geth).
It’s also possible to create alternative execution client implementations to improve the security properties of your chain. Note that if you modify the EVM, you must apply the same modifications to every execution client that you would like to support.
### Alternative VMs
The OP Stack allows you to replace the EVM with *any* state transition function, as long as the transition can be triggered via the Engine API. This has, for example, been used to implement an OP Stack chain that runs a GameBoy emulator rather than the EVM.
[Tutorial: Adding a precompile](./tutorials/new-precomp.md).
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
## Overview
Featured Hacks is a compilation of some of the cool stuff people are building on top of the OP Stack!
## OPCraft
### Author
[Lattice](https://lattice.xyz/)
### Description
OPCraft was an OP Stack chain that ran a modified EVM as the backend for a fully on-chain 3D voxel game built with [MUD](https://mud.dev/).
### OP Stack Configuration
- Data Availability: Ethereum DA (Goerli)
- Sequencer: Single Sequencer
- Derivation: Standard Rollup
- Execution: Modified Rollup EVM
### Links
-[Announcing OPCraft: an Autonomous World built on the OP Stack](https://dev.optimism.io/opcraft-autonomous-world/)
-[OPCraft Explorer](https://opcraft.mud.dev/)
-[OPCraft on GitHub](https://github.com/latticexyz/opcraft)
-[MUD](https://mud.dev/)
## Ticking Optimism
### Author
[@therealbytes](https://twitter.com/therealbytes)
### Description
Ticking Optimism is a proof-of-concept implementation of an OP Stack chain that calls a `tick` function every block. By using the OP Stack, Ticking Optimism avoids the need for off-chain infrastructure to execute a function on a regular basis. Ticking Conway is a system that uses Ticking Optimism to build [Conway’s Game of Life](https://conwaylife.com/) on-chain.
### OP Stack Configuration
- Data Availability: Ethereum DA (any)
- Sequencer: Single Sequencer
- Derivation: Standard Rollup with custom `tick` function
- Execution: Rollup EVM
### Links
-[Ticking Optimism on GitHub](https://github.com/therealbytes/ticking-optimism)
-[Ticking Conway on GitHub](https://github.com/therealbytes/ticking-conway)
Hello! This Getting Started guide is meant to help you kick off your OP Stack journey by taking you through the process of spinning up your very own OP Stack chain on the Ethereum Goerli testnet. You can use this chain to perform tests and prepare for the superchain, or you can modify it to adapt it to your own needs (which may make it incompatible with the superchain in the future).
## Know before you go
Before we kick off, note that this is a relatively long tutorial! You should prepare to set aside an hour or two to get everything running. Here’s an itemized list of what we’re about to do:
1. Install dependencies
2. Build the source code
3. Generate and fund accounts and private keys
4. Configure your network
5. Deploy the L1 contracts
6. Initialize op-geth
7. Run op-geth
8. Run op-node
9. Get some Goerli ETH on your L2
10. Send some test transactions
11. Celebrate!
## Prerequisites
You’ll need the following software installed to follow this tutorial:
We’re going to be spinning up an EVM Rollup from the OP Stack source code. You could use docker images, but this way we keep the option to modify component behavior if you need to do so. The OP Stack source code is split between two repositories, the [Optimism Monorepo](https://github.com/ethereum-optimism/optimism) and the [`op-geth`](https://github.com/ethereum-optimism/op-geth) repository.
### Build the Optimism Monorepo
1. Clone the [Optimism Monorepo](https://github.com/ethereum-optimism/optimism).
Since we’re deploying our OP Stack chain to Goerli, you’ll need to have access to a Goerli L1 node. You can either use a node provider like [Alchemy](https://www.alchemy.com/)(easier) or [run your own Goerli node](https://notes.ethereum.org/@launchpad/goerli)(harder).
## Generate some keys
You’ll need four accounts and their private keys when setting up the chain:
- The `Admin` account which has the ability to upgrade contracts.
- The `Batcher` account which publishes Sequencer transaction data to L1.
- The `Proposer` account which publishes L2 transaction results to L1.
- The `Sequencer` account which signs blocks on the p2p network.
You can generate all of these keys with the `rekey` tool in the `contracts-bedrock` package.
1. Enter the Optimism Monorepo:
```bash
cd optimism
```
1. Move into the `contracts-bedrock` package:
```bash
cd packages/contracts-bedrock
```
1. Run the `rekey` command:
```bash
npx hardhat rekey
```
You should get an output like the following:
```
Mnemonic: barely tongue excite actor edge huge lion employ gauge despair this learn
Save these accounts and their respective private keys somewhere, you’ll need them later. Fund the `Admin` address with a small amount of Goerli ETH as we’ll use that account to deploy our smart contracts. You’ll also need to fund the `Proposer` and `Batcher` address — note that the `Batcher` burns through the most ETH because it publishes transaction data to L1.
Recommended funding amounts are as follows:
-`Admin` — 0.2 ETH
-`Proposer` — 0.5 ETH
-`Batcher` — 1.0 ETH
::: danger Not for production deployments
The `rekey` tool is *not* designed for production deployments. If you are deploying an OP Stack based chain into production, you should likely be using a combination of hardware security modules and hardware wallets.
:::
## Configure your network
Once you’ve built both repositories, you’ll need head back to the Optimism Monorepo to set up the configuration for your chain. Currently, chain configuration lives inside of the [`contracts-bedrock`](https://github.com/ethereum-optimism/optimism/tree/develop/packages/contracts-bedrock) package.
1. Enter the Optimism Monorepo:
```bash
cd ~/optimism
```
1. Move into the `contracts-bedrock` package:
```bash
cd packages/contracts-bedrock
```
1. Before we can create our configuration file, we’ll need to pick an L1 block to serve as the starting point for our Rollup. It’s best to use a finalized L1 block as our starting block. You can use the `cast` command provided by Foundry to grab all of the necessary information (replace `<RPC>` with the URL for your L1 Goerli node):
1. Fill out the remainder of the pre-populated config file found at [`deploy-config/getting-started.json`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/deploy-config/getting-started.json). Use the default values in the config file and make following modifications:
- Replace `"ADMIN"` with the address of the Admin account you generated earlier.
- Replace `"PROPOSER"` with the address of the Proposer account you generated earlier.
- Replace `"BATCHER"` with the address of the Batcher account you generated earlier.
- Replace `"SEQUENCER"` with the address of the Sequencer account you generated earlier.
- Replace `"BLOCKHASH"` with the blockhash you got from the `cast` command.
- Replace `"TIMESTAMP"` with the timestamp you got from the `cast` command. Note that although all the other fields are strings, this field is a number! Don’t include the quotation marks.
## Deploy the L1 contracts
Once you’ve configured your network, it’s time to deploy the L1 smart contracts necessary for the functionality of the chain.
1. Inside of `contracts-bedrock`, copy `.env.example` to `.env`.
```sh
cp .env.example .env
```
1. Fill out the two environment variables inside of that file:
- `L1_RPC` — URL for your L1 node.
- `PRIVATE_KEY_DEPLOYER` — Private key of the `Admin` account.
1. Once you’re ready, deploy the L1 smart contracts:
```bash
npx hardhat deploy --network getting-started
```
Contract deployment can take up to 15 minutes. Please wait for all smart contracts to be fully deployed before continuing to the next step.
## Generate the L2 config files
We’ve set up the L1 side of things, but now we need to set up the L2 side of things. We do this by generating three important files, a `genesis.json` file, a `rollup.json` configuration file, and a `jwt.txt`[JSON Web Token](https://jwt.io/introduction) that allows the `op-node` and `op-geth` to communicate securely.
1. Head over to the `op-node` package:
```bash
cd ~/optimism/op-node
```
1. Run the following command, and make sure to replace `<RPC>` with your L1 RPC URL:
You should then see the `genesis.json` and `rollup.json` files inside the `op-node` package.
1. Next, generate the `jwt.txt` file with the following command:
```bash
openssl rand -hex 32 > jwt.txt
```
1. Finally, we’ll need to copy the `genesis.json` file and `jwt.txt` file into `op-geth` so we can use it to initialize and run `op-geth` in just a minute:
```bash
cp genesis.json ~/op-geth
cp jwt.txt ~/op-geth
```
## Initialize op-geth
We’re almost ready to run our chain! Now we just need to run a few commands to initialize `op-geth`. We’re going to be running a Sequencer node, so we’ll need to import the `Sequencer` private key that we generated earlier. This private key is what our Sequencer will use to sign new blocks.
1. Head over to the `op-geth` repository:
```bash
cd ~/op-geth
```
1. Create a data directory folder:
```bash
mkdir datadir
```
1. Put a password file into the data directory folder:
```bash
echo "pwd" > datadir/password
```
1. Put the `Sequencer` private key into the data directory folder (don’t include a “0x” prefix):
Whew! We made it. It’s time to run `op-geth` and get our system started.
Run `op-geth` with the following command. Make sure to replace `<SEQUENCER>` with the address of the `Sequencer` account you generated earlier.
```bash
./build/bin/geth \
--datadir ./datadir \
--http\
--http.corsdomain="*"\
--http.vhosts="*"\
--http.addr=0.0.0.0 \
--http.api=web3,debug,eth,txpool,net,engine \
--ws\
--ws.addr=0.0.0.0 \
--ws.port=8546 \
--ws.origins="*"\
--ws.api=debug,eth,txpool,net,engine \
--syncmode=full \
--gcmode=full \
--nodiscover\
--maxpeers=0 \
--networkid=42069 \
--authrpc.vhosts="*"\
--authrpc.addr=0.0.0.0 \
--authrpc.port=8551 \
--authrpc.jwtsecret=./jwt.txt \
--rollup.disabletxpoolgossip=true\
--password=./datadir/password \
--allow-insecure-unlock\
--mine\
--miner.etherbase=<SEQUENCER> \
--unlock=<SEQUENCER>
```
And `op-geth` should be running! You should see some output, but you won’t see any blocks being created yet because `op-geth` is driven by the `op-node`. We’ll need to get that running next.
## Run op-node
Once we’ve got `op-geth` running we’ll need to run `op-node`. Like Ethereum, the OP Stack has a consensus client (the `op-node`) and an execution client (`op-geth`). The consensus client drives the execution client over the Engine API.
Head over to the `op-node` package and start the `op-node` using the following command. Replace `<SEQUENCERKEY>` with the private key for the `Sequencer` account, replace `<RPC>` with the URL for your L1 node, and replace `<RPCKIND>` with the kind of RPC you’re connected to. Although the `l1.rpckind` argument is optional, setting it will help the `op-node` optimize requests and reduce the overall load on your endpoint. Available options for the `l1.rpckind` argument are `"alchemy"`, `"quicknode"`, `"quicknode"`, `"parity"`, `"nethermind"`, `"debug_geth"`, `"erigon"`, `"basic"`, and `"any"`.
```bash
./bin/op-node \
--l2=http://localhost:8551 \
--l2.jwt-secret=./jwt.txt \
--sequencer.enabled \
--sequencer.l1-confs=3 \
--verifier.l1-confs=3 \
--rollup.config=./rollup.json \
--rpc.addr=0.0.0.0 \
--rpc.port=8547 \
--p2p.listen.ip=0.0.0.0 \
--p2p.listen.tcp=9003 \
--p2p.listen.udp=9003 \
--rpc.enable-admin \
--p2p.sequencer.key=<SEQUENCERKEY> \
--l1=<RPC> \
--l1.rpckind=<RPCKIND>
```
Once you run this command, you should start seeing the `op-node` begin to process all of the L1 information after the starting block number that you picked earlier. Once the `op-node` has enough information, it’ll begin sending Engine API payloads to `op-geth`. At that point, you’ll start to see blocks being created inside of `op-geth`. We’re live!
If `op-node` errors out and exits, you might need to reinitialize `op-geth`:
The final component necessary to put all the pieces together is the `op-batcher`. The `op-batcher` takes transactions from the Sequencer and publishes those transactions to L1. Once transactions are on L1, they’re officially part of the Rollup. Without the `op-batcher`, transactions sent to the Sequencer would never make it to L1 and wouldn’t become part of the canonical chain. The `op-batcher` is critical!
1. Head over to the `op-batcher` package inside the Optimism Monorepo:
```bash
cd ~/optimism/op-batcher
```
1. And run the `op-batcher` using the following command. Replace `<RPC>` with your L1 node URL and replace `<BATCHERKEY>` with the private key for the `Batcher` account that you created and funded earlier. It’s best to give the `Batcher` at least 1 Goerli ETH to ensure that it can continue operating without running out of ETH for gas.
```bash
./bin/op-batcher \
--l2-eth-rpc=http://localhost:8545 \
--rollup-rpc=http://localhost:8547 \
--poll-interval=1s \
--sub-safety-margin=6 \
--num-confirmations=1 \
--safe-abort-nonce-too-low-count=3 \
--resubmission-timeout=30s \
--rpc.addr=0.0.0.0 \
--rpc.port=8548 \
--target-l1-tx-size-bytes=2048 \
--l1-eth-rpc=<RPC> \
--private-key=<BATCHERKEY>
```
## Get some ETH on your Rollup
Once you’ve connected your wallet, you’ll probably notice that you don’t have any ETH on your Rollup. You’ll need some ETH to pay for gas on your Rollup. The easiest way to deposit Goerli ETH into your chain is to send funds directly to the `OptimismPortalProxy` contract. You can find the address of the `OptimismPortalProxy` contract for your chain by looking inside the `deployments` folder in the `contracts-bedrock` package.
1. First, head over to the `contracts-bedrock` package:
```bash
cd ~/optimism/packages/contracts-bedrock
```
1. Grab the address of the `OptimismPortalProxy` contract:
1. Grab the `OptimismPortalProxy` address and, using the wallet that you want to have ETH on your Rollup, send that address a small amount of ETH on Goerli (0.1 or less is fine). It may take up to 5 minutes for that ETH to appear in your wallet on L2.
## Use your Rollup
Congratulations, you made it! You now have a complete OP Stack based EVM Rollup.
To see your rollup in action, you can use the [Optimism Mainnet Getting Started tutorial](https://github.com/ethereum-optimism/optimism-tutorial/blob/main/getting-started). Follow these steps:
cast send --mnemonic-path mnem.delme $GREETER "setGreeting(string)" "New greeting"
cast call $GREETER "greet()" | cast --to-ascii
```
To use any other development stack, see the getting started tutorial, just replace the Greeter address with the address of your rollup, and the Optimism Goerli URL with `http://localhost:8545`.
## Rollup operations
### Stopping your Rollup
To stop `op-geth` you should use Ctrl-C.
If `op-geth` aborts (for example, because the computer it is running on crashes), you will get these errors on `op-node`:
```
WARN [02-16|21:22:02.868] Derivation process temporary error attempts=14 err="stage 0 failed resetting: temp: failed to find the L2 Heads to start from: failed to fetch L2 block by hash 0x0000000000000000000000000000000000000000000000000000000000000000: failed to determine block-hash of hash 0x0000000000000000000000000000000000000000000000000000000000000000, could not get payload: not found"
```
In that case, you need to remove `datadir`, reinitialize it:
1. Start `op-geth` (using the same command line you used on the initial node)
1. Start `op-node` (using the same command line you used on the initial node)
1. Wait while the node synchronizes
## What’s next?
You can use this rollup the same way you’d use any other test blockchain. Once the superchain is available, this blockchain should be able to join the test version. Alternatively, you could [modify the blockchain in various ways](./hacks.md). **Please note that OP Stack Hacks are unofficial and are not explicitly supported by the OP Stack.** You will not be able to receive significant developer support for any modifications you make to the OP Stack.
Welcome to OP Stack Hacks, the **highly experimental** region of the OP Stack docs. OP Stack Hacks are an unofficial guide for messing around with the OP Stack. Here you’ll find information about ways that the OP Stack can be modified in interesting ways.
OP Stack Hacks create blockchains that aren’t exactly OP Stack, and may be insecure.. Hacked OP Stack chains can break key invariants that are required to interoperate with the Optimism Superchain (link). **Developers of chains that wish to interoperate with the Optimism Superchain should *not* include any hacks**. When in doubt, stick with the official components within [the current release of the OP Stack](../releases/README.md#current-release).
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
# Overview
The Settlement Layer includes modules that are used by third-party chains to establish a *view* of the state of your OP Stack chain. This view can then be used by applications on those chains to make decisions based on the state of your OP Stack chain. Third-party chains can be any other blockchain, including other OP Stack chains. One common Settlement Layer mechanism is a withdrawal system that allows users to send assets from your OP Stack chain to the third-party chain. Modifications to this layer typically involve introducing new modules or tweaking the security model of existing modules.
## Default
The default Settlement Layer module is currently the Attestation Proof Optimistic Settlement module. This module allows a third-party chain to become aware of the state of an OP Stack chain through an Optimistic protocol where challenges can be executed alongside a threshold of attestations from a pre-defined set of addresses over a state that differs from the proposed state. Once the Cannon fault proof is shipped to production, this default module will be replaced with a module that allows anyone to challenge proposals by playing the Cannon dispute game.
## Security
Modifications to the Settlement Layer can strongly impact the security of common mechanisms like user withdrawals. A decreased withdrawal delay can, for instance, open the door to gas spam attacks that make challenges exceedingly expensive. It is generally not recommended to modify the Settlement Layer unless you know what you’re doing.
## Modding
### Tweaked parameters
One simple modification to the Settlement Layer is to tweak the parameters of the default Optimistic asset withdrawal mechanism. For example, the withdrawal period can be reduced if a smaller withdrawal period would be sufficient to secure your system.
### Custom proofs
Settlement Layer modules use a proof system to verify the correctness of the state of your OP Stack chain as proposed on the third-party chain. In general, these proofs are either Optimistic proofs that require a withdrawal delay or Validity proofs that use a mathematical proof system to assert the validity of the proposal. The current Attestation Proof Optimistic Settlement module could be replaced with a fault proof system.
### Multiple modules
There is no requirement that a system only have one Settlement Layer module. It is possible to use one or more Settlement Layer modules on one or more third-party chains. A system that aims to bridge assets between two chains will likely need to use one Data Availability Layer module and one Settlement Layer module per chain.
title:Adding Attributes to the Derivation Function
lang:en-US
---
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
## Overview
In this guide, we’ll modify the Bedrock Rollup. Although there are many ways to modify the OP Stack, we’re going to spend this tutorial modifying the Derivation function. Specifically, we’re going to update the Derivation function to track the amount of ETH being burned on L1! Who’s gonna tell [ultrasound.money](http://ultrasound.money) that they should replace their backend with an OP Stack chain?
## Getting the idea
Let’s quickly recap what we’re about to do. The `op-node` is responsible for generating the Engine API payloads that trigger `op-geth` to produce blocks and transactions. The `op-node` already generates a “system transaction” for every L1 block that relays information about the current L1 state to the L2 chain. We’re going to modify the `op-node` to add a new system transaction that reports the total burn amount (the base fee multiplied by the gas used) in each block.
Although it might sound like a lot, the whole process only involves deploying a single smart contract, adding one new file to `op-node`, and modifying one existing file inside `op-node`. It’ll be painless. Let’s go!
## Deploy the burn contract
We’re going to use a smart contract on our Rollup to store the reports that the `op-node` makes about the L1 burn. Here’s the code for our smart contract:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title L1Burn
* @notice L1Burn keeps track of the total amount of ETH burned on L1.
*/
contract L1Burn {
/**
* @notice Total amount of ETH burned on L1.
*/
uint256 public total;
/**
* @notice Mapping of blocks numbers to total burn.
*/
mapping (uint64 => uint256) public reports;
/**
* @notice Allows the system address to submit a report.
*
* @param _blocknum L1 block number the report corresponds to.
* @param _burn Amount of ETH burned in the block.
*/
function report(uint64 _blocknum, uint64 _burn) external {
"L1Burn: reports can only be made from system address"
);
total += _burn;
reports[_blocknum] = total;
}
/**
* @notice Tallies up the total burn since a given block number.
*
* @param _blocknum L1 block number to tally from.
*
* @return Total amount of ETH burned since the given block number;
*/
function tally(uint64 _blocknum) external view returns (uint256) {
return total - reports[_blocknum];
}
}
```
Deploy this smart contract to your L2 (using any tool you find convenient). Make a note of the address that the contract is deployed to because you’ll need it in a minute. Simple!
## Add the burn transaction
Now we need to add logic to the `op-node` to automatically submit a burn report whenever an L1 block is produced. Since this transaction is very similar to the system transaction that reports other L1 block info (found in [l1_block_info.go](https://github.com/ethereum-optimism/optimism/blob/c9cd1215b76111888e25ee27a49a0bc0c4eeb0f8/op-node/rollup/derive/l1_block_info.go)), we’ll use that transaction as a jumping-off point.
1. Navigate to the `op-node` package:
```bash
cd ~/optimism/op-node
```
1. Inside of the folder `rollup/derive`, create a new file called `l1_burn_info.go`:
```bash
touch rollup/derive/l1_burn_info.go
```
1. Paste the following into `l1_burn_info.go`, and make sure to replace `YOUR_BURN_CONTRACT_HERE` with the address of the `L1Burn` contract you just deployed.
return nil, fmt.Errorf("failed to create L1 burn tx: %w", err)
}
l1Tx := types.NewTx(dep)
opaqueL1Tx, err := l1Tx.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("failed to encode L1 burn tx: %w", err)
}
return opaqueL1Tx, nil
}
```
Feel free to take a look at this file if you’re interested. It’s relatively simple, mainly just defining a new transaction type and describing how the transaction should be encoded.
## Insert the burn transactions
Finally, we’ll need to update `~/optimism/op-node/rollup/derive/attributes.go` to insert the new burn transaction into every block. You’ll need to make the following changes:
returnnil,NewCriticalError(fmt.Errorf("failed to create l1InfoTx: %w",err))
}
```
1. Immediately following, change these lines:
```go
txs:=make([]hexutil.Bytes,0,1+len(depositTxs))
txs=append(txs,l1InfoTx)
```
to
```go
txs:=make([]hexutil.Bytes,0,2+len(depositTxs))
txs=append(txs,l1InfoTx)
txs=append(txs,l1BurnTx)
```
All we’re doing here is creating a new burn transaction after every `l1InfoTx` and inserting it into every block.
## Rebuild your op-node
Before we can see this change take effect, you’ll need to rebuild your `op-node`:
```bash
cd ~/optimism/op-node
make op-node
```
Now start your `op-node` if it isn’t running or restart your `op-node` if it’s already running. You should see the change immediately — new blocks will contain two system transactions instead of just one!
## Checking the result
Query the `total` function of your contract, you should also start to see the total slowly increasing. Play around with the `tally` function to grab the amount of gas burned since a given L2 block. You could use this to implement a version of [ultrasound.money](http://ultrasound.money) that keeps track of things with an OP Stack as a backend. We did it reddit!
One way to get the total is to run these commands:
With just a few tiny changes to the `op-node`, you were just able to implement a change to the OP Stack that allows you to keep track of the L1 ETH burn on L2. Once the Cannon fault proof system is live you’ll not only be able to track the L1 burn on L2, you’ll be able to *prove* the burn to contracts back on L1. You could build a trustless prediction market on the amount of ETH burned. That’s crazy!
The OP Stack is an extremely powerful platform that allows you to perform a large amount of computation trustlessly. It’s a superpower for smart contracts. Tracking the L1 burn is just one of the many, many wild things you can do with the OP Stack. If you’re looking for inspiration or you want to see what others are building on the OP Stack, check out our OP Stack Hacks page. Maybe you’ll find a project you want to work on, or maybe you’ll get the inspiration you need to build the next killer smart contract.
::: warning 🚧 OP Stack Hacks are explicitly things that you can do with the OP Stack that are *not* currently intended for production use
OP Stack Hacks are not for the faint of heart. You will not be able to receive significant developer support for OP Stack Hacks — be prepared to get your hands dirty and to work without support.
:::
One possible use of OP Stack is to run an EVM with a new precompile for operations to speed up calculations that are not currently supported. In this case we’ll make a simple precompile that returns a constant value if it’s called with four or less bytes, or an error if it is called with more than that.
To create a new precompile, the file to modify is `[op-geth/core/vm/contracts.go](https://github.com/ethereum-optimism/op-geth/blob/optimism-history/core/vm/contracts.go)`.
1. Add to `PrecompiledContractsBerlin` on line 82 (or a later fork, if the list of precompiles changes again) a structure named after your new precompile, with an address that is unlikely to ever clash with a standard precompile (0x100, for example):
RequiredGas(input[]byte)uint64// RequiredPrice calculates the contract gas use
Run(input[]byte)([]byte,error)// Run runs the precompiled contract
}
```
It means that for every precompile we need two functions:
-`RequiredGas` which returns the gas cost for the call. This function takes an array of bytes as input, and returns a single value, the gas cost.
-`Run` which runs the actual precompile. This function also takes an array of bytes, but it returns two values: the call’s output (a byte array) and an error.
For every fork that changes the precompiles we have a [`map`](https://www.w3schools.com/go/go_maps.php)from addresses to the `PrecompiledContract` definitions:
```go
// PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum
The key of the map is an address. We create those from bytes using `common.BytesToAddress([]byte{<bytes to convert to address go here>})`. In this case we have two bytes, `0x01` and `0x00`. Together we get the address `0x0…0100`.
The syntax for a precompiled contract interface is `&<variable name>{}`.
The next step is to define the precompiled contract itself.
Then we define a function as part of that structure. Here we just require a constant amount of gas, but of course the calculation can be a lot more sophisticated.
This is the function that actually executes the precompile.
```go
// Only allow input up to four bytes (function signature)
iflen(input)>4{
returnnil,errConstInvalidInputLength
}
```
Return an error if warranted. The reason this precompile allows up to four bytes of input is that any standard call (for example, using `cast`) is going to have at least four bytes for the function signature.
`return a, b` is the way we return two values from a function in Go. The normal output is `nil`, nothing, because we return an error.
```go
output:=make([]byte,6)
fori:=0;i<6;i++{
output[i]=byte(64+i)
}
returnoutput,nil
}
```
Finally, we create the output buffer, fill it, and then return it.
## Conclusion
An OP Stack chain with additional precompiles can be useful, for example, to further reduce the computational effort required for cryptographic operations by moving them from interpreted EVM code to compiled Go code.
🎈 Thanks for your help improving the project! We are so happy to have you!
There are plenty of ways to contribute, in particular we appreciate support in the following areas:
## Code contributions
The Optimism codebase is maintained in a monorepo at [https://github.com/ethereum-optimism/optimism](https://github.com/ethereum-optimism/optimism). It's a [collection of packages](https://github.com/ethereum-optimism/optimism#directory-structure) all requiring different skills to maintain and evolve ranging from NodeJS and TypeScript, Solidity and EVM, Go and Geth to Docker and Kubernetes. The following are good entry points into using your coding skills to help us build Optimism:
- Reporting issues. For security issues see [Security policy](https://github.com/ethereum-optimism/.github/blob/master/SECURITY.md).
- Participate in the [Bug Bouty programme](https://immunefi.com/bounty/optimism/).
- Fixing and responding to existing issues. You can start off with those tagged ["good first issue"](https://github.com/ethereum-optimism/optimism/contribute) which are meant as introductory issues for external contributors.
- Work on open [bounties on Gitcoin](https://gitcoin.co/ethereum-optimism).
::: tip
Following the guidelines on [Contributing](https://github.com/ethereum-optimism/optimism/blob/master/CONTRIBUTING.md) and [Code of Conduct](https://github.com/ethereum-optimism/.github/blob/master/CODE_OF_CONDUCT.md) in all your interactions with the project will ensure your contributions are processed by the team.
:::
## Community contributions
- Pick an idea from the [project ideas list](https://github.com/ethereum-optimism/optimism-project-ideas) to start building
- Improve the [community site](https://community.optimism.io/)[documentation](https://github.com/ethereum-optimism/community-hub) or [tutorials](https://github.com/ethereum-optimism/optimism-tutorial).
- Become an "Optimizer" and answer questions in the [Optimism Discord](https://discord-gateway.optimism.io).
Whether you're just looking to [deploy a basic contract](https://github.com/ethereum-optimism/optimism-tutorial/tree/main/getting-started) or you're ready to [build a cross-chain app](./bridge/messaging.md), you'll be able to find everything you need to start building on Optimism within this section.
If you're looking for third-party tools that make building on Optimism easier, check out the [Tools for Developers](../useful-tools) section.
## Where should I start?
### Just getting started with Optimism?
If you're brand new to Optimism, we recommend checking out the [guide to deploying a basic contract](https://github.com/ethereum-optimism/optimism-tutorial/tree/main/getting-started).
It'll get you familiar with the core steps required to get a contract deployed to the network.
Luckily, Optimism is [EVM equivalent](https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306), so it's 100% the same as deploying a contract to Ethereum.
If you're a bit more familiar with Optimism and Ethereum, you can try walking through one of the various [tutorials](https://github.com/ethereum-optimism/optimism-tutorial) put together by the Optimism community.
They'll help you get a headstart when building your first Optimistic project.
### Ready to deploy a contract?
If you're looking to deploy your contracts to the Optimism mainnet or the Optimism Goerli testnet, take a look at our page on [using your favorite tools](./build/using-tools.md).
It contains sample configuration files for deploying your contracts from common frameworks like Hardhat, Truffle, and Brownie.
You might also want to check out our guides for [running a local development environment](./build/dev-node.md) or [running your own Optimism node](./build/run-a-node.md).
These guides are designed to help you feel totally confident in your Optimism deployment.
### Want to explore the cross-chain frontier?
We've got detailed guides for that.
If you want to bridge a token from Ethereum to Optimism (or vice versa!), you should learn more about our [Standard Token Bridge](./bridge/standard-bridge.md).
The Standard Token Bridge makes the process of moving tokens between chains as easy as possible.
If you're looking for something more advanced, we recommend reading through our page on [sending data between L1 and L2](./bridge/messaging.md).
Contracts on one chain can trigger contract functions on the other chain, it's pretty cool!
We even dogfood the same infrastructure and use it under the hood of the Standard Token Bridge.
## Still don't know where to look?
If you can't find the content you're looking for you've got a few options to get extra help.
We recommend first searching through this documentation (search bar at the top right).
If you've already done this and come up short, you can try [asking us a question in Discord](https://discord-gateway.optimism.io), [checking the Help Center](https://help.optimism.io/hc/en-us), or [making an issue on GitHub](https://github.com/ethereum-optimism/community-hub/issues).
As an application developer you are probably interested in the fact Bedrock has a mempool and the changes in transaction fees.
You might also be interested in changes in the RPC interface and block timing.
-[EIP-1559](#eip-1559)
-[Mempool](#mempool)
-[JSON-RPC](#json-rpc)
-[Block Production](#block-production)
</details>
<details>
<summary>Infrastructure provider (or anybody else running a node)</summary>
To run a node you need to understand the executables required to run it.
You might also be interested in the existence of the mempool and the changes in block timing, fess, and the JSON RPC.
-[Mempool](#mempool)
-[Block Production](#block-production)
-[Historical Data](#historical-data)
-[JSON-RPC](#json-rpc)
-[Chain Reorganizations](#chain-reorganizations)
[See here for a more detailed guide](./node-operator-guide.md) on how to run a Bedrock node.
</details>
<details>
<summary>Bridge developer</summary>
As a bridge developer you are likely most interested in deposits into Optimism and withdrawals back into Ethereum L1.
-[Two-Phase Withdrawals](#two-phase-withdrawals)
-[Deposits](#deposits-from-ethereum-to-optimism)
</details>
## The EVM
### Block Production
:::warning Block Time Subject to Change
Currently blocks are produced every two seconds.
However, that value may change in the future.
:::
Unlike the legacy network which mines a block for every incoming transaction, the Bedrock network will produce new blocks every two seconds. This introduces the following changes to the EVM:
-`TIMESTAMP` will return the timestamp of the block. It will update every two seconds.
-`BLOCKNUMBER` will return an actual block number. It will update every two seconds. The one-to-one mapping between blocks and transactions will no longer apply.
The Bedrock upgrade also introduces the concept of _system transactions_. System transactions are created by the `op-node`, and are used to execute deposits and update the L2's view of L1. They have the following attributes:
- Every block will contain at least one system transaction called the [L1 attributes deposited transaction](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#l1-attributes-deposited-transaction). It will always be the first transaction in the block.
- Some blocks will contain one or more [user-deposited transactions](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#user-deposited-transactions).
- All system transactions have an [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718)-compatible transaction type of `0x7E`.
- All system transactions are unsigned, and set their `v`, `r`, and `s` fields to `null`.
For more information about these transactions, see the [deposited transactions specification](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md) on GitHub.
:::warning Known Issue
Some Ethereum client libraries, such as Web3j, cannot parse the `null` signature fields described above. To work around this issue, you will need to manually filter out the system transactions before passing them to the library.
:::
### EIP-1559
As part of the Bedrock upgrade, we have upgraded the network to support [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559). In EIP-1559 the cost of a unit of gas is composed of two components:
-**Base fee**: This fee is the same for all transactions in a block. It varies between blocks based on the difference between the actual size of the blocks (which depends on the demand for block space) and the target block size. When the block uses more gas than the target block size the base fee goes up to discourage demand. When the block uses less gas than the target block size the base fee goes down to encourage demand.
-**Priority fee**: This fee is specified in the transaction itself and varies between transactions. Block proposers are expected to select the transactions that offer them the highest priority fees first.
There are some differences between Ethereum and Optimism in this regard:
- ETH is not burned. Burning ETH on L2 would only lock it in the bridge forever.
- The EIP 1559 parameters have different values. Once those values are finalized they will be posted here.
The L1 security fee, which is the majority of the transaction cost, uses the same mechanism as before the upgrade. However, the transactions to L1 are going to be submitted on a [non-contract address](#the-transaction-trail). Between that and improved compression, the L1 security fee should be reduced by about 20%.
From an application development perspective, EIP-1559 introduces the following changes:
- The `BASEFEE` opcode is now supported. The `BASEFEE` opcodes returns the base fee of the current block.
- The `eth_maxPriorityFeePerGas` and `eth_feeHistory` RPC methods are now supported. `eth_maxPriorityFeePerGas` returns a fee per gas that is an estimate of how much you can pay as a priority fee, or 'tip', to get a transaction included in the current block. `eth_feeHistory` returns a collection of historical gas information from which you can decide what to submit as your `maxFeePerGas` and/or `maxPriorityFeePerGas`.
### Removed Opcodes
One of the design goals of the Bedrock upgrade is to be maximally EVM equivalent. To reduce differences between Optimism's EVM and vanilla Ethereum's EVM, we have removed the `L1BLOCKNUMBER` opcode.
### ETH Balances
The previous version of the system used an ERC20 contract called `OVM_ETH` to represent ETH balances. These balances will be migrated into the Bedrock network's state as part of the migration. To preserve backwards compatibility, the methods on the `OVM_ETH` contract will continue to work. Note, however, that the `totalSupply()` method will return zero.
## Chain Reorganizations
Unlike the legacy network, Bedrock nodes _always_ derive blocks from L1. This means that if L1 experiences a reorg, L2 will reorganize itself to match the state of L1. Blocks that have not been submitted to L1 yet are gossipped via a peer-to-peer network, and can be reorganized if the data on L1 does not match the data gossiped over P2P.
Bedrock adopts the same vocabulary as the Beacon Chain to describe block finality. Blocks can be in one of the following states:
-`unsafe`, meaning that the block has been received via gossip but has not yet been submitted to L1. Unsafe blocks can be reorged if L1 reorgs, or the sequencer reorgs.
-`safe`, meaning that the block has been submitted to L1. Unsafe blocks can be reorged if L1 reorgs.
-`finalized`, meaning that the block has reached sufficient depth to be considered final. Finalized blocks cannot be reorged.
The current `safe`, `unsafe`, and `finalized` blocks can be queried via [JSON-RPC](#json-rpc).
## Historical Data
Bedrock nodes can serve pre-Bedrock block bodies, transactions, and receipts out of the box. However, you will need to run a Legacy Geth instance to serve historical execution traces. See the [Node Operator Guide](./node-operator-guide.md) for more information about how to do this.
Note that the following legacy fields have been removed from pre-Bedrock JSON-RPC transaction responses:
-`queueOrigin`
-`l1TxOrigin`
-`l1BlockNumber`
-`l1Timestamp`
-`index`
-`queueIndex`
-`rawTransaction`
If your application needs these fields, query Legacy Geth instead of `op-geth`.
## JSON-RPC
Bedrock supports all of the standard JSON-RPC methods exposed by go-ethereum. In order to reduce differences between Bedrock and vanilla Ethereum, some legacy methods have been removed. These methods and their replacements are:
-`eth_getBlockRange`: Use `eth_getBlockByNumber` in a batch request instead.
-`rollup_getInfo`: None of the information returned by this method exists on Bedrock, so there is no replacement for this method.
-`rollup_gasPrices`: Use `eth_gasPrice` instead. The L1 and L2 fees are combined, and returned as a single value.
To query `op-node`'s sync status, use the `optimism_syncStatus` RPC method. This method will return the current `safe`, `unsafe`, and `finalized` as seen by the `op-node`.
## Mempool
Since the legacy network creates a block for every transaction, it processes new transactions in a first-come-first-serve manner. Bedrock, however, creates blocks on a fixed interval and therefore needs a mempool to store pending transactions until they are included in a block. To minimize MEV, Bedrock's mempool is private. To submit transactions, you will need to configure `op-geth` to forward transactions to the sequencer. This may change in the future.
The sequencer processes transactions in the mempool in order of their base and priority fees.
## Two-Phase Withdrawals
On the legacy network, funds are withdrawn as follows:
1. Users send a withdrawal message.
2. Users wait seven days for the withdrawal to be finalized.
3. Users post a withdrawal proof on L1, and claim their funds.
However, this introduces a security risk. If the withdrawal proof can be successfully forged, an attacker could withdraw funds from the bridge that they are not authorized to. This kind of attack has been exploited before - a fraudulent proof led to the loss of [$100M on Binance Smart Chain](https://www.nansen.ai/research/bnb-chains-cross-chain-bridge-exploit-explained).
To eliminate this risk, Bedrock requires users to post their withdrawal proofs upfront. Users must wait for a valid output root to be proposed so that the withdrawal proof can be validated on-chain. Once the seven-day waiting period has expired, users can then finalize the withdrawal and claim their funds. The updated withdrawal flow is as follows:
1. Users send a withdrawal message.
2. Users wait for a state output to be proposed on-chain. This can take up to an hour.
3. Users call `proveWithdrawalTransaction()` on the `OptimismPortal` to post and validate their proof.
4. Users wait for the withdrawal to be finalized. This takes seven days on mainnet.
5. Users call `finalizeWithdrawal()` on the `OptimismPortal` to claim their funds.
By posting the proof upfront, it gives on-chain monitoring tools enough time to detect a fraudulent withdrawal proof and attempt corrective action.
Regular users can do this monitoring too. For example, an exechange could halt withdrawals in the event of a fraudulent proof.
Since this change fundamentally changes the way withdrawals are handled, it is **not** backwards-compatible with the old network. If you are performing withdrawals outside our standard bridge interface, you will need to update your software. The easiest way to to do this is to use our [TypeScript SDK](https://github.com/ethereum-optimism/optimism/tree/develop/packages/sdk), which includes two-phase withdrawals support out of the box.
For more information on two-phase withdrawals, see the withdrawals specification on [GitHub](https://github.com/ethereum-optimism/optimism/blob/develop/specs/withdrawals.md).
## Deposit Replayability
:::warning Breaking Change
The changes described in this section are **not** backwards-compatible with the old network. Please read this section carefully.
:::
On the legacy network, deposits are replayable. This is no longer the case in Bedrock. Additionally, as part of the migration, all deposits on the legacy network that have not been replayed will no longer be replayable. **This means that if you have not replayed your deposit, you must do so before the migration.** This affects fewer than 100 transactions of the nearly 40 million on mainnet.
## Contracts
### L1 contracts
#### L2OutputOracle
[The `L2OutputOracle` contract](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/L2OutputOracle.sol) contains the state root of the Optimism blockchain.
Once fault proofs are activated, it will be the one that receives the result of the fault proof process.
This is the contract that replaces the old State Commitment Chain.
#### OptimismPortal
[The `OptimismPortal` contract](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/OptimismPortal.sol) provides [the low-level API for communications between layers](#deposits-from-ethereum-to-optimism). Unless you are trying to send L2 transactions via L1 to bypass the sequencer, we strongly recommend sending messages between L1 and L2 via the L1CrossDomainMessenger and L2CrossDomainMessenger.
#### Existing interface
These contracts provide the same interface as existed pre-Bedrock so dapps don’t have to be modified to run on Bedrock.
The `L1CrossDomainMessenger` contract is used for sending messages between Ethereum and Optimism. Those messages may or may not have assets attached to them.
The `L1StandardBridge` contract uses `L1CrossDomainMessenger` to transfer ETH and ERC-20 tokens between Ethereum and Optimism.
### L2 contracts (predeploys)
#### L1Block
[The `L1Block` contract](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L2/L1Block.sol) sits at address `0x4200000000000000000000000000000000000015`.
You can use [the getter functions](https://docs.soliditylang.org/en/v0.8.12/contracts.html#getter-functions) to get these parameters:
-`number`: The latest L1 block number known to L2 (the `L1BlockNumber` contract is still supported to avoid breaking existing applications)
-`timestamp`: The timestamp of the latest L1 block
-`basefee`: The base fee of the latest L1 block
-`hash`: The hash of the latest L1 block
-`sequenceNumber`: The number of the L2 block within the epoch (the epoch changes when there is a new L1 block)
Currently the L1 information is delayed by ten block confirmations (~2.5 minutes) to minimize the impact of reorgs.
This value may be reduced in the future.
#### SequencerFeeVault
[The `SequencerFeeVault` contract](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L2/SequencerFeeVault.sol) handles funding the sequencer on L1 using the ETH base fee on L2.
The fees are calculated using [EIP 1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md), the same mechanism that Ethereum uses (but with different parameter values).
#### L2ToL1MessagePasser
[The `L2ToL1MessagePasser` contract](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L2/L2ToL1MessagePasser.sol) is used internally by `L2CrossDomainMessenger` to initiate withdrawals.
#### Existing interface
These contracts provide the same interface as existed pre-Bedrock so dapps don’t have to be modified to run on Bedrock.
The `DeployerWhitelist` contract used to manage the whitelist before [Optimism moved out of beta](https://twitter.com/optimismFND/status/1471571415774023682).
The `OVM_ETH` contract used to manage users ETH balances prior to Bedrock.
## Communication between layers
In Optimism terminology "deposit" refers to any message going from the Ethereum blockchain to Optimism, whether it has any assets attached or not.
Similarly, "withdrawal" refers to any message going from Optimism to Ethereum.
[See here for the messenger specs](https://github.com/ethereum-optimism/optimism/blob/develop/specs/messengers.md) and [here for the bridge specs](https://github.com/ethereum-optimism/optimism/blob/develop/specs/bridges.md).
<!--
### Gas cost changes
The gas costs for communication between layers are going to change, they will probably get lower.
More information will be posted here once we have more exact information after we profile a test network.
-->
<!-- TODO get the figures and put them here -->
### Deposits (from Ethereum to Optimism)
To create a deposit we recommend that you use the pre-Bedrock contracts [`L1StandardBridge`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/L1StandardBridge.sol) and [`L1CrossDomainMessenger`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/L1CrossDomainMessenger.sol).
[`OptimismPortal`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/OptimismPortal.sol) also has low-level deposit functionality.
With the OptimismPortal’s `depositTransaction` function you can do from L1 anything you can do by contacting L2 directly: send transactions, send payments, create contracts, etc.
This provides an uncensorable alternative in case the sequencer is down.
Even though the sequencer is down, verifiers (nodes that synchronize the Optimism state from L1) are still going to receive such transactions and modify the state accordingly.
When the sequencer is back up it has to process the transactions in the same order to have a valid state.
We recommend adding a 50% buffer to whatever is returned by `estimateGas` to ensure that your deposit will not run out of gas (Note: the Optimism SDK already does this under the hood). For example, if you wish to send a deposit of ETH, you might call `eth_estimateGas` and see that the deposit is expected to consume `100,000 gas`. You should then multiply that estimated about by `1.5` and then send your transaction with a `gasLimit` of at least `150,000 gas`.
:::tip
In order to prevent the Optimism network from being DOSed via forced L1 to L2 transactions that bypass the Sequencer, a fee adjustment schedule to all L1→L2 transactions that closely mimics EIP1559 is included with Bedrock. Like in the current network, deposit fees are paid by burning some amount of L1 gas proportional to your deposit's L2 gas limit. Unfortunately, this means that you may have cases where you estimate how much gas an L1→L2 deposit will cost, and deposit fees increase by the time your transaction gets included in a block and executed, causing your deposit to run out of gas and revert. This is why we recommend adding a 50% buffer to your `gasLimit` to ensure your deposit will not run out of gas.
:::
Deposits that come from contracts still use [address aliasing](../build/differences.md#address-aliasing).
Deposits will also be faster, probably about 2.5 minutes or less, rather than the 10-20 minutes they take now.
<!--
Deposits are implemented using [a new transaction type](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#the-deposited-transaction-type), 0x7E.
-->
[You can read the full deposit specifications here](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#the-deposited-transaction-type).
[You can read the full withdrawal specifications here](https://github.com/ethereum-optimism/optimism/blob/develop/specs/withdrawals.md)
## Behind the scenes
This section discusses some of the changes in Optimism internals.
### The transaction trail
There is no longer a CTC (cannonical transaction chain) contract. Instead, L2 blocks are saved to the Ethereum blockchain using a non-contract address to minimize the L1 gas expenses. Please see the [Public Testnets](./public-testnets.md) page for more information on where to find batch submission addresses.
[The block and transaction format is also different](https://github.com/ethereum-optimism/optimism/blob/develop/specs/rollup-node.md#l2-chain-derivation).
Bedrock is the name of the first ever official release of the OP Stack, which is a set of free and open-source modular components that work together to power Optimism.
- To understand what is in the Bedrock release, keep reading.
- To develop on Optimism Mainnet, which will upgrade its infrastructure to the Bedrock release, read the docs.
- To contribute to the OP Stack, see the contribution guidelines on the ethereum-optimism monorepo.
## Summary of Improvements
Bedrock improves on its predecessor by reducing transaction fees using optimized batch [compression](#optimized-data-compression) and Ethereum as a data availability layer; shortening delays of including L1 transactions in rollups by handling L1 re-orgs more gracefully; enabling modular proof systems through code re-use; and improving node performance by removing technical debt.
### Lower fees
In addition, Bedrock implements an optimized data [compression](#optimized-data-compression) strategy to minimize data costs. We are currently benchmarking the impact of this change, but we expect it to reduce fees significantly.
Bedrock also removes all gas costs associated with EVM execution when submitting data to L1. This reduces fees by an additional 10% over the previous version of the protocol.
### Shorter deposit times
Bedrock introduces support for L1 re-orgs in the node software, which significantly reduces the amount of time users need to wait for deposits. Earlier versions of the protocol could take up to 10 minutes to confirm deposits. With Bedrock, we expect deposits to confirm within 3 minutes.
### Improved proof modularity
Bedrock abstracts the proof system from the OP Stack so that a rollup may use either a fault proof or validity proof (e.g., a zk-SNARK) to prove correct execution of inputs on the rollup. This abstraction enables systems like [Cannon](https://github.com/ethereum-optimism/cannon) to be used to prove faults in the system.
### Improved node performance
The node software performance has been significantly improved by enabling execution of several transactions in a single rollup "block" as opposed to the prior "one transaction per block" model in the previous version. This allows the cost of merkle trie updates to be amortized across multiple transactions. At current transaction volume, this reduces state growth by approximately 15GB/year.
Node performance is further improved by removing technical debt from the previous version of the protocol. This includes removing the need for a separate "data transport layer" node to index L1, and updating the node software to efficiently query for transaction data from L1.
### Improved Ethereum equivalence
Bedrock was designed from the ground up to be as close to Ethereum as possible. Multiple deviations from Ethereum in the previous version of the protocol have been removed, including:
1. The one-transaction-per-block model.
2. Custom opcodes to get L1 block information.
3. Separate L1/L2 fee fields in the JSON-RPC API.
4. A custom ERC20 representation of ETH balances.
Bedrock also adds support for EIP-1559, chain re-orgs, and other Ethereum features present on L1.
## Design Principles
Bedrock was built to be modular & upgradeable, to reuse existing code from Ethereum, and to be as close to 100% Ethereum-equivalent as possible.
### Modularity
Bedrock makes it easy to swap out different components in the OP Stack and add new capabilities by using well-defined interfaces and versioning schemes. This allows for a flexible architecture that can adapt to future developments in the Ethereum ecosystem.
Examples:
- Separation of [rollup node](#rollup-node) and execution client
- Modular fault proof design
### Code re-use
Bedrock uses existing Ethereum architecture and infrastructure as much as possible. This approach enables the OP Stack to inherit security and "lindy" benefits from the battle-tested codebases used in production on Ethereum Mainnet. You'll find examples of this throughout the design including:
- EVM contracts instead of precompiled client code
### Ethereum equivalence
Bedrock is designed to have maximum compatibility with the existing Ethereum developer experience. A few exceptions exist due to fundamental differences between an L1 and a rollup: an altered fee model, faster block time (2s vs 12s), and a special transaction type for including L1 [deposit](#deposits) transactions.
Examples:
- Fault proof designed to prove faults of minimally modified Ethereum [execution client](#execution-client)
- Code re-use of Ethereum [execution client](#execution-client) for use by nodes in the L2 network and sequencers
## Protocol
Rollups are derived from a data availability source (generally an L1 blockchain like Ethereum). In their most common configuration, rollup protocols derive a **"canonical L2 chain"** from two primary sources of information:
1. Transaction data posted by Sequencers to the L1 and;
2.[Deposit](#deposits) transactions posted by accounts and contracts to a bridge contract on L1.
The following are the fundamental components of the protocol:
* Deposits are _writes_ to the canonical L2 chain by directly interacting with smart contracts on the L1.
* Withdrawals are _writes_ to the canonical L2 chain that implicitly trigger interactions with contracts and accounts on the L1.
* Batches are _writes_ of data corresponding to batches on the rollup.
* Block derivation is how _reads_ of data on the L1 are interpreted to understand the canonical L2 chain.
* Proof systems define _finality_ of posted output roots on the L1 such that they may be _executed_ upon (e.g., to execute withdrawals).
### Deposits
A **deposit** is a transaction on L1 that is to be included in the rollup. [Deposits](#deposits) are _guaranteed_ by definition to be included in the [canonical L2 chain](#protocol) as a means of preventing censorship or control of the L2.
#### Arbitrary message passing from L1
A **deposited transaction** is the transaction on the rollup that is made as a part of a [deposit](#deposits). With Bedrock, [deposits](#deposits) are fully generalized Ethereum transactions. For example, an account or contract on Ethereum can “deposit” a contract creation.
Bedrock defines a **deposit contract** that is available on the L1: it is a smart contract that L1 accounts and contracts can interact with to write to the L2. [Deposited transactions](#arbitrary-message-passing-from-l1) on the L2 are derived from the values in the event(s) emitted by this [deposit](#deposits) contract, which include expected parameters such as from, to, and data.
For full details, see the [deposit contract](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#deposit-contract) section of the protocol specifications.
#### Purchasing guaranteed L2 gas on L1
Bedrock also specifies a gas burn mechanism and a fee market for [deposits](#deposits). The gas that [deposited transactions](#arbitrary-message-passing-from-l1) spend on an L2 is bought on L1 via a gas burn. This gas is purchased on a fee market and there is a hard cap on the amount of gas provided to all [deposits](#deposits) in a single L1 block. This mechanism is used to prevent denial of service attacks that could occur by writing transactions to L2 from L1 that are extremely gas-intensive on L2, but cheap on L1.
The gas provided to [deposited transactions](#arbitrary-message-passing-from-l1) is sometimes called "guaranteed gas." Guaranteed gas is unique in that it is paid for by burning gas on L1 and is therefore not refundable.The total amount of L1 gas that must be burned per unit of guaranteed L2 gas requested depends on the price of L2 gas reported by a EIP-1559 style fee mechanism. Furthermore, users receive a dynamic gas stipend based on the amount of L1 gas spent to compute updates to the fee mechanism.
For a deeper explanation, read the [deposits section](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md#deposits) of the protocol specifications.
### Withdrawals
**Withdrawals** are cross-domain transactions that are initiated on L2 and finalized by a transaction executed on L1. Notably, withdrawals may be used by an L2 account to call an L1 contract, or to transfer ETH from an L2 account to an L1 account.
Withdrawals are initiated on L2 via a call to the **Message Passer** predeploy contract, which records the important properties of the message in its storage. Withdrawals are finalized on L1 via a call to the [OptimismPortal](https://github.com/ethereum-optimism/optimism/blob/develop/specs/withdrawals.md#the-optimism-portal-contract) contract, which proves the inclusion of this withdrawal message. In this way, withdrawals are different from [deposits](#deposits). Instead of relying on [block derivation](#block-derivation), withdrawal transactions must use smart contracts on L1 for finalization.
#### Two-step withdrawals
Withdrawal proof validation bugs have been the root cause of many of the biggest bridge hacks of the last few years. The Bedrock release introduces an additional step in the withdrawals’ process of prior versions meant to provide an extra layer of defense against these types of bugs. In the two-step withdrawal process, a Merkle proof corresponding to the withdrawal must be submitted 7 days before the withdrawal can be finalized.. This new safety mechanism gives monitoring tools a full 7 days to find and detect invalid withdrawal proofs . If the [withdrawal](#withdrawals) proof is found to be invalid, a contract fix can be deployed before funds are lost. This dramatically reduces the risk of a bridge compromise.
For full details, see the [withdrawals](https://github.com/ethereum-optimism/optimism/blob/develop/specs/withdrawals.md) section of the protocol specification.
### Batches
In Bedrock, a wire format is defined for messaging between the L1 and L2 (i.e., for L2 deriving blocks from L1 and for L2 to write transactions to the L1). This wire format is designed to minimize costs and software complexity for writing to the L1.
#### Optimized data compression
To optimize data compression, lists of L2 transactions called **sequencer batches** are organized into groups of objects called **channels**, each of which have a maximum size that is defined in a [configurable parameter](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#channel-format) that will initially be set to ~9.5Mb. These [channels](#optimized-data-compression) are expected to be compressed using a compression function and submitted to the L1.
#### Parallelized batch submission
To parallelize messages from the sequencers that are submitting [compressed](#optimized-data-compression)[channel](#optimized-data-compression) data to the L1, [channels](#optimized-data-compression) are further broken down into **channel frames**, which are chunks of [compressed](#optimized-data-compression)[channel](#optimized-data-compression) data that can fit inside of a single L1 transaction. Given [channel frames](#parallelized-batch-submission) are mutually independent and the ordering is known, the Ethereum transactions sent by the sequencer to the L1 can be sent in parallel which minimizes sequencer software complexity and allows for filling up all available space for data on the L1.
#### Minimized usage of Ethereum gas
Bedrock removes all execution gas used by the L1 system from submitting [channel](#optimized-data-compression) data to the L1 in transactions called **batcher transactions**. All validation logic that was previously happening on smart contracts on the L1 is moved into the [block derivation](#block-derivation) logic. Instead, [batcher transactions](#minimized-usage-of-ethereum-gas) are sent to a single EOA on Ethereum referred to as the **batch inbox address**.
Batches are still subject to validity checks (i.e. they have to be encoded correctly), and so are individual transactions within the batch (e.g. signatures have to be valid). Invalid [batches](#optimized-data-compression) and invalid individual transactions within an otherwise valid batch are considered to be discarded and irrelevant to the system.
> Note: Ethereum will soon upgrade to include [EIP-4844](https://eip4844.com/), which introduces a separate fee market for writing data and an increased cap of the amount of data the Ethereum protocol is willing to store. This change is expected to further decrease the costs associated with posting data to an L1.
For a deeper explanation, read [the wire format specifications](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#overview).
### Block Derivation
In Bedrock, the protocol is designed to guarantee that the timing of [deposits](#deposits) on the L1 is respected with regards to the [block derivation](#block-derivation) of the [canonical L2 chain](#protocol). Doing so is a _pure function_ of data written to the L1 by sequencers, [deposits](#deposits), and L1 block attributes. To accomplish this, the protocol defines strategies for guaranteeing inclusion of deposits, handling L1 and L2 timestamps, and processing sequencing windows in a pipeline to ensure correct ordering.
#### Guaranteed inclusion of deposits
A goal of the [block derivation](#block-derivation) protocol is to define it such that there must be an L2 block every "L2 block time" number of seconds, and that the timestamp of L2 blocks stays in sync with the timestamps of L1 (i.e., to ensure [deposits](#deposits) are included in a logical temporal order).
In Bedrock, the concept of a **sequencing epoch** is introduced: it is a range of L2 blocks derived from a range of L1 blocks. Each [epoch](#guaranteed-inclusion-of-deposits) is identified by an **epoch number**, which is equal to the block number of the first L1 block in the sequencing window. Epochs can vary in size, subject to some constraints.
The batch derivation pipeline treats the timestamps of the L1 blocks associated with [epoch number](#guaranteed-inclusion-of-deposits) as the anchor point for determining the order of transactions on the L2. The protocol guarantees that the first L2 block of an [epoch](#guaranteed-inclusion-of-deposits) never falls behind the timestamp of the L1 block matching the [epoch](#guaranteed-inclusion-of-deposits). The first blocks of an epoch _must_ contain deposits on L1 in order to guarantee that deposits will be processed.
Note that the target configuration for the block time on L2 in the Bedrock release is 2 seconds.
> **Note** that the target configuration for the block time on L2 in the Bedrock release is 2 seconds.
#### Handling L1 and L2 timestamps
Bedrock attempts to address the problem of reconciling the timestamps on L2 with timestamps on L1 present in [deposited transactions](#arbitrary-message-passing-from-l1). It does this by allowing a short window of time for sequencing to liberally apply timestamps on L2 transactions between [epochs](#guaranteed-inclusion-of-deposits).
A **sequencing window** is a sequence of L1 blocks from which an [epoch](#guaranteed-inclusion-of-deposits) can be derived. A [sequencing window](#handling-l1-and-l2-timestamps) whose first L1 block has the number `N` contains [batcher transactions](#minimized-usage-of-ethereum-gas) for [epoch](#guaranteed-inclusion-of-deposits)`N`.
The [sequencing window](#handling-l1-and-l2-timestamps) contains blocks `[N, N + SWS)` where `SWS` is the **sequencer window size**: a fixed rollup-level configuration parameter. This parameter must be at least 2. Increasing it provides more opportunity for sequencers to order L2 transactions with respect to [deposits](#deposits), and lowering it introduces stricter windows of time for sequencers to submit batcher transactions. It is a tradeoff between creating MEV opportunity and increasing software complexity.
A protocol constant called **max sequencer drift** governs the maximum timestamp a block can have within its epoch. Having this drift allows the sequencer to maintain liveness in case of temporary problems connecting to L1. Each L2 block’s timestamp fits within the following range:
The [canonical L2 chain](#protocol) can be processed from scratch by starting with the L2 genesis state, setting the L2 chain inception as the first epoch, and then processing all sequencing windows in order to determine the correct ordering of [sequencer batches](#optimized-data-compression) and [deposits](#deposits) according to the following simplified pipeline:
| **Stage** | **Notes** |
| --- | --- |
| Read from L1 | Epochs are defined by L1 blocks. Contained within an L2 block is data pertaining to [batcher transactions](#minimized-usage-of-ethereum-gas) or [deposits](#deposits) which must be included in the [canonical L2 chain](#protocol) |
| Buffer and decode into [channels](#optimized-data-compression) | The data from L1 blocks contains unordered [channel frames](#parallelized-batch-submission), which must all be collected before reconstructing them into channels. |
| Decompress [channels](#optimized-data-compression) into [batches](#optimized-data-compression) | Since [channels](#optimized-data-compression) are [compressed](#optimized-data-compression) to minimize data fee costs on the L1, they must be decompressed. |
| Queue [batches](#optimized-data-compression) into sequential order | With the latest information from L1, [batches](#optimized-data-compression) can be validated and processed sequentially. There are some nuances to what the correct ordering is in relation to [epochs](#guaranteed-inclusion-of-deposits) and timestamps from L2, see the full specification [here](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#batch-queue). |
| Interpret as L2 blocks | At this point, the correct ordering of [batches](#optimized-data-compression) can be determined.<br><br>Following this, the [execution client](#execution-client) can interpret them into L2 blocks. For implementation details pertaining to [execution clients](#execution-client), see the [engine queue](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#engine-queue) section of the protocol specifications. |
### Fault Proofs
After a sequencer processes one or more L2 blocks, the outputs computed from executing transactions in those blocks will need to be written with L1 for trustless execution of L2-to-L1 messaging, such as [withdrawals](#withdrawals).
In Bedrock, outputs are hashed in a tree-structured form which minimizes the cost of proving any piece of data captured by the outputs. Proposers periodically submit **output roots** that are Merkle roots of the entire [canonical L2 chain](#protocol) to the L1.
Future upgrades of the OP Stack should include a specification for a variation of a fault proof with bonding included to create incentives for proposers to propose correct output roots.
For full details, read the [L2 Output Root Proposals section](https://github.com/ethereum-optimism/optimism/blob/develop/specs/proposals.md#l2-output-root-proposals-specification) of the protocol specifications.
## Implementation
With Bedrock, the OP Stack leans heavily into the technical separation of concerns specified by Ethereum by mirroring the separation between the Ethereum execution layer and consensus layer. Bedrock introduces separation of execution client and rollup node in this same way.
### Execution Client
An **execution client** is the system that sequencers and other kinds of node operators run to determine the state of the [canonical L2 chain](#protocol). It also performs other functions such as processing inbound transactions and communicating them peer-to-peer, and handling the state of the system to process queries against it.
With Bedrock, the OP Stack is designed to reuse [Ethereum’s own execution client specifications](https://github.com/ethereum/execution-specs) and its many implementations. In this release, Bedrock has demonstrated an extremely limited modification of go-ethereum, the most popular Ethereum client written in Go, to a [diff of less than 2000 lines of code](https://op-geth.optimism.io/).
There are two fundamental reasons for having any diff at all: handling deposited transactions, and charging transaction fees.
#### Handling deposited transactions
To represent [deposited transactions](#arbitrary-message-passing-from-l1) in the rollup, there is an additional transaction type introduced. The [execution client](#execution-client) implements this [new transaction type](https://github.com/ethereum-optimism/optimism/blob/develop/specs/%5Bdeposits%5D(#deposits).md%23the-deposited-transaction-type) according to the [EIP-2718 typed transactions](https://eips.ethereum.org/EIPS/eip-2718) standard.
#### Charging transaction fees
Rollups also fundamentally have two kinds of fees associated with transactions:
**Sequencer fees**
The cost of operating a sequencer is computed using the same gas table as Ethereum and with the same [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) algorithm. These fees go to the protocol for operating sequencers and fluctuate based on the congestion of the network.
**Data availability fees**
Data availability costs are associated with writing [batcher transactions](#minimized-usage-of-ethereum-gas) to the L1. These fees are intended to cover the cost that sequencers need to pay to submit [batcher transactions](#minimized-usage-of-ethereum-gas) to the L1.
In Bedrock, the data availability portion of the fee is determined based on information in a system contract on the rollup called a [GasPriceOracle](https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md#gaspriceoracle). This contract is updated during [block derivation](#block-derivation) from the gas pricing information retrieved from the L1 block attributes that get inserted at the beginning of every [epoch](#guaranteed-inclusion-of-deposits).
Bedrock specifies that both of these fees are added up into a single `gasPrice` field when using the JSON-RPC.
### Rollup Node
Unlike Ethereum, Bedrock does not have proof-of-stake consensus. Instead, the consensus of the [canonical L2 chain](#protocol) is defined by [block derivation](#block-derivation). An [execution client](#execution-client) of the OP Stack communicates to a new component that implements [block derivation](#block-derivation) called a **rollup node**. This node communicates to the [execution client](#execution-client) using the exact same [Engine API](https://github.com/ethereum/execution-apis/tree/main/src/engine) that Ethereum uses.
The [rollup node](#rollup-node) is a stateless component responsible for deriving the state of the system by reading data and [deposits](#deposits) on the L1. In Bedrock, a [rollup node](#rollup-node) can either be used to sequence incoming transactions from users or other [rollup nodes](#rollup-node) or to verify confirmed transactions posted on the L1 by singularly relying on the L1.
The multiple uses of a rollup node are outlined below.
#### Verifying the canonical L2 chain
The simplest mode of running a [rollup node](#rollup-node) is to only follow the [canonical L2 chain](#protocol). In this mode, the [rollup node](#rollup-node) has no peers and is strictly used to read data from the L1 and to interpret it according to [block derivation](#block-derivation) protocol rules.
One purpose of this kind of node is to verify that any output roots shared by other nodes or posted on the L1 are correct according to protocol definition. Additionally, proposers intending to submit output roots to the L1 themselves can generate the output roots they need using the [optimism_outputAtBlock](https://github.com/ethereum-optimism/optimism/blob/develop/specs/rollup-node.md#l2-output-rpc-method) of the node which returns a 32-byte hash corresponding to the L2 output root.
For this purpose, nodes should only need to follow the finalized head. The term ["finalized"](https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/#finality) refers to the Ethereum proof-of-stake consensus (i.e. canonical and practically irreversible) — the finalized L2 head is the head of the [canonical L2 chain](#protocol) that is derived only from finalized L1 blocks.
#### Participating in the L2 network
The most common way to use a [rollup node](#rollup-node) is to participate in a network of other [rollup nodes](#rollup-node) tracking the progression and state of an L2. In this mode, a [rollup node](#rollup-node) is both reading the data and [deposits](#deposits) it observes from the L1 and interpreting it as blocks and accepting inbound transactions from users and peers in a network of other [rollup nodes](#rollup-node).
Nodes participating in the network may make use of the safe and unsafe heads of the L2 they're syncing.
- The **safe L2 head** represents the rollup that can be constructed where every block up to and including the head can be fully derived from the reference L1 chain, before L1 has necessarily finalized (i.e., a re-org may occur on L1 still).
- The **unsafe L2 head** includes [unsafe blocks](https://github.com/ethereum-optimism/optimism/blob/develop/specs/glossary.md#unsafe-l2-block) that have not yet been derived from L1. These blocks either come from operating the [rollup node](#rollup-node) as a sequencer or from [unsafe sync](https://github.com/ethereum-optimism/optimism/blob/develop/specs/glossary.md#unsafe-sync) with the sequencer. This is also known as the "latest" head. The safe L2 head is always chosen over the unsafe L2 head in cases of disagreements. When disagreements occur, the unsafe portion of the chain will reorg.
For most purposes, nodes in the L2 network will refer to the unsafe L2 head for end-user applications.
#### Sequencing transactions
The third way to use a [rollup node](#rollup-node) is to sequence transactions. In this mode, a [rollup node](#rollup-node) will _create_ new blocks on top of the unsafe L2 head. Currently, there is only one sequencer per OP Stack network.
The sequencer is also responsible for posting batches to L1 for other nodes in the network to sync from.
### Batcher
The role of a sequencer is to produce [batches](#batches). To do this, a sequencer can run [rollup nodes](#rollup-node) and have separate processes which perform [batching](#batches) by reading from a trusted [rollup node](#rollup-node) they run. This warrants an additional component of the OP Stack called a [batcher](https://github.com/ethereum-optimism/optimism/blob/develop/specs/glossary.md#batcher) that reads transaction data from a [rollup node](#rollup-node) and interprets it into [batcher transactions](#minimized-usage-of-ethereum-gas) to be written to the L1. The batcher component is responsible for reading the unsafe L2 head of a [rollup node](#rollup-node) run by a sequencer, creating batcher transactions, and writing them to the L1.
### Standard Bridge Contracts
Bedrock also includes a pair of bridge contracts used for the most common kinds of [deposits](#deposits) called the [standard bridges](https://github.com/ethereum-optimism/optimism/blob/develop/specs/bridges.md#standard-bridges). These contracts wrap the [deposit](#deposits) and [withdrawal](#withdrawals) contracts to provide simple interfaces for [depositing](#deposits) and [withdrawing](#withdrawals) ETH and ERC-20 tokens.
These bridges are designed to involve a native token on one side of the bridge, and a wrapped token on the other side that can manage minting and burning. Bridging a native token involves locking the native token in a contract and then minting an equivalent amount of mintable token on the other side of the bridge.
For full details, see the [standard bridge](https://github.com/ethereum-optimism/optimism/blob/develop/specs/bridges.md#standard-bridges) section of the protocol specifications.
### Cannon
Although fault proof construction and verification is implemented in the [Cannon](https://github.com/ethereum-optimism/cannon) project, the fault proof game specification and integration of an output root challenger into the rollup node are part of later specification milestones.
## Further Reading
### Protocol Specification
The protocol specification defines the technical details of the OP Stack. It is the most up-to-date source of truth for the inner workings of the protocol. The protocol specification is located in the ethereum-optimism [monorepo](https://github.com/ethereum-optimism/optimism/blob/develop/specs/README.md).
### Bedrock Differences
For a deep dive into the differences between Bedrock and previous versions of the protocol, see the [How is Bedrock Different?](./how-is-bedrock-different.md) page.
The Bedrock `op-node` exposes a variety of metrics to help observe the health of the system and debug issues. Metrics are formatted for use with Prometheus, and exposed via a metrics endpoint. The default metrics endpoint is `http://localhost:7300/metrics`.
To enable metrics, pass the `--metrics.enabled` flag to the `op-node`. You can customize the metrics port and address via the `--metrics.port` and `--metrics.addr` flags, respectively.
## Important Metrics
To monitor the health of your node, you should monitor the following metrics:
-`op_node_default_refs_number`: This metric represents the `op-node`'s current L1/L2 reference block number for different sync types. If it stops increasing, it means that the node is not syncing. If it goes backwards, it means your node is reorging.
-`op_node_default_peer_count`: This metric represents how many peers the `op-node` is connected to. Without peers, the `op-node` cannot sync unsafe blocks and your node will lag behind the sequencer as it will fall back to syncing purely from L1.
-`op_node_default_rpc_client_request_duration_seconds`: This metrics measures the latency of RPC requests initiated by the `op-node`. This metric is important when debugging sync performance, as it will reveal which specific RPC calls are slowing down sync. This metric exposes one timeseries per RPC method. The most important RPC methods to monitor are:
-`engine_forkChoiceUpdatedV1`, `engine_getPayloadV1`, and `engine_newPayloadV1`: These methods are used to execute blocks on `op-geth`. If these methods are slow, it means that sync time is bottlenecked by either `op-geth` itself or your connection to it.
-`eth_getBlockByHash`, `eth_getTransactionReceipt`, and `eth_getBlockByNumber`: These methods are used by the `op-node` to fetch transaction data from L1. If these methods are slow, it means that sync time is bottlenecked by your L1 RPC.
| op_node_default_last_publishing_errors_unix | Timestamp of last p2p publishing errors event | | gauge |
| op_node_default_unsafe_payloads_buffer_len | Number of buffered L2 unsafe payloads | | gauge |
| op_node_default_unsafe_payloads_buffer_mem_size | Total estimated memory size of buffered L2 unsafe payloads | | gauge |
| op_node_default_refs_number | Gauge representing the different L1/L2 reference block numbers | layer,type | gauge |
| op_node_default_refs_time | Gauge representing the different L1/L2 reference block timestamps | layer,type | gauge |
| op_node_default_refs_hash | Gauge representing the different L1/L2 reference block hashes truncated to float values | layer,type | gauge |
| op_node_default_refs_seqnr | Gauge representing the different L2 reference sequence numbers | type | gauge |
| op_node_default_refs_latency | Gauge representing the different L1/L2 reference block timestamps minus current time, in seconds | layer,type | gauge |
This guide is for the *bedrock* upgrade, which is coming in Q1, 2023, subject to approval by Optimism governance.
Do not attempt to use this in production prior to that upgrade. Keep an eye on these docs or [our official Twitter](https://twitter.com/OPLabsPBC) for announcements.
:::
This document provides an overview of how to deploy a Bedrock node. To learn more about how Bedrock itself works and its motivations, please see [the specs on GitHub](https://github.com/ethereum-optimism/optimism/tree/develop/specs).
This document is designed to be a general overview of how to deploy a Bedrock node.
## Deployment Overview
A Bedrock deployment consists of two core components:
1. The Rollup Node, which is responsible for deriving blocks from L1 and passing them to the Execution engine. It also participates in a peer-to-peer network that synchronizes unsubmitted blocks as the sequencer creates them. We refer to this component as `op-node`.
2. The Execution Engine, which is responsible for executing the blocks it receives from the rollup node and storing state. It also exposes standard JSON-RPC methods to query blockchain data and submit transactions to the network. We refer to this component as `op-geth`, since our Execution Engine is [a minimal fork](https://op-geth.optimism.io/) of `go-ethereum`.
The Rollup Node and Execution Engine communicate with each other over JSON-RPC via the Engine API. This is similar to how regular Ethereum networks are deployed. The Rollup Node functions as Optimism's consensus client, and the Execution Engine as its execution client.
For Goerli and mainnet, you may also need to run a third component called Legacy Geth. Legacy Geth is used to serve execution traces for transactions prior to the Bedrock upgrade, which we refer to as "historical transactions". When the Rollup Node encounters an RPC call that requires historical execution traces, it will forward the request to Legacy Geth. Note, however, that unlike our previous networks requests for historical _data_ will be served by the Execution Engine directly. This distinction will be clarified later on in this document.
The architecture of a typical Bedrock deployment looks like this:
We recommend the following minimum system requirements to run Bedrock:
-`op-node`: Minimum 2CPUs, 4GB RAM. No storage is necessary.
-`op-geth`: Minimum 4 CPUs, 8GB RAM. At least 32GB of storage is required for Goerli. At least 600GB of storage is required for mainnet. Storage must be SSD. Requirements are significantly higher for archive nodes.
## Getting the Software
`op-geth` and `op-node` are available as Docker images. Consult the [documentation](./public-testnets.md) for the network you are participating in to get the correct image tag.
Legacy Geth uses version `0.5.29` of our old `l2geth` image.
You can also compile `op-geth` and `op-node` from source.
## Node Configuration
:::warning
Always run `op-node` and `op-geth` in a one-to-one configuration. Don't run multiple `op-geth` instances behind one `op-node`, or vice versa.
:::
To configure your node, you will need to do the following:
1. Configure `op-node` to point to the correct L1, `op-geth`, and L2 network.
2. Initialize `op-geth` with the correct network parameters.
3. Configure `op-geth` to properly communicate with the Rollup Node.
4. Optionally, configure Legacy Geth.
### Configuring op-geth
:::tip
Even though the Docker image for the Execution Engine is called `op-geth`, the actually binary is still called `geth` in order to minimize differences between `op-geth` and `go-ethereum`.
:::
We'll start with `op-geth`'s configuration because it is more complex. As mentioned before, `op-geth` is a minimal fork of `go-ethereum`. As a result, it stores its state in a database that requires initialization. Initialization is done one of two ways, depending on which network you're deploying:
1.**With a Genesis File:** This is used for testnets or internal deployments that are not migrated from a legacy network. In this case, you'll download the genesis file and initialize the data directory via `geth init`.
2.**With a Data Directory:** This is used for networks that are migrated from a legacy network. In this case, you'll download a preconfigured data directory and extract it. No further initialization is necessary in this case, because the data directory contains the network's genesis information.
Regardless of how `op-geth` is initialized, you'll need to ensure that you have sufficient disk space available to store the network's data. As of this writing, the mainnet data directory is ~100GB for a full node and ~1TB for an archival node. The Goerli data directory is ~6GB for a full node.
Instructions for each initialization method are below.
#### Initialization via Genesis File
`op-geth` uses JSON files to encode a network's genesis information. For networks that are initialized in this way, you'll receive a URL to the genesis JSON. You'll need to download the genesis JSON, then run the following command to initialize the data directory:
```bash
curl -o <path to genesis JSON> -sL <URL to genesis JSON>
geth init \
--datadir="<your data directory>"\
"<path to genesis JSON>"
```
#### Initialization via Data Directory
To initialize `op-geth` with a preconfigured data directory, simply download and extract the data directory to a place of your choosing. The data directory is exported as a tar file. An example command to do this is below:
```bash
curl -o <path to data directory> -sL <URL to data directory>
tar-xvf <path to data directory>
```
#### Configuration
Once `op-geth` is initialized, it can be configured via CLI flags. `op-geth` accepts all the [standard `go-ethereum` flags](https://geth.ethereum.org/docs/interface/command-line-options) as well as a few extra flags that are specific to Optimism. These flags are:
-`--rollup.historicalrpc`: Enables the historical RPC endpoint. This endpoint is used to fetch historical execution data from Legacy Geth. This flag is only necessary for upgraded networks.
-`--rollup.sequencerhttp`: HTTP endpoint of the sequencer. `op-geth` will route `eth_sendRawTransaction` calls to this URL. Bedrock does not currently have a public mempool, so this is required if you want your node to support transaction submission. Consult the documentation for the network you are participating in to get the correct URL.
-`--rollup.disabletxpoolgossip`: Disables transaction pool gossiping. While not required, it's useful to set this to `true` since transaction pool gossip is currently unsupported.
To communicate with `op-node` and enable the Engine API, you'll also need to generate a JWT secret file and enable Geth's authenticated RPC endpoint.
To generate the JWT secret, run the following:
```bash
openssl rand -hex 32 > jwt.txt
```
Then, specify the following flags:
-`--authrpc.addr`: Sets the address `op-geth`'s authenticated RPC should listen on.
-`--authrpc.port`: Sets the port `op-geth`'s authenticated RPC should listen on. The default value is `8551`.
-`--authrpc.jwtsecret`: Sets the path to a JWT secret file you generated above.
-`--syncmode=full`: This prevents Geth from attempting to snap sync. Snap sync is currently unsupported, but will be enabled shortly after the mainnet upgrade.
-`--maxpeers=0`: This prevents Geth from peering with other Geth nodes. Execution-layer peering is currently unsupported, but will be added as part of enabling snap sync.
-`--nodiscover`: This disables Geth's peer discovery mechanism. Execution-layer discovery is currently unsupported, but will be added as part of enabling snap sync.
#### Optional op-geth Configuration
You may also want to specify the following flags based on your configuration:
-`--authrpc.vhosts`: Whitelists which hosts (as defined in the `Host` header) are allowed to access the authenticated RPC endpoint. This is useful if you're running `op-geth` on containerized infrastructure. The default value is `localhost`.
-`--http.vhosts`: Whitelists which hosts (as defined in the `Host` header) are allowed to access the unauthenticated RPC endpoint. This is useful if you're running `op-geth` on containerized infrastructure. The default value is `localhost`.
-`--http`, `--http.addr`, and `--http.port`: Enables the unauthenticated RPC endpoint, configures its address, and configures its port. You'll almost certainly want to specify these, since they will enable Geth's JSON-RPC endpoint.
-`--ws`, `--ws.addr`, and `--ws.port`: Enables the WebSocket API.
-`--verbosity`: Configures Geth's log level. This is a number between 0 and 5, with 5 being the most verbose. Defaults to 3.
#### Working Base Configuration
A valid command that runs `op-geth` on our `beta-1` network and enables RPC over HTTP and WebSockets looks like:
Consult [Geth's documentation](https://geth.ethereum.org/docs/) for more information on customizing `op-geth`'s behavior.
### Configuring op-node
`op-node` is a standalone, statically linked binary. It stores no state, and requires no initialization. It consumes configuration parameters either via the command line or environment variables. For some networks, the Rollup Node also requires a configuration file (called `rollup.json` or the "rollup config") that configures network-specific genesis parameters. For official networks like Goerli and mainnet, the genesis config is hardcoded in the `op-node` software and can be specified via a `--network` flag.
A minimal valid configuration for a rollup node on our `beta-1` testnet looks like this:
```bash
op-node --l1=<goerli RPC url> \
--l2=<op-geth authenticated RPC url> \
--network=beta-1
--rpc.addr=127.0.0.1 \
--rpc.port=9545 \
--l2.jwt-secret=<path to JWT secret>
```
You can manually specify a path to a rollup config with the `--rollup.config` flag. This is used for testnets or internal deployments that are not migrated from a legacy network.
Each of the above flags can also be defined via an environment variable. Run `op-node --help` to see a list of all available flags and environment variables.
#### Configuring Peer-to-Peer Networking
Unlike the previous system, the `op-node` participates in a peer-to-peer network. This network is used to distribute blocks that have not been submitted to L1 yet. The `op-node` will automatically discover and connect to peers using a hardcoded set of bootnodes. You can also manually specify peers to connect to via the `--p2p.static` flag.
For best results, run `op-node` with a static IP address that is accessible from the public Internet. For Kubernetes deployments, this can be achieved by configuring a dedicated `Ingress` with an external IP, and using the `--p2p.advertise.ip` flag to specify the IP address of the load balancer when advertising IP addresses to peers.
The default port for the peer-to-peer network is `9003`. You will need to open this port on your firewall to receive unsubmitted blocks. For your node to be discoverable, this port must be accessible via both TCP and UDP protocols.
### Legacy Geth
If you are running a node for an upgraded network like Goerli or mainnet, you will also need to run Legacy Geth in order to serve historical execution traces. Fundamentally, Legacy Geth is our old `l2geth` binary running against a preconfigured data directory. To configure Legacy Geth, follow the instructions above for using a preconfigured data directory, then execute the following command:
:::danger
It is imperative that you specify the `USING_OVM=true` environment variable in the command below. Failing to specify this will cause `l2geth` to return invalid execution traces, or panic at startup.
:::
```bash
USING_OVM=true\
ETH1_SYNC_SERVICE_ENABLE=false\
RPC_API=eth,rollup,net,web3,debug \
RPC_ADDR=0.0.0.0 \
RPC_CORS_DOMAIN=*\
RPC_ENABLE=true\
RPC_PORT=8545 \
RPC_VHOSTS=*\
geth --datadir <path to data directory>
```
This command is the minimum required to run Legacy Geth and expose a functioning RPC endpoint. As before, `l2geth` takes all standard `go-ethereum` flags so you can customize the configuration as needed.
As mentioned above, don't forget to specify `--rollup.historicalrpc` on `op-geth` to properly route requests for historical execution to Legacy Geth.
Since Legacy Geth is read-only, it is safe to run multiple Legacy Geth nodes behind a load balancer.
#### Historical Execution vs. Historical Data Routing
Only requests for historical execution will be routed to Legacy Geth.
Everything else will be served by `op-geth` directly.
The term _historical execution_ refers to RPC methods that need to execute transactions prior to bedrock (not just read data from the database):
-`eth_call`
-`eth_estimateGas`
-`debug_traceBlockByNumber`
-`debug_traceBlockByHash`
-`debug_traceCall`
-`debug_traceTransaction`
If you do not need these RPC methods for historical data, then you do not need to run Legacy Geth at all.
## Troubleshooting
### 401 Unauthorized: Signature Invalid
If you see a log that looks like this in `op-node`:
```
WARN [12-13|15:53:20.263] Derivation process temporary error attempts=80 err="stage 0 failed resetting: temp: failed to find the L2 Heads to start from: failed to fetch current L2 forkchoice state: failed to find the finalized L2 block: failed to determine L2BlockRef of finalized, could not get payload: 401 Unauthorized: signature is invalid
```
It means that the `op-node` is unable to authenticate with `op-geth`'s authenticated RPC using the JWT secret. To fix:
1. Check that the JWT secret is correct in both services.
2. Check that `op-geth`'s authenticated RPC is enabled, and that the URL is correct.
### 403 Forbidden: Invalid Host Specified
If you see a log that looks like this in `op-node`:
It means that you have not whitelisted `op-node`'s host with `op-geth`. To fix:
1. Make sure that the `--authrpc.vhosts` parameter in `op-geth` is either set to the correct host, or `*`.
2. Check that `op-geth`'s authenticated RPC is enabled, and that the URL is correct.
### Failed to Load P2P Config
If you see a log that looks like this in `op-node`:
```
CRIT [12-13|13:46:21.386] Application failed message="failed to load p2p config: failed to load p2p discovery options: failed to open discovery db: mkdir /p2p: permission denied"
```
It means that the `op-node` does not have write access to the P2P discovery or peerstore directories. To fix:
1. Make sure that the `op-node` has write access to the P2P directory. By default, this is `/p2p`.
2. Set the P2P directory to somewhere the `op-node` can access via the `--p2p.discovery.path` and `--p2p.peerstore.path` parameters.
3. Set the discovery path to `memory` to disable persistence via the `--p2p.discovery.path` and `--p2p.peerstore.path` parameters.
### Wrong Chain
If you see a log that looks like this in `op-node`:
```
{"attempts":183,"err":"stage 0 failed resetting: temp: failed to find the L2 Heads to start from: wrong chain L1: genesis: 0x4104895a540d87127ff11eef0d51d8f63ce00a6fc211db751a45a4b3a61a9c83:8106656, got 0x12e2c18a3ac50f74d3dd3c0ed7cb751cc924c2985de3dfed44080e683954f1dd:8106656","lvl":"warn","msg":"Derivation process temporary error","t":"2022-12-13T23:31:37.855253213Z"}
```
It means that the `op-node` is pointing to the wrong chain. To fix:
1. Verify that the `op-node`'s L1 URL is pointing to the correct L1 for the given network.
2. Verify that the `op-node`'s rollup config/`--network` parameter is set to the correct network.
3. Verify that the `op-node`'s L2 URL is pointing to the correct instance of `op-geth`, and that `op-geth` is properly initialized for the given network.
## Further Reading
Now that you've got your node up and running, check out the [Upgrade Guide](./upgrade-guide.md) for what to expect when we upgrade our official testnet and mainnet.
This guide is for the *bedrock* upgrade, which is coming in Q1, 2023, subject to approval by Optimism governance.
Do not attempt to use this in production prior to that upgrade. Keep an eye on these docs or [our official Twitter](https://twitter.com/OPLabsPBC) for announcements.
:::
This document provides an overview of how the Bedrock upgrade will be executed and how it will impact node operators and dApp developers.
## Upgrade Overview
Unlike previous upgrades, the Bedrock upgrade will not be a "regenesis" event where historical transaction data is lost and the chain resets at block zero. Instead, the Bedrock upgrade will resemble a hard fork where the new Bedrock chain will be a continuation of the old one. This ensures that the upgrade is as seamless as possible.
The upgrade will proceed as follows on upgrade day:
1. Deposits and withdrawals on the legacy network will be paused.
2. Transactions on the legacy sequencer will no longer be accepted.
3. The smart contracts on L1 will be upgraded and an irregular state transition on L2 will be performed.
4. The Bedrock sequencer will start up.
5. Deposits and withdrawals will be re-enabled.
6. The contract addresses, binaries, and data directories required to interact with the new system will be distributed.
Backwards compatibility is one of the upgrade's key design goals.
Potential incompatibilities and their workarounds are highlighted in the sections below.
## Optimism Mainnet Upgrade
The Bedrock upgrade to the Optimism Mainnet Network is yet to be scheduled.
We plan to announce an official date and time in February 2023 at least 3 weeks in advance of the upgrade, subject to approval by Optimism governance.
## For Node Operators
:::tip Prerequisites
This section assumes that you have read and understood our [Node Operator Guide](./node-operator-guide.md). Please read that first if you haven't already.
:::
From a node operator perspective, the old system will be completely _replaced_ on upgrade day. This means that rather than upgrading legacy infrastructure, node operators will be standing up entirely new infrastructure to run the Bedrock network.
On upgrade day, we will provide node operators with the following information:
1. The correct `op-node` and `op-geth` images and binaries to use.
2. A URL to an upgraded data directory containing the genesis state for the new system.
3. A URL to a legacy data directory containing data for Legacy Geth.
4. A set of bootnodes to use as part of the peer-to-peer network.
We will embed the rollup config into the `op-node` itself. Then, on upgrade day, you will need to:
1. Initialize `op-geth`'s data directory using the upgraded genesis state from the provided URL. See the [Initialization via Data Directory](./node-operator-guide.md#initialization-via-data-directory) section of the Node Operator Guide for more information.
2. Specify the `op-node`'s network via the `--network` flag or `OP_NODE_NETWORK` environment variable. Its value will be `goerli` for the Goerli upgrade, or `mainnet` for the mainnet upgrade.
3. Initialize Legacy Geth's data directory using the legacy genesis state from the provided URL. See the [Initialization via Data Directory](./node-operator-guide.md#initialization-via-data-directory) and [Legacy Geth](./node-operator-guide.md#legacy-geth) sections of the Node Operator Guide for more information.
4. Set the `op-geth``--rollup.historicalrpc` parameter to point to Legacy Geth's RPC endpoint.
5. Start `op-geth` and `op-node` as usual.
The best way to prepare for the upgrade is to participate in one of our public testnets. Please see the [public testnets](./public-testnets.md) page for how to connect to our testnet.
## For dApp and Wallet Developers
On upgrade day, deposits and withdrawals will be paused, along with ingress on the sequencer. This means that all transactions on Optimism will be halted for the duration of the upgrade.
Once the upgrade is complete, everything should be identical to how it was before the upgrade. All balances, contract addresses, transaction data, block data, and historical execution traces will be preserved. The new network is EVM-equivalent, so all existing Ethereum tooling will continue to work with the new system. Differences are described in [How is Bedrock Different?](./how-is-bedrock-different.md).
## FAQs
### When is the upgrade taking place?
The Goerli upgrade is tentatively scheduled for January 2023. The mainnet upgrade is tentatively scheduled for February 2023. The Goerli upgrade will be live for at least a month before the mainnet upgrade.
### Is this a hard fork, or a new network?
This is a hard fork. The network will retain the same chain ID, transaction history, and state. The first block of the new network will be the last block of the new network + 1.
### How long will the upgrade take?
We expect the upgrade to take less than 4 hours.
### How can I best prepare for the upgrade?
The best way to prepare for the upgrade is to participate in one of our public testnets. Please see the [Beta Testnet](https://www.notion.so/External-Optimism-Bedrock-Beta-Testnet-454a37e469af4658b89a9d766334e331) page for how to connect to our current testnet.
### Why is Legacy Geth necessary?
The upgraded data directory used to initialize `op-geth` contains the current state of the network as well as all historical block, transaction, and receipt data. However, providing historical execution would require bundling the legacy system's EVM implementation with `op-geth`. In an effort to keep our diff between `op-geth` and upstream `go-ethereum` small, we instead route requests for historical execution traces to Legacy Geth which already contains the correct execution engine.
You only need to run Legacy Geth if you need historical execution traces.
### What version of upstream Geth is op-geth based off of?
`op-geth` is currently based off of the `1.10.x` version of `go-ethereum`.
`op-geth` is periodically updated include the latest upstream changes.
### How can I see the difference between upstream Geth and op-geth?
A single-commit diff is maintained in the `op-geth` repository. See [here](https://github.com/ethereum-optimism/op-geth/compare/master...optimism) for the comparison.
### Will transaction tracing for post-Bedrock data be faster?
Yes. `op-geth` uses the latest transaction tracers from upstream, which have much better performance than tracers legacy `l2geth` uses.
If you [run your own replica](build/run-a-node.md), it is important that you subscribe either to the release announcement mailing list or the RSS feed to know when you need to upgrade.
Optimism is built according to a strong design philosophy that stands on four main pillars: simplicity, pragmatism, sustainability, and, of course, optimism.
It's important to understand these pillars as they heavily influence the design of Optimism as a whole.
## Simplicity
Optimism is designed to be as simple as possible for the featureset it provides.
Ideally, Optimism should be composed of the minimum number of moving parts required for a secure, scalable, and flexible L2 system.
This simplicity gives Optimism's design a number of significant advantages over other more complex L2 constructions.
Simplicity reduces engineering overhead, which in turn means we can spend our time working on new features instead of re-creating existing ones.
Optimism prefers to use existing battle-tested Ethereum code and infrastructure where possible.
The most visible example of this philosophy in practice is the choice to use Geth as Optimism's client software.
When dealing with critical infrastructure, simplicity is also security.
Every line of code we write is an opportunity to introduce unintentional bugs.
A simple protocol means there's less code to write and, as a result, less surface area for potential mistakes.
A clean and minimal codebase is also more accessible to external contributors and auditors.
All of this serves to maximize the security and correctness of the Optimism protocol.
Simplicity is also important for the long-term vision of Optimism.
By limiting the amount of code that we write on top of Ethereum tooling, we're able to spend most of our time working directly with existing codebases.
Engineering effort that goes into Optimism can also directly benefit Ethereum, and vice versa.
This will only become more pronounced as the Optimism protocol solidifies and existing resources can be redirected towards core Ethereum infrastructure.
## Pragmatism
For all its idealism, the design process behind Optimism is ultimately driven by pragmatism.
The core Optimism team has real-world constraints, the projects that build on Optimism have real-world needs, and the users that engage with Optimism have real-world problems.
Optimism's design philosophy prioritizes user and developer needs over theoretical perfection.
Sometimes the best solution isn't the prettiest one.
Optimism is also developed with the understanding that any core team will have limited areas of expertise.
Optimism is developed iteratively and strives to continously pull feedback from users.
Many core Optimism features today (like [EVM Equivalence](https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306)) were only made possible by this iterative approach to protocol development.
## Sustainability
Optimism is in it for the long haul.
Application developers need assurance that the platform they're building on will remain not only operational but competitive over long periods of time.
Optimism's design process is built around the idea of long-term sustainability and not taking shortcuts to scalability.
At the end of the day, a scalable system means nothing without the ecosystem that sustains it.
Sustainability actively influences Optimism's protocol design in ways that go hand-in-hand with our philosophy of simplicity.
The more complex a codebase, the more difficult it is for people outside of the core development team to actively contribute.
By keeping our codebase simple we're able to build a bigger community of contributors who can help maintain the protocol long-term.
## Optimism
Of course, none of this would be possible without a sense of optimism.
Our optimism about the Ethereum vision keeps this project moving forward.
We believe in an optimistic future for Ethereum, a future where we get to redesign our relationships to the institutions that coordinate our lives.
Although Optimism looks like a standalone blockchain, it's ultimately designed as an extension to Ethereum.
We keep this in mind whenever we're creating new features or trying to simplify existing ones.
Optimism is as close to Ethereum as possible not only for pragmatic reasons, but because Optimism exists so that Ethereum can succeed.
We hope that you can see the influence of this philosophy when looking at Optimism's design.
The big idea that makes Optimism possible is the Optimistic Rollup.
We'll go through a brief explainer of *how* Optimistic Rollups work at a high level.
Then we'll explain *why* Optimism is built as an Optimistic Rollup and why we believe it's the best option for a system that addresses all of our design goals.
## Optimistic Rollups TL;DR
Optimism is an "Optimistic Rollup," which is basically just a fancy way of describing a blockchain that piggy-backs off of the security of another "parent" blockchain.
Specifically, Optimistic Rollups take advantage of the consensus mechanism (like PoW or PoS) of their parent chain instead of providing their own.
In Optimism's case this parent blockchain is Ethereum.
In Bedrock L2 blocks are saved to the Ethereum blockchain using a non-contract address ([`0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0001`](https://etherscan.io/address/0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0001)), to minimize the L1 gas expense.
As these blocks are submitted as transaction calldata on Ethereum, there is no way to modify or censor them after the "transaction" is included in a block that has enough attestations.
This is the way that Optimism inherits the availability and integrity guarantees of Ethereum.
Blocks are written to L1 in [a compressed format](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#batch-submission-wire-format) to reduce costs.
This is important because writing to L1 is [the major cost of Optimism transactions](../developers/build/transaction-fees.md).
## Block production
Optimism block production is primarily managed by a single party, called the "sequencer," which helps the network by providing the following services:
- Providing transaction confirmations and state updates.
- Constructing and executing L2 blocks.
- Submitting user transactions to L1.
In Bedrock the sequencer does have a mempool, similar to L1 Ethereum, but the mempool is private to avoid opening opportunities for MEV.
Blocks are produced every two seconds, regardless of whether they are empty (no transactions), filled up to the block gas limit with transactions, or anything in between.
Transactions get to the sequencer in two ways:
1. Transactions submitted on L1 (called *deposits* whether they have assets attached or not) are included in the chain in the appropriate L2 block.
Every L2 block is identified by the "epoch" (the L1 block to which it corresponds, which typically has happened a few minutes before the L2 block) and its serial number within that epoch.
The first block of the epoch includes all the deposits that happened in the L1 block to which it corresponds.
If the sequencer attempts to ignore a legitimate L1 transaction it ends up with a state that is inconsistent with the verifiers, same as if the sequencer tried to fake the state by other means.
This provides Optimism with L1 Ethereum level censorship resistance.
You can read more about this mechanism [is the protocol specifications](https://github.com/ethereum-optimism/optimism/blob/develop/specs/derivation.md#deriving-the-transaction-list).
1. Transactions submitted directly to the sequnecer.
These transactions are a lot cheaper to submit (because you do not need the expense of a separate L1 transaction), but of course they cannot be made censorship resistant, because the sequencer is the only entity that knows about them.
For the moment, [The Optimism Foundation](https://www.optimism.io/) runs the only block producer. Refer to [Protocol specs](../protocol/README.md) section for more information about how we plan to decentralize the Sequencer role in the future.
## Block execution
The execution engine (implemented as the `op-geth` component) receive blocks using two mechanisms:
1. The execution engine can update itself using peer to peer network with other execution engines.
This operates the same way that the L1 execution clients synchronize the state across the network.
You can read more about it [in the specs](https://github.com/ethereum-optimism/optimism/blob/develop/specs/exec-engine.md#happy-path-sync).
1. The rollup node (implemented as the `op-node` component) derives the L2 blocks from L1.
This mechanism is slower, but censorship resistant.
You can read more about it [in the specs](https://github.com/ethereum-optimism/optimism/blob/develop/specs/exec-engine.md#worst-case-sync).
## Bridging assets between layers
Optimism is designed so that users can send arbitrary messages between smart contracts on Optimism and Ethereum.
This makes it possible to transfer assets, including ERC20 tokens, between the two networks.
The exact mechanism by which this communication occurs differs depending on the direction in which messages are being sent.
Optimism uses this functionality in the Standard bridge to allow users to deposit assets (ERC20s and ETH) from Ethereum to Optimism and also allow withdrawals of the same from Optimism back to Ethereum.
See the [developer documentation and examples](../developers/bridge/standard-bridge/) on details on the inner workings of the Standard bridge.
### Moving from Ethereum to Optimism
In Optimism terminology, transactions going from Ethereum (L1) to Optimism (L2) are called *deposits*, even if they do not have any assets attached to them.
You use [`L1CrossDomainMessenger`](https://github.com/ethereum-optimism/optimism-tutorial/tree/main/cross-dom-comm) or [`L1StandardBridge`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/contracts/L1/L1StandardBridge.sol).
Deposit transactions become part of the canonical blockchain in the first L2 block of the "epoch" corresponding to the L1 block where the deposits were made.
This L2 block will usually be created a few minutes after the corresponding L1 block.
You can read more about this [in the specs](https://github.com/ethereum-optimism/optimism/blob/develop/specs/deposits.md).
### Moving from Optimism to Ethereum
Withdrawals (the term is used for any Optimism to Ethereum message, regardless of whether it has attached assets or not) have three stages:
1. You initialize withdrawals with an L2 transaction.
1. Wait for the next output root to be submitted to L1 (you can see this on [the SDK](../sdk/js-client.md)) and then submit the withdrawal proof using `proveWithdrawalTransaction`.
This new step enables off-chain monitoring of the withdrawals, which makes it easier to identify incorrect withdrawals or output roots.
This protects Optimism users against a whole class of potential bridge vulnerabilities.
1. After the fault challenge period ends (a week on mainnet, less than that on the test network), finalize the withdrawal.
[You can read the full withdrawal specifications here](https://github.com/ethereum-optimism/optimism/blob/develop/specs/withdrawals.md)
## Fault proofs
In an Optimistic Rollup, state commitments are published to Ethereum without any direct proof of the validity of these commitments.
Instead, these commitments are considered pending for a period of time (called the "challenge window").
If a proposed state commitment goes unchallenged for the duration of the challenge window (currently set to 7 days), then it is considered final.
Once a commitment is considered final, smart contracts on Ethereum can safely accept withdrawal proofs about the state of Optimism based on that commitment.
When a state commitment is challenged, it can be invalidated through a "fault proof" ([formerly known as a "fraud proof"](https://github.com/ethereum-optimism/optimistic-specs/discussions/53)) process.
If the commitment is successfully challenged, then it is removed from the `StateCommitmentChain` to eventually be replaced by another proposed commitment.
It's important to note that a successful challenge does not roll back Optimism itself, only the published commitments about the state of the chain.
The ordering of transactions and the state of Optimism is unchanged by a fault proof challenge.
The fault proof process is currently undergoing major redevelopment as a side-effect of the November 11th [EVM Equivalence](https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306) update.
You can read more about this process within the [Protocol specs](../protocol/README.md) section of this website.
With the OVM 2.0 upgrade, which happened on November 11th, 2021, the Optimism protocol went through its biggest upgrade to date. The primary focus of this upgrade was [EVM Equivalence](https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306), a new design for Optimism that brought it close to 1:1 parity with Ethereum. For a high level overview of the current protocol version, see ['How Optimism works'](./2-rollup-protocol.md) section.
## Roadmap
Below is a brief summary of some of the planned [Optimism roadmap](https://www.optimism.io/about) releases.
## Next gen fault proofs
As part of the OVM 2.0 upgrade, the **Optimism fault proof mechanism had to be temporarily disabled**. This means that users of the Optimism network currently need to trust the Sequencer node (run by Optimism PBC) to publish valid state roots to Ethereum. **You can read more about our security model [here](../security-model/optimism-security-model.md)**.
We're making progress on the upgrade fault proof mechanism and we expect to productionize our work in 2022. You can keep up with developments in the [Cannon repository](https://github.com/ethereum-optimism/cannon/).
## Decentralizing the sequencer
Currently, Optimism runs the sole sequencer on Optimism. This does not mean that Optimism can censor user transactions. However, it is still desirable to decentralize the sequencer over time, eliminating Optimism's role entirely so that anyone can participate in the network as a block producer.
The first step to decentralizing the sequencer is to still have one sequencer at a time, but rotate that sequencer with some frequency. The precise mechanic for sequencer rotation is not yet finalized, but will involve two components:
- an **economic mechanism** which creates a competitive market for sequencing, and redirects excess sequencer profits [towards protocol development](https://medium.com/ethereum-optimism/retroactive-public-goods-funding-33c9b7d00f0c).
- a **governance mechanism** which prevents sequencers from prioritizing short-term profits over the long-term health of the network.
After this, the next step is to support multiple concurrent sequencers. This can be simply achieved by adopting a standard BFT consensus protocol, as used by other L1 protocols and sidechains like Polygon and Cosmos.
You can keep up with the roadmap progress in [Cannon repository](https://github.com/ethereum-optimism/cannon/) for the fault proofs and [Optimism specs repository](https://github.com/ethereum-optimism/optimistic-specs) for the overall protocol work.
<!-- - Welcome! Give context -- "how to read these docs" -->
Optimism is a Layer 2 scaling protocol for Ethereum applications.
I.e., it makes transactions cheap. Real cheap.
We aim to make transacting on Ethereum affordable and
accessible to anyone.
This document is intended for anyone looking for a deeper understanding of how the protocol works
'under the hood'.
Optimism is meant to look, feel and behave like Ethereum but cheaper and faster.
For developers building on our Optimism, we aim to make the transition as seamless as possible.
With very few exceptions,
existing Solidity smart contracts can run on L2 exactly how they run on L1.
Similarly, off-chain code (ie. UIs and wallets), should be able to interact with L2 contract with little more than an updated RPC endpoint.
## System Overview
The smart contracts in the Optimism protocol can be separated into a few key components. We will discuss each component in more detail below.
-**[Chain:](#chain-contracts)** Contracts on layer-1, which hold the ordering of layer-2 transactions, and commitments to the associated layer-2 state roots.
-**[Verification:](#verification)** Contracts on layer-1 which implement the process for challenging a transaction result.
-**[Bridge:](#bridge-contracts)** Contracts which facilitate message passing between layer-1 and layer-2.
-**[Predeploys:](#predeployed-contracts)** A set of essential contracts which are deployed and available in the genesis state of the system. These contracts are similar to Ethereum's precompiles, however they are written in Solidity, and can be found at addresses prefixed with 0x42.
## Chain Contracts
The Chain is composed of a set of contracts running on the Ethereum mainnet. These contracts store ordered
lists of:
1. An _ordered_ list of all transactions applied to the L2 state.
2. The proposed state root which would results from the application of each transaction.
3. Transactions sent from L1 to L2, which are pending inclusion in the ordered list.
<!--
**Planned section outline**
- Delineation between CTC and SCC,
-**high priority**: explain once and for all that challenges roll back state roots, but NOT transactions
- Diagram of "the chains" and what is stored on chain -- ideally illustrates the "roll up" mechanism whereby only roots of batches are SSTOREd
- Sequencing -- what are the properties, what are the implications
- Ring buffer?? (lean deprioritize)
-->
The chain is composed of the following concrete contracts:
The Canonical Transaction Chain (CTC) contract is an append-only log of transactions which must be applied to the OVM state. It defines the ordering of transactions by writing them to the `CTC:batches` instance of the Chain Storage Container. The CTC also allows any account to `enqueue()` an L2 transaction, which the Sequencer must eventually append to the rollup state.
The State Commitment Chain (SCC) contract contains a list of proposed state roots which Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique state root calculated off-chain by applying the canonical transactions one by one.
Provides reusable storage in the form of a "Ring Buffer" data structure, which will overwrite storage slots that are no longer needed. There are three Chain Storage Containers deployed, two are controlled by the CTC, one by the SCC.
<!-- stackex: TODO - create a stackexchange Q and A, to make this term real. -->
## Verification
In the previous section, we mentioned that the Chain includes a list of the _proposed_ state roots
resulting from each transaction. Here we explain a bit more about how these proposals happen, and how
we come to trust them.
In brief: If a proposed state root is not the correct result of executing a transaction, then a Verifier (which is anyone running an Optimism 'full node') can initiate a transaction result challenge. If the transaction result is successfully proven to be incorrect, the Verifier will receive a reward taken from funds which a Sequencer must put up as a bond.
::: Notice
This system is still being written, so these details are likely to
The Bond Manager contract handles deposits in the form of an ERC20 token from bonded Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a challenge. In the event of a successful challenge, the faulty Proposer's bond is slashed, and the Verifier's gas costs are refunded.
## Bridge Contracts
The Bridge contracts implement the functionality required to pass messages between layer 1 and layer 2. [You can read an overview
here](/docs/developers/bridge/messaging.html)
<!--
**Planned section outline**
- Low-level tools (ovmL1TXORIGIN, state committment access)
### Key concepts
-**Relaying** refers to executing a message sent from the other domain, ie. "this message was relayed
-->
The Bridge is composed of the following concrete contracts:
The L1 Cross Domain Messenger (L1xDM) contract sends messages from L1 to L2, and relays messages from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 epoch gas limit, it can be resubmitted via this contract's replay function.
The L2 Cross Domain Messenger (L2xDM) contract sends messages from L2 to L1, and is the entry point for L2 messages sent via the L1 Cross Domain Messenger.
## The Standard Bridge
One common case of message passing is "transferring" either ERC-20
tokens or ETH between L1 and Optimism. To deposit tokens
into Optimism, the bridge locks them on L1 and mints equivalent
tokens in Optimism. To withdraw tokens, the bridge burns the
Optimism tokens and releases the locked L1 tokens. [More details
are here](/docs/developers/bridge/standard-bridge.html)
Factory contract for creating standard L2 token representations of L1 ERC20s compatible with and working on the standard bridge.
[See here for more information](https://github.com/ethereum-optimism/optimism-tutorial/tree/main/standard-bridge-standard-token).
## Predeployed Contracts
"Predeploys" are a set of essential L2 contracts which are deployed and available in the genesis state of the system. These contracts are similar to Ethereum's precompiles, however they are written in Solidity and can be found in the OVM at addresses prefixed with 0x42.
Looking up predeploys is available in the Solidity library [`Lib_PredeployAddresses`](https://github.com/ethereum-optimism/optimism/blob/master/packages/contracts/contracts/libraries/constants/Lib_PredeployAddresses.sol) as well as in the `@eth-optimism/contracts` package as `predeploys` export.
The L1MessageSender is a predeployed contract running on L2.
During the execution of cross domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()` function.
Note that this contract is not written in Solidity. However,
the interface linked above still works as if it were. In this way
The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of a message on L2. The L1 Cross Domain Messenger performs this proof in its _verifyStorageProof function, which verifies the existence of the transaction hash in this contract's `sentMessages` mapping.
The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by any account. It accepts a more efficient compressed calldata format, which it decompresses and encodes to the standard EIP155 transaction format. This contract is the implementation referenced by the Proxy Sequencer Entrypoint, thus enabling the Optimism team to upgrade the decompression of calldata from the Sequencer.
The OP Stack is a decentralized development stack maintained by the Optimism Collective and built to power Optimism.
The OP Stack is constantly evolving as new layers and modules are developed. The OP Stack is also not a product (in the traditional sense) but rather a collection of software components that power the Optimism ecosystem.
**A “Release” of the OP Stack is a particular set of software components that are production-ready and which fit the stack’s design principles and goals.**
Only the software components included within the Current Release of the OP Stack are considered in the scope of the OP Stack. Anything usage of the OP Stack outside of the official, intended capabilities of the Current Release are considered [OP Stack Hacks](../build/hacks.md) — unofficial modifications that are useful for experimentation but could have unforeseen results, such as security vulnerabilities, and are likely cause your chain to no longer be interoperable with the Optimism Superchain (link). **Developer support for OP Stack Hacks is limited — when in doubt, stick to the capabilities of the Current Release!**
The first release of the OP Stack is called **Bedrock**.
The Bedrock release primarily consists of the core software required to run L2 blockchains and was originally designed to power an upgrade to the Optimism Mainnet network.
## Resources
### Rollup Protocol
Learn about the basics of the Rollup protocol used by Bedrock on the Rollup Protocol page.
### Bedrock Explainer
Learn all about the Bedrock release of the OP Stack by reading the Bedrock Explainer.
### Specifications
Dive deep into the specifications for the Bedrock release in the [specs folder of the Optimism Monorepo](https://github.com/ethereum-optimism/optimism/blob/develop/specs/README.md).
Security in crypto is vital. Users, developers and infrastructure providers expect the code to work as intended. When it doesn't, these same groups (rightfully) demand a fast, secure, and clearly communicated fix.
Over the years at Optimism we have learned a great deal about this delicate balance, and the importance of transparency around security models. It is not good enough to just be transparent, it also needs to be accessible. If the average user cannot understand your security model then it does not matter how transparent it is.
In line with this philosophy of transparency we have a very accessible run down of [Optimism's security model](./optimism-security-model.md) that anyone can understand.
We also have a long standing [bug bounty program](./bounties.md) that has paid out one of the largest open source software bounties ever!
We take your trust very seriously and we are super excited to have you along for our decentralisation journey.
Optimism takes security seriously and as such, we have a massive bug bounty program. We don't just talk about it either! We have given out one of the [largest bounty payouts ever](https://medium.com/ethereum-optimism/disclosure-fixing-a-critical-bug-in-optimisms-geth-fork-a836ebdf7c94)! You can read more about that bug [here](https://www.saurik.com/optimism.html). Below are the various bug bounty programs we have, as well as how to reach out to us if your bug is not covered by an existing bounty.
### Main Bounty Page
Optimism has a very detailed [Bug bounty Page on Immunefi](https://immunefi.com/bounty/optimism/). In the listing you can find all the information relating to assets in scope, reporting, and the payout process.
### Bedrock Bounty
With our upcoming launch of [Bedrock](../developers/bedrock/how-is-bedrock-different.md) we will be launching a specific bug bounty program. Follow our [Twitter](https://twitter.com/optimismFND) or keep an eye on [Immunefi](https://immunefi.com/bounty/optimism/) for more information.
### Unscoped Bug
If you think you have found a critical or major bug that is not covered by our existing bug bounty, please report it to us via the Immunefi program regardless. We will seriously consider the impact of any issues, and have previously rewarded security researchers for bugs not within the stated scope of the program.
Constantly pushing to improve the security guarantees that users have while using Optimism is a top priority.
At the moment, **it’s important to understand that the security of the Optimism blockchain is dependent on a [multisig wallet](https://www.coindesk.com/tech/2020/11/10/multisignature-wallets-can-keep-your-coins-safer-if-you-use-them-right/)** managed by several anonymous individuals.
This multisig wallet can be used to upgrade core Optimism smart contracts without upgrade delays.
Please also keep in mind that just like any other system, **the Optimism codebase may contain unknown bugs** that could lead to the loss of some or all of the assets held within the system.
[Optimism’s smart contract codebase has been audited repeatedly](https://github.com/ethereum-optimism/optimism/tree/develop/technical-documents/audits) but **audits are not a stamp of approval** and **a completed audit does not mean that the audited codebase is free of bugs.**
It’s important to understand that using Optimism inherently exposes you to the risk of bugs within the Optimism codebase.
## Security Model FAQ
### Does Optimism have fault proofs?
**No**, Optimism does not currently have fault proofs.
**Fault proofs do not meaningfully improve the security of a system if that system can be upgraded within the 7 day challenge window (”fast upgrade keys”)**.
A system with fast upgrade keys, such as Optimism, is fully dependent on the upgrade keys for security.
Optimism’s goal is to be the first system that deploys fault proofs that can secure the system by themselves, without fast upgrade keys.
### Who manages the multisig?
The multisig is managed by an anonymous set of individuals.
Members are anonymous in order to make the multisig more difficult to compromise.
### How is Optimism planning to remove the multisig?
Check out Optimism’s detailed [Pragmatic Path to Decentralization](https://medium.com/ethereum-optimism/our-pragmatic-path-to-decentralization-cb5805ca43c1) post for a detailed view into how the multisig may be removed in a way that makes Optimism the first chain with true fault proof security.
### How can I help make Optimism more secure?
[Optimism has one of the biggest bug bounties (ever)](https://immunefi.com/bounty/optimism/).
You can earn up to $2,000,042 by finding critical bugs in the Optimism codebase.
You can also [run your own verifier node](https://github.com/smartcontracts/simple-optimism-node/) to detect network faults.
The OP Stack is a work in progress. Constantly pushing to improve the overall security and decentralization of the OP Stack is a top priority.
:::
## Security in the decentralized context
The OP Stack is a decentralized development stack that powers Optimism. Components of the OP Stack may be maintained by various different teams within the Optimism Collective. It is generally easier to talk about the security model of specific chains built on the OP Stack rather than the security model of the stack itself. **The OP Stack security baseline is to create safe defaults while still giving developers the flexibility to make modifications and extend the stack.**
## FAQ
### Is every OP Stack chain safe?
The security model of an OP Stack based blockchain depends on the modules used for its components. Because of the flexibility provided by OP Stack, it is always possible to set up an insecure blockchain using OP Stack components. **The goal of the OP Stack is to provide safe defaults.**
Please also keep in mind that just like any other system, **the OP Stack may contain unknown bugs** that could lead to the loss of some or all of the assets held within an OP Stack based system. [Many components of the OP Stack codebase have been audited](https://github.com/ethereum-optimism/optimism/tree/develop/technical-documents/security-reviews) but **audits are not a stamp of approval** and **a completed audit does not mean that the audited codebase is free of bugs.** It’s important to understand that using the OP Stack inherently exposes you to the risk of bugs within the OP Stack codebase.
### Is the OP Stack safe to modify?
As with anything, modify the OP Stack at your own risk. There is no guarantee that modifications to the stack will be safe. If you aren’t entirely sure about what you’re doing, stick with the safer defaults that the OP Stack provides. At the moment, the OP Stack is not particularly amenable to modifications and **you should not expect any technical support for modifications that fall outside of the standard Rollup configuration of the stack**.
### Can I use fault proofs?
**Not yet.** The OP Stack does not currently have a fault proof system. **Note that fault proofs do not meaningfully improve the security of a system if that system can be upgraded within the 7 day challenge window (”fast upgrade keys”)**. A system with fast upgrade keys is fully dependent on the upgrade keys for security.
Fault proofs are a key roadmap item and top priority for the OP Stack. In the meantime, the OP Stack can be shipped with several other excellent security options for systems that want to improve security before fault proofs are available in production.
### How can I help make the OP Stack more secure?
One of the easiest ways to help secure the OP Stack is to look for bugs and vulnerabilities. [Optimism Mainnet, a user of the OP Stack, has one of the biggest bug bounties (ever)](https://immunefi.com/bounty/optimism/). You can earn up to $2,000,042 by finding critical bugs in the Optimism Mainnet codebase (and by extension the OP Stack).
Don’t forget that the OP Stack is a decentralized development stack. Anyone can start to contribute to the OP Stack by building software that follows [the stack’s design principles](../understand/design-principles.md). You can always help make the OP Stack more secure by building components, like alternative client or proof implementations, that users of the OP Stack can take advantage of.
title:Security Policy, Vulnerability Reporting, and Bug Bounties
lang:en-US
---
## Reporting in the decentralized context
It's important to remember that the OP Stack is a decentralized software development stack built by the Optimism Collective. Different components of the OP Stack may be maintained by different teams that have different reporting processes. **This page describes general best practices for reporting bugs and provides specific reporting guidelines for the OP Stack code contained within the [ethereum-optimism](https://github.com/ethereum-optimism) GitHub organization**.
## Reporting bugs and vulnerabilities
::: danger 🚫 How NOT to disclose a vulnerability
Do *not* disclose vulnerabilities publicly or by executing them against a production network. If you do, will you not only be putting users at risk, but you will forfeit your right to a reward. Always follow the appropriate reporting pathways as described below.
- Do *not* disclose the vulnerability publicly, for example by filing a public ticket.
- Do *not* test the vulnerability on a publicly available network, either the testnet or the mainnet.
:::
### OP Stack bounty programs
The security of OP Stack smart contracts and blockchain infrastructure is paramount. Below are the various OP Stack-related bug bounty programs, as well as how to reach out if your bug is not covered by an existing bounty.
#### Optimism Mainnet bounty program
Optimism Mainnet is covered by a comprehensive [bug bounty program on Immunefi](https://immunefi.com/bounty/optimism/), which has already resulted in one of the [largest bounty payouts ever](https://medium.com/ethereum-optimism/disclosure-fixing-a-critical-bug-in-optimisms-geth-fork-a836ebdf7c94). In the listing you can find all the information relating to assets in scope, reporting, and the payout process. Because Optimism Mainnet is currently the primary user of the OP Stack, bugs in OP Stack software can generally be reported via the Optimism Mainnet bounty program.
#### Unscoped bugs
If you think you have found a significant bug or vulnerabilities in OP Stack smart contracts, infrastructure, etc., even if that component is not covered by an existing bug bounty, please report it to via the [Optimism Mainnet Immunefi program](https://immunefi.com/bounty/optimism/). The impact of any and all reported issues will be considered and the program has previously rewarded security researchers for bugs not within its stated scope.
### Other vulnerabilities
For vulnerabilities in any websites, email servers, or other non-critical infrastructure within the OP Stack, please email [OP Labs](https://www.oplabs.co/) at [security@oplabs.co](mailto:security@oplabs.co) and include detailed instructions for confirming and reproducing the vulnerability.
## Vulnerability disclosure
Each OP Stack component maintainer may determine its own process for vulnerability disclosure. However, the following describes a recommended process for disclosure that is currently in use by [OP Labs](https://www.oplabs.co/).
In the event that an OP Stack component maintainer learns of a critical security vulnerability, the maintainer reserves the right to silently fix it without immediately publicly disclosing the existence of nature of the vulnerability.
In such a scenario, the disclosure process used by [OP Labs](https://www.oplabs.co/) is as follows:
1. Silently fix the vulnerability and include the fix in release X.
1. After 4-8 weeks, disclose that release X contained a security fix.
1. After an additional 4-8 weeks, publish details of the vulnerability, along with credit to the reporter (with express permission from the reporter).
Alongside this policy, maintainers also reserve the right to:
- Bypass this policy and publish details on a shorter timeline.
- Directly notify a subset of downstream users prior to making a public announcement.
This policy is based the [Geth](https://geth.ethereum.org/) team’s [silent patch policy](https://geth.ethereum.org/docs/vulnerabilities/vulnerabilities#why-silent-patches).
**The OP Stack is the standardized, shared, and open-source development stack that powers Optimism, maintained by the Optimism Collective.**
The OP Stack consists of the many different software components managed and maintained by the Optimism Collective that, together, form the backbone of Optimism.
The OP Stack is built as a public good for the Ethereum and Optimism ecosystems.
## The OP Stack powers Optimism
The OP Stack is the set of software that powers Optimism — currently in the form of the software behind Optimism Mainnet and eventually in the form of the Optimism Superchain and its governance.
With the advent of the Superchain concept, it has become increasingly important for Optimism to easily support the secure creation of new chains that can interoperate within the proposed Superchain ecosystem.
As a result, the OP Stack is primarily focused around the creation of a shared, high-quality, and fully open-source system for creating new L2 blockchains.
By coordinating on shared standards, the Optimism Collective can avoid rebuilding the same software in silos repeatedly.
Although the OP Stack today significantly simplifies the process of creating L2 blockchains, it’s important to note that this does not fundamentally define what the OP Stack **is**.
The OP Stack is *all* of the software that powers Optimism.
As Optimism evolves, so will the OP Stack.
**The OP Stack can be thought of as software components that either help define a specific layer of the Optimism ecosystem or fill a role as a module within an existing layer**
Although the current heart of the OP Stack is infrastructure for running L2 blockchains, the OP Stack theoretically extends to layers on top of the underlying blockchain including tools like block explorers, message passing mechanisms, governance systems, and more.
Layers are generally more tightly defined towards the bottom of the stack (like the Data Availability Layer) but become more loosely defined towards the top of the stack (like the Governance Layer).
## The OP Stack today
Optimism Bedrock is the current iteration of the OP Stack.
The Bedrock release provides the tools for launching a production-quality Optimistic Rollup blockchain.
At this point in time, the APIs for the different layers of the OP Stack are still tightly coupled to this Rollup configuration of the stack.
If you'd like to learn more about the current state of the OP Stack, check out [the page describing the Bedrock release](../releases/bedrock.md).
The OP Stack of today was built to support the Optimism Superchain (link), a proposed network of L2s that share security, communication layers, and a common development stack (the OP Stack itself).
The Bedrock release of the OP Stack makes it easy to spin up an L2 that will be compatible with the Superchain when it launches.
If you'd like to launch a Superchain-ready L2, check out our guide for running a chain based on the Bedrock release of the OP Stack.
It is possible to modify components of the OP Stack to build novel L2 systems.
If you're interested in experimenting with the OP Stack, check out [the OP Stack Hacks section of this site](../build/hacks.md).
Please note that, as of the Bedrock release, the OP Stack is *not* designed to support these modifications and you will very much be *hacking* on the codebase.
As a result, **you should, for the moment, expect limited (if any) developer support for OP Stack Hacks.**
OP Stack Hacks will likely make your chain incompatible with the Optimism Superchain.
Have fun, but at your own risk and **stick to the Bedrock release if you're looking to join the Superchain!**
## The OP Stack tomorrow
The OP Stack is an evolving concept.
As Optimism grows, so will the OP Stack.
Today, the Bedrock Release of the OP Stack simplifies the process of deploying new L2 Rollups.
As work on the stack continues, it should become easier to plug in and configure different modules.
As the Superchain (link) begins to take shape, the OP Stack can evolve alongside it, to include the message-passing infrastructure that allows different chains to interoperate seamlessly.
At the end of the day, the OP Stack becomes what Optimism needs.
## Dive Deeper into the OP Stack
Ready to dive into the world of the OP Stack?
- If you’re interested in learning more about the current release of the OP Stack, check out the Bedrock Release page.
- If you’re interested in understanding the OP Stack in more depth, start with the [Design Principles](./design-principles.md) and [Landscape Overview](./landscape.md).
- If you're excited to join the Superchain, launch your first Superchain-ready L2 with our [Getting Started guide](../build/getting-started.md) or dive directly into the OP Stack codebase to learn more.
The OP Stack is the next frontier for Ethereum. You’re already here, so what are you waiting for?
The OP Stack is a set of software components for building L2 blockchain ecosystems, built by the Optimism Collective to power Optimism.
Components to be added to the OP Stack should be built according to three key design principles:
-**U**tility
-**S**implicity
-**E**xtensibility.
Software that follows these principles is **USE**ful software for the Optimism Collective!
:::
## Utility
For something to be part of the OP Stack, it should help power the Optimism Collective.
This condition helps guide the type of software that can be included in the stack.
For instance, a powerful open-source block explorer that makes it easier for users to inspect the Superchain would be a great addition to the OP Stack.
Although utility is important for inclusion in the OP Stack, you shouldn’t be afraid to experiment.
Do something crazy.
Build something that’s never been built before, even if it doesn’t have any clear utility. Make a blockchain for Emojis, or whatever. Have fun!
## Simplicity
Complex code does not scale.
Code that makes it into the OP Stack should be simple.
Simplicity reduces engineering overhead, which in turn means the Collective can spend its time working on new features instead of re-creating existing ones.
The OP Stack prefers to use existing battle-tested code and infrastructure where possible.
The most visible example of this philosophy in practice is the choice to use Geth as the OP Stack’s default execution engine.
When dealing with critical infrastructure, simplicity is also security and maintainability.
Every line of code written is an opportunity to introduce bugs and vulnerabilities.
A simple protocol means there's less code to write and, as a result, less surface area for potential mistakes.
A clean and minimal codebase is also more accessible to external contributors and auditors.
All of this serves to maximize the security and correctness of the OP Stack.
## Extensibility
Good OP Stack code is inherently open, collaborative, and extensible.
Collaboration allows us to break out of siloed development.
Collaboration allows us spend more time building on top of one another's work and less time rebuilding the same components over and over again.
Collaboration is how we win, *together*.
Extensible code should be designed with the mindset that others will want to build with and on top of that code.
In practice, this means that the code should be open source (under a permissive license), expose clean APIs, and generally be modular such that another developer can relatively easily extend the functionality of the code.
Extensibility is a key design principle that unlocks the superpower of collaboration within the Optimism Collective ecosystem.
## Contributing to the OP Stack
The OP Stack is a decentralized software stack that anyone can contribute to.
If you're interested in contributing to the OP Stack, check out [the Contributing section of these docs](../CONTRIB.md).
Of course, software that has impact for the Optimism Collective can receive Retroactive Public Goods Funding.
Build for the OP Stack — get rewarded for writing great open source software. What's not to love?
**The OP Stack is a common development stack for building L2 blockchain ecosystems, built by the Optimism Collective to power Optimism.**
The OP Stack is best thought of as a collection of software components maintained by the Optimism Collective that either help to define new layers of the stack or fit in as modules within the stack.
Because the OP Stack is a work in progress, the landscape of the different layers and modules is still evolving.
This page sketches out the different conceptual layers of the stack as they exist today and introduces some of the modules that fit into those layers.
This doesn't include all of the modules or layers that may exist in the future, but gives a good overview of the landscape of the OP Stack today.
If you’re interested in learning more about the latest *production* release of the OP Stack, the components of the stack that are highly tested and ready for real-world action, check out the page about the [Bedrock Release](../releases/bedrock.md).
::: warning
Please note that not all of the modules described on this page already exist in a production state — these are explicitly marked as either “**in development**” or “**proposed**”
:::
## Existing Landscape

## Layers
### Data Availability
The Data Availability Layer defines where the raw inputs to an OP Stack based chain are published. An OP Stack chain can use one or more Data Availability module to source its input data. Because an OP Stack chain is derived from the Data Availability Layer, the Data Availability module(s) used have a significant impact on the security model of a system. For example, if a certain piece of data can no longer be retrieved from the Data Availability Layer, it may not be possible to sync the chain.
#### Ethereum DA
Ethereum DA is currently the most widely used Data Availability module for the OP Stack. When using the Ethereum DA module, source data can be derived from any piece of information accessible on the Ethereum blockchain. This includes Ethereum calldata, events, and 4844 data blobs.
The Sequencing Layer determines how user transactions on an OP Stack chain are collected and published to the Data Availability Layer module(s) in use. In the default Rollup configuration of the OP Stack, Sequencing is typically handled by a single dedicated Sequencer. Rules defined in the Derivation Layer generally restrict the Sequencer’s ability to withhold transactions for more than a specific period of time. In the proposed future, Sequencing will be modular such that chains can easily select and change the mechanism that controls their current Sequencer.
#### Single Sequencer
The default Sequencer module for the OP Stack is the Single Sequencer module in which a dedicated actor is given the ability to act as the Sequencer. The Single Sequencer module allows a governance mechanism to determine who may act as the Sequencer at any given time.
#### Multiple Sequencer (proposed)
A simple modification to the Single Sequencer module is the Multiple Sequencer module in which the Sequencer at any given time is selected from a pre-defined set of possible actors. Individual OP Stack based chains would be able to determine the exact mechanism that defines the set of possible Sequencers and the mechanism that selects a Sequencer from the set.
### Derivation
The Derivation Layer defines how the raw data in the Data Availability Layer is processed to form the processed inputs that are sent to the Execution Layer via the standard [Ethereum Engine API](https://github.com/ethereum/execution-apis/blob/94164851c1630ff0a9c31d8d7d3d4fb886e196c0/src/engine/README.md). The Derivation Layer may also use the current system state, as defined by the Execution Layer, to inform the parsing of raw input data. The Derivation Layer can be modified to derive Engine API inputs from many different data sources. The Derivation Layer is typically tied closely to the Data Availability Layer because it must understand how to parse any raw input data.
#### Rollup
The Rollup module derives Engine API inputs from Ethereum block data, Sequencer transaction batches, Deposited transaction events, and more.
The Indexer module is a proposed Derivation Layer module that would derive Engine API inputs when transactions are sent to, events are emitted by, or storage is modified in specific smart contracts on a Data Availability Layer module like Ethereum DA.
### Execution
The Execution Layer defines the structure of state within an OP Stack system and defines the state transition function that mutates this state. State transitions are triggered when inputs are received from the Derivation Layer via the Engine API. The Execution Layer abstraction opens up the door to EVM modifications or different underlying VMs entirely.
#### EVM
The EVM is an Execution Layer module that uses the same state representation and state transition function as the Ethereum Virtual Machine. The EVM module in the Ethereum Rollup configuration of the OP Stack is a [lightly modified](https://op-geth.optimism.io/) version of the EVM that adds support for L2 transactions initiated on Ethereum and adds an extra L1 Data Fee to each transaction to account for the cost of publishing transactions to Ethereum.
-[Specifications](https://github.com/ethereum-optimism/optimism/blob/develop/specs/exec-engine.md)(where it differs from [geth](https://geth.ethereum.org/))
The Settlement Layer is a mechanism on external blockchains that establish a **view** of the state of an OP Stack chain on those external chains (including other OP Stack chains). For each OP Stack chain, there may be one or more Settlement mechanisms on one or more external chains. Settlement Layer mechanisms are **read-only** and allow parties external to the blockchain to make decisions based on the state of an OP Stack chain.
The term “Settlement Layer” has its origins in the fact that Settlement Layer mechanisms are often used to handle withdrawals of assets out of a blockchain. This sort of withdrawal system first involves proving the state of the target blockchain to some third-party chain and then processing a withdrawal based on that state. However, the Settlement Layer is not strictly (or even predominantly) financial and, at its core, simply allows a third-party chain to become aware of the state of the target chain.
Once a transaction is published and finalized on the corresponding Data Availability layer, the transaction is also finalized on the OP Stack chain. Short of breaking the underlying Data Availability layer, it can no longer be modified or removed. It may not be accepted by the Settlement Layer yet because the Settlement Layer needs to be able to verify transaction *results*, but the transaction itself is already immutable.
#### Attestation-based Fault Proof
An Attestation-based Fault Proof mechanism uses an optimistic protocol to establish a view of an OP Stack chain. In optimistic settlement mechanisms generally, **Proposer** entities can propose what they believe to be the current valid state of the OP Stack chain. If these proposals are not invalidated within a certain period of time (the “challenge period”), then the proposals are assumed by the mechanism to be correct. In the Attestation Proof mechanism in particular, a proposal can be invalidated if some threshold of pre-defined parties provide attestations to a valid state that is different than the state in the proposal. This places a trust assumption on the honesty of at least a threshold number of the pre-defined participants.
#### Fault Proof Optimistic Settlement (proposed & in development)
A Fault Proof Optimistic Settlement mechanism is mostly identical to the Attestation-based Fault Proof mechanism used today but it replaces the MultiSig challenger with a permissionless fault proving process. A correctly constructed fault proof should be able to invalidate any incorrect proposals during the allocated challenge period. This places a trust assumption on the correctness of the fault proof construction.
#### Validity Proof Settlement (proposed)
A Validity Proof Settlement mechanism uses a mathematical proof to attest to the correctness of a proposed view. A proposed state will not be accepted without a valid proof. This places a trust assumption on the correctness of the validity proof construction.
### Governance
The Governance Layer refers to the general set of tools and processes used to manage system configuration, upgrades, and design decisions. This is a relatively abstract layer that can contain a wide range of mechanisms on a target OP Stack chain and on third-party chains that impact many of the other layers of the OP Stack.
#### MultiSig Contracts
MultiSig Contracts are smart contracts that carry out actions when they receive a threshold of signatures from some pre-defined set of participants. These are often used to manage upgrades of components of an OP Stack based system. Currently, this is the mechanism used to manage upgrades of the bridge contracts on Optimism Mainnet. The security of a MultiSig Contract system depends on many different factors, including the number of participants, the threshold, and the safety procedures of each individual participant.
#### Governance Tokens
Governance Tokens are widely used to decentralize decision making. Although the exact functionality of a Governance Token varies on a case-by-case basis, the most common mechanisms allow token holders to vote on some subset of decisions that a project must make. Voting can either be carried out directly or via delegation.
If you are already familiar with [building on Optimism](../developers/README.md) and just need the tools to get cracking, you are in the right place!
## Connecting
You have the list of [networks](./networks.md) and [node providers](./providers.md) to help you connect to an Optimism node.
## Deploying
To get some ETH bridged over for deployment gas fees, use one of the available [faucets](./faucets.md) or just bridge ETH using the [Optimism Gateway](https://gateway.optimism.io/).
## Monitoring
Your app is live in production? Watch it grow using one of the [monitoring tools](./monitoring.md). We also have a set of [troubleshooting tools](./debugging.md) and [block explorers](./explorers.md) to help you provide a stellar service to your users.
As Optimism is [EVM Equivalent](https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306), most debugging tools work out the box with Optimism.
:::
## Tenderly
[Tenderly](https://tenderly.co/) lets you inspect any transaction execution on the Optimism mainnet.
You can inspect the state of your verified contract in any step of the transactions execution, as well as step into or over function calls.
## Etherscan
[Etherscan](https://explorer.optimism.io) allows you to see events as well as revert messages for transactions that have been mined on Optimism (mainnet) as well as [Optimism Goerli (testnet)](https://goerli-explorer.optimism.io).
You can see more information about all the L2 features Etherscan offers in our [Explorers page](./explorers.md#etherscan).
## Blockscout
[Blockscout](https://blockscout.com/optimism/goerli/) allows you to see events on our Goerli testnet.
## Know other good tools?
Reach out to us in our [Discord](https://discord-gateway.optimism.io) or [make a PR](https://github.com/ethereum-optimism/community-hub/pulls).
We'd love your help in expanding the tools available to build Optimistically.
We have a Blockscout explorer for the [Goerli testnet](https://blockscout.com/optimism/goerli/). It includes:
-[Verified contract source code, along with the ability to interact with it](https://blockscout.com/optimism/goerli/address/0x106941459A8768f5A92b770e280555FAF817576f/contracts#address-tabs)
We have Etherscan explorers for the [Optimism mainnet](https://explorer.optimism.io) and the [Optimism Goerli testnet](https://goerli-explorer.optimism.io).
Etherscan has lots of tools to help you debug transactions.
Optimistic Etherscan has all the tools you expect from Etherscan, such as:
-[Verified contract source code, along with the ability to interact with it](https://explorer.optimism.io/address/0x420000000000000000000000000000000000000F#code)
If none of the Etherscan CSV files contains the information you need, you can use a query on [Dune Analytics](https://dune.xyz), similar to [this query](https://dune.xyz/queries/354886?addr=%5Cx25E1c58040f27ECF20BBd4ca83a09290326896B3).
You have to log on with a Dune account, but their free tier is sufficient.
```sql
SELECT*FROMoptimism.transactions
WHERE"from"='{{addr}}'or"to"='{{addr}}'
LIMIT100
```
Notes:
- Make sure to select the data source **Optimism (OVM 1.0)**
- This is how you specify parameters in Dune, `{{` followed by the parameter name and then `}}`.
- Addresses are specified as `\x<hex address>` rather than `0x<hex address>`.
- The limit is not required, but here to save resources
-->
### Pre 23 June 2021 history
Follow these steps:
1. Clone go-ethereum (the standard version) and checkout version v1.9.10:
You can then use ERC20 events filters to get the events that you want for each address. Note that you will have to repeat this process for each datadir to get the full event history.
If you are non-technical and need help requesting this data please reach out to us in Discord and we will be happy to help.
Meta-transactions let users sign transactions that are then submitted (and the gas paid for) by somebody else.
Optimism is a good place for meta-transactions because the low gas costs make it possible to explore business models that allow for payment for transactions by other means.
Here are some example use cases for meta-transactions:
-**On boarding**.
Users who aren't committed to web3 yet need to pay and go through [KYC](https://www.thalesgroup.com/en/markets/digital-identity-and-security/banking-payment/issuance/id-verification/know-your-customer) before they can do anything.
This is a bad initial experience that can cause people to decide they prefer to investigate something else, especially for non-
-**Privacy**.
It's easy to use a new address for privacy purposes.
It is a lot harder to transfer ETH to the new address privately without creating a connection between it and your identity.
-**Transaction payment by other means**.
With meta-transactions you can collect payment for transactions either using a different token (ERC-20) or a off-chain means (for example a credit card).
## OpenGSN
The [Gas Station Network](https://opengsn.org/) is distributed infrastructure for meta-transaction that allows you to create your own relay, or pay other relays to relay your users' traffic.
Relays have to post a bond, which they lose if they attempt to censor transactions (by pretending to accept them without sending them on chain).
See here for [their documentation](https://docs.opengsn.org/).
Check out the [Optimism status page](https://status.optimism.io/).
This page includes public APIs, the gateway, deposits, withdraws and transaction sequencing for both Optimism mainnet and Optimism Goerli.
## Public Grafana Dashboard
[Optimism](https://optimism.io) maintains a [public Grafana dashboard](https://public-grafana.optimism.io/d/9hkhMxn7z/public-dashboard?orgId=1&refresh=5m) that tracks gas prices, transaction volume, and network uptime in one place.
You can view information about both the Optimism mainnet and the Optimism Goerli testnet on this dashboard.
## Block explorers
### Etherscan
Etherscan provides a lot of detailed information about what's happening on Optimism.
Check out the [Optimism mainnet explorer](https://explorer.optimism.io) as well as the [Optimism Goerli explorer](https://goerli-explorer.optimism.io) to get a look for yourself.
### Blockscout
Another block explorer for the Georli test network is [Blockscout](https://blockscout.com/optimism/goerli/).
## Dashboards on Dune Analytics
[Dune Analytics](https://dune.xyz) allows anyone to create dashboards that present information about Optimism Ethereum.
You can find a full list of community created dashboards for Optimism [here](https://dune.xyz/browse/dashboards?q=optimism), or [create your own](https://docs.dune.xyz/#queries) dashboard.
We recommend using [Alchemy](https://www.alchemy.com/optimism) for its scalablity, reliability, and data accuracy.
:::
::: warning
Some API calls, such as the those in the [personal namespace](https://geth.ethereum.org/docs/rpc/ns-personal) make no sense in a shared environment.
Such RPCs are either totally unsupported, or will return nonsensical values.
:::
## Optimism (mainnet)
::: tip Pre-Bedrock
We are currently testing the [Bedrock](../developers/bedrock/bedrock.md) release.
The mainnet network has still not been updated.
:::
| Parameter | Value |
| --------- | ----- |
| Network Name | **`Optimism`** |
| Description | **`Mainnet`** |
| Chain ID | **`10`** |
| Explorer | **[https://explorer.optimism.io](https://explorer.optimism.io)** |
| HTTP Endpoint<sup>1</sup> | We recommend [Alchemy](https://docs.alchemy.com/reference/optimism-api-quickstart/?a=818c11a8da). Optimism also provides this endpoint: **`https://mainnet.optimism.io`.** _But it is not for production systems and is rate limited._ |
If you are seeing rate limit issues when testing with the public end point, or if you need websocket functionality, we recommend signing up for [Alchemy's](https://www.alchemy.com/optimism) free trial.
:::
(1) Some API calls, such as those in the [personal namespace](https://geth.ethereum.org/docs/rpc/ns-personal) make no sense in a shared environment.
Such RPCs are either not supported, or will return nonsensical values.
### API Options:
1. Get free access to Optimism through [Alchemy](https://www.alchemy.com/optimism)
2. For small scale tests, you can use our public API:
- HTTP endpoint: [https://mainnet.optimism.io](https://mainnet.optimism.io)(note, this is for testing. For production, use Alchemy)
You can run a large application for free using [Alchemy](https://www.alchemy.com/optimism). We’ve done extensive diligence and Alchemy is our recommendation due to reliability, scalability, and data correctness. They're the default API provider and developer platform for top projects like OpenSea and Facebook.
## Optimism Goerli
::: tip Purpose
This is our test network.
It has already been updated to the [Bedrock](../developers/bedrock/bedrock.md) release.
:::
| Parameter | Value |
| --------- | ----- |
| Network Name | **`Optimism Goerli`** |
| Description | **`Testnet (public)`** |
| Chain ID | **`420`** |
| Explorer | **[https://goerli-explorer.optimism.io](https://goerli-explorer.optimism.io)** |
The authoritative list of contract addresses is [in the monorepo](https://github.com/ethereum-optimism/optimism/tree/develop/packages/contracts-bedrock/deployments/goerli).
1. Get free access to Optimism through [Alchemy](https://www.alchemy.com/optimism)
2. For small scale tests, you can use our public API:
- HTTP endpoint: [https://goerli.optimism.io](https://goerli.optimism.io)(note, this is for testing. For production, use Alchemy)
You can run a large application for free using [Alchemy](https://www.alchemy.com/optimism). We’ve done extensive diligence and Alchemy is our recommendation due to reliability, scalability, and data correctness.
They're the default API provider and developer platform for top projects like OpenSea and Facebook.
They also support websocket functionality, which our public endpoint does not.
To see the full list of providers visit [Node & API Providers](./providers.md).
Alternatively, if you already have Goerli ETH, you can [bridge it](https://app.optimism.io/bridge). For more faucet options see [Network Faucets](./faucets.md).
::: warning Ignore other networks
Optimism mainnet and Optimism Goerli are, from Optimism's perspective, production networks. This means our Goerli network is something you can rely on for consistent state and uptime. We have other testnets that we use to test our code (such as the Goerli Nightly network) that we use to test new features. These networks are for _us_ to test, and therefore might not have reliable state & uptime.
If you want to test out our new infrastructure before it is stable, or are interested in working on the latest and greatest protocols please check these networks out! If not, they are best ignored.
We try to make sure they work and preserve the state.
In the months prior to a major release, such as Bedrock, we may have a different network for testing dapps on that release.
However, we also have other networks such as [Goerli Nightly](https://github.com/ethereum-optimism/optimism/tree/develop/packages/contracts/deployments/goerli-nightly).
These are networks that are used for internal Optimism development.
Unless you are working on the Optimism protocol (rather than building things on top of it), ignore these network.
[Oracles](https://ethereum.org/en/developers/docs/oracles/) provide off-chain data on chain.
This allows code running on a blockchain to access a wide variety of information.
For example, a [stablecoin](https://ethereum.org/en/stablecoins/) that accepts ETH as collateral needs to know the ETH/USD exchange rate:
- How many stablecoins can we give a user for a given amount of ETH?
- Do we need to liquidate any deposits because they are under collateralized?
Different oracles have different security assumptions and different levels of decentralization.
Usually they are either run by the organization that produces the information, or have a mechanism to reward entites that provide accurate information and penalize those that provide incorrect information.
## Types of oracles
There are two types of oracles:
1.**Push oracles** are updated continously and always have up to date information available on chain.
1.**Pull oracles** are only updated when information is requested by a contract.
Pull oracles are themselves divided into two types:
1. Double-transaction oracles, which require two transactions.
The first transaction is the request for information, which usually causes the oracle to emit an event that triggers some off-chain mechanism to provide the answer (through its own transaction).
The second transaction actually reads on-chain the result from the oracle and uses it.
1. Single-transaction oracles, which only require one transaction, such as [Chainlink's random nunber generator](https://docs.chain.link/docs/get-a-random-number/#request-random-values).
The way this works is that the transaction that requests the information includes a callback (address and the call data to provide it).
When the oracle is updated (which also happens through a transaction, but one that is not sent by the user), the oracle uses the callback to inform a contract of the result.
## Gas Oracle
Optimism provides a [Gas Price Oracle](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts/contracts/L2/predeploys/OVM_GasPriceOracle.sol) that provides information about [gas prices and related parameters](../developers/build/transaction-fees.md).
It can also calculate the total cost of a transaction for you before you send it.
This contract is a predeploy at address `0x420000000000000000000000000000000000000F`:
-[On the production Optimism network](https://explorer.optimism.io/address/0x420000000000000000000000000000000000000F#readContract)
-[On the Optimism Goerli test network](https://goerli-explorer.optimism.io/address/0x420000000000000000000000000000000000000F)
This is a push Oracle.
Optimism updates the gas price parameters on chain whenever those parameters change.
The L1 gas price, which can be volatile, is only pushed once every 5 minutes, and each time can change only by up to 20%.
## Chainlink
On Optimism [Chainlink](https://chain.link/) provides a number of [price feeds](https://docs.chain.link/docs/optimism-price-feeds/).
Those feeds are available on the production network.
This is a push Oracle.
You can always get up to date information (see, for example, [here (scroll down to **latestAnswer**)](https://explorer.optimism.io/address/0x13e3Ee699D1909E989722E753853AE30b17e08c5#readContract)).
[See this guide to learn how to use the Chainlink feeds](https://docs.chain.link/docs/get-the-latest-price/).
## Portal
[Portal](https://portal-docs.readthedocs.io/en/latest/index.html) offers users private, scalable, and fast compute power at low costs.
### Verifiable Randomness Function (VRF)
#### Portal
Portal providers a source of randomness on chain (for now on Optimism Goerli, but eventually also on the Optimism mainnet).
[You can learn how to use it here](https://portal-docs.readthedocs.io/en/latest/user-vrf-docs.html).
It is a single-transaction pull oracle.
#### Band
[Band](https://bandprotocol.com/vrf) provides a source of [on-chain randomness](https://bandprotocol.com/vrf).
[You can learn how to use it here](https://docs.bandchain.org/vrf/getting-started.html).
It is a single-transaction pull oracle.
## Universal Market Access (UMA)
[UMA](https://umaproject.org/) is a generic oracle.
It lets any contract request information (ask a question), and any staked entity can provide an answer.
Other external entities can dispute the proposed answer by providing their own answer and a putting up their own stake.
In the case of dispute the question goes to a vote of token holders.
The token holders that vote with the majority are assumed to be truthful and get rewarded.
The external entities that proposed the correct answer are rewarded.
Those that proposed the wrong answer lose their stake.
[See here for the UMA addresses on Optimism](https://github.com/UMAprotocol/protocol/blob/master/packages/core/networks/10.json).
[See here for instructions how to use UMA](https://docs.umaproject.org/build-walkthrough/build-process).
UMA is a pull Oracle, it does not get information until it is requested by a contract.
This means that an decentralized application needs to issue two transactions.
First, a transaction that causes a contract on the blockchain to ask for the information.
Later (in the case of UMA 48 hours later if there is no dispute, longer if there is), a second transaction need to be triggered to causes the contract to read from the Oracle and see the response to the request.
## Uniswap
Technically speaking [Uniswap](https://uniswap.io/) is not an oracle, because the information comes from on-chain sources.
However, Uniswap pools do provide [quotes that give the relative costs of assets](https://docs.uniswap.org/protocol/concepts/V3-overview/oracle).
::: warning
Using onchain asset prices, especially those in low liquidity pools, makes you vulnerable to price manipulation.
:::
To use Uniswap as an Oracle:
1. See [the list of pools on Optimism](https://info.uniswap.org/#/optimism/).
1. To find the pool address, [look at the Uniswap factory](https://explorer.optimism.io/address/0x1f98431c8ad98523631ae4a59f267346ea31f984#readContract).
| One token address | [Address of the ERC-20 contract for that token on Optimism (chainId 10)](https://static.optimism.io/optimism.tokenlist.json) |
| Other token address | [Address of the ERC-20 contract for that token on Optimism (chainId 10)](https://static.optimism.io/optimism.tokenlist.json) |
| Pool fee | The pool fee percentage times ten thousand. For example, for 0.3% enter `3000` |
1. In your contract, use [IUniswapV3PoolState](https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/pool/IUniswapV3PoolState.sol) and [IUniswapV3PoolDerivedState](https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol) to get the pool state.
Some API calls, such as the those in the [personal namespace](https://geth.ethereum.org/docs/rpc/ns-personal) make no sense in a shared environment.
Such RPCs are either totally unsupported, or will return nonsensical values.
:::
::: tip
**We strongly recommend all developers use [Alchemy](https://www.alchemy.com/optimism).**
**We’ve done extensive diligence and Alchemy powers our public API.**
We recommend Alchemy due to (a) the reliability, scalability and data correctness of its developer platform and (b) the comprehensive set of tooling and APIs they provide. You can run large applications on their massive free tier.
:::
### Alchemy's Description & Pricing
[Alchemy](https://docs.alchemy.com/reference/optimism-api-quickstart/?a=818c11a8da) is our recommended Optimism API provider and developer platform. Its robust, free tier offers access to (1) enhanced features like SDKs and enhanced APIs and (2) hosted Optimism nodes.
_(1) Alchemy's enhanced features_
Alchemy's free private RPC endpoint provides a complimentary suite of proprietary tools.
These include a custom-built [Ethers.js SDK](https://www.alchemy.com/sdk/?a=818c11a8da)(which are supersets of the Ethers.js Provider and Wallet libraries) and [enhanced APIs](https://www.alchemy.com/enhanced-apis/?a=818c11a8da) such as NFT, Transfers, and Notify APIs.
https://www.alchemy.com/optimism/sdk
_(2) Alchemy's hosted Optimism nodes_
Alchemy hosts our public API because of its data accuracy, reliability, and scalability.
It counts companies like OpenSea, dYdX, and Facebook among its customers.
Its API takes only a few lines of codes to get up and running. Alchemy isn't just a node provider, but also a developer platform and API provider.
### Alchemy's Supported Networks
- Optimism Ethereum
- Optimism Goerli
[Sign up for a free Alchemy account here](https://www.alchemy.com/optimism).
## Ankr
### Description and Pricing
[Ankr](https://www.ankr.com/) provides a geo-distributed and decentralized (free) public and premium (Pay-as-you-go) [Optimism RPC](https://www.ankr.com/rpc/optimism/) comprised of many independent blockchain nodes running worldwide for low-latency and incredibly reliable connections.
Moreover, Ankr offers access to developer tooling on Optimism like SDKs and [Advanced APIs](https://www.ankr.com/advanced-api/) such as NFT, Token and Query API.
### Supported Networks
- Optimism Ethereum
- Optimism Goerli
## Blast
### Description and Pricing
[Blast](https://blastapi.io/) offers access to dedicated Optimism nodes with free data access up to 12M API calls per month and 25 req/s. Paid subscription tiers are available for all development needs.
On the platform, there are also [Public APIs](https://blastapi.io/public-api/optimism) available that can be added easily in Metamask.
### Supported Networks
- Optimism Ethereum
- Optimism Goerli
## BlockVision
[BlockVision](https://blockvision.org/) is a one-stop development platform and on-chain data retrieval portal for developers that boasts impressively low-latencies and high availability.
### Supported Networks
- Optimism Ethereum
## GetBlock
[GetBlock developer](https://getblock.io/en/nodes/optimism/) tools and valuable insights guarantee a simple and reliable API access to multiple blockchains.
### Supported Networks
- Optimism Ethereum
- Optimism Goerli
## Infura
### Description and Pricing
[Infura](https://infura.io) offers access to hosted Optimism nodes via addon.
This addon is currently free but Infura seems to intend to charge $200/month for this addon in the future.
### Supported Networks
- Optimism Ethereum
- Optimism Goerli
## NodeReal
### Description and pricing
[NodeReal](https://nodereal.io/) is a one-stop blockchain infrastructure and services provider, we provide scalable, reliable, and efficient blockchain solutions for everyone, aiming to support the massive adoption, growth, and long-term success of the Web3 ecosystem. You can connect to the Optimism MegaNode for free every month. Details are [here](https://nodereal.io/pricing)
[Sign up for your free account here](https://nodereal.io/meganode).
### Supported Networks
- Optimism Ethereum
## NOWNodes
### Description and pricing
[NOWNodes](https://nownodes.io/nodes/optimism) provide access to mainnet Optimism node. Shared and Dedicated nodes are Available. You can connect to the shared Optimism node for free for one month with 5,000 requests/per day or for €20 with 1,000,000 requests/per month.
The URL format is `https://optimism.nownodes.io/?API_key=<API key from NOWNodes`.
### Supported Networks
- Optimism Ethereum
## Pocket Network
### Description and pricing
[Pocket](https://www.portal.pokt.network/) offers access to a highly-available dedicated pool of Optimism nodes coordinated autonomously by the Pocket Network protocol. Through the Pocket Portal, developers may mint Optimism RPC endpoints with a generous free tier of 1M requests per day (per endpoint, max 2 per account).
### Supported Networks
- Optimism Ethereum
## QuickNode
### Description and Pricing
[QuickNode](https://www.quicknode.com/) offers access to hosted Optimism nodes for $9/month at its cheapest tier.
You can select addons, like "Archive Mode" or "Trace Mode" for an additional cost.
### Supported Networks
- Optimism Ethereum
- Optimism Goerli
## Don't see your company here?
We try to keep this list up to date as we find out about more infrastructure providers who maintain Optimism nodes.
If you're a node provider and you'd like to be included in this list, please message us in our [Discord](https://discord-gateway.optimism.io) or [make a PR](https://github.com/ethereum-optimism/community-hub/pulls).