Optimism 백서

Optimism

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 5쪽

# CrossL2Inbox (Pull Model): 1. A source contract emits an event to the event log. 2. A destination contract calls `validateMessage()` on the `CrossL2Inbox`. 3. The `CrossL2Inbox` verifies that the log exists on the source chain. 4. The destination contract receives verification and proceeds with its logic. ## Next steps * Learn how to [pass messages between blockchains](/app-developers/tutorials/interoperability/message-passing) # Testing apps for OP Stack chains Source: https://docs.optimism.io/app-developers/guides/testing-apps Learn best practices for testing apps on OP Stack chains. For the most part, running applications on OP Stack chains is identical to running them on Ethereum, so the testing is identical too. In this guide, you learn the best practices for OP Stack testing where there are differences. ## Unit tests and single layer integration tests The vast majority of tests do not involve any OP Stack-specific features. In those cases, while you *could* test everything on an OP Stack chain or a test network, that would normally be inefficient. Most Ethereum development stacks include features that make testing easier, which normal Ethereum clients, such as geth (and our modified version, `op-geth`) don't support. Therefore, it is a good idea to run the majority of tests, which do not rely on OP Stack-specific features, in the development stack. It is a lot faster. It is a best practice to design and run thorough tests across an OP test network, either in your [local multichain development environment](/app-developers/tools/development/supersim), our [devnets](/op-stack/introduction/op-stack), or on [the test network](/op-mainnet/network-information/connecting-to-op#op-sepolia), depending on your use case. Alternatively, with [Tenderly Virtual TestNets](https://docs.tenderly.co/virtual-testnets?mtm_campaign=ext-docs\&mtm_kwd=optimism)you can run tests with complete integration with existing protocols, access to unlimited faucets, continuous state sync, and access to development tools such as Debugger and Simulator UI. Running proper testing is key to identifying fringe cases where the equivalence between OP Stack chains and Ethereum breaks down (or where Ethereum mainnet itself and the development stack may be non-equivalent in a production environment). ## Multilayer integration tests Some apps need OP Stack-specific features that aren't available as part of the development stack. For example, if your decentralized application relies on [inter-domain communication](/app-developers/guides/bridging/messaging), the effort of developing a stub to let you debug it in a development stack is probably greater than the hassle of having the automated test go to [a local multichain development environment](/app-developers/tools/development/supersim) each time. ## Testing and Staging with Tenderly Tenderly [Virtual TestNets](https://docs.tenderly.co/virtual-testnets?mtm_campaign=ext-docs\&mtm_kwd=optimism) provide a powerful environment for testing OP Stack applications with mainnet-like conditions. They offer several advantages for testing OP Stack applications: * **Mainnet State Replication**: Virtual TestNets can sync with the latest OP Stack mainnet state, allowing you to test against real network conditions and interact with up-to-date protocols without spending real assets. * **Unlimited Faucet**: Access [unlimited test tokens](https://docs.tenderly.co/virtual-testnets/unlimited-faucet?mtm_campaign=ext-docs\&mtm_kwd=optimism) for both native currency and ERC-20 tokens, enabling comprehensive testing of complex DeFi interactions. * **Collaborative Testing**: Your entire team can access the same testing environment, making it easier to debug issues and validate fixes. * **CI/CD Integration**: Incorporate automated testing in your deployment pipeline using [Virtual TestNets' API](https://docs.tenderly.co/reference/api?mtm_campaign=ext-docs\&mtm_kwd=optimism#/operations/createAlert) and [GitHub Actions integration](https://docs.tenderly.co/virtual-testnets/ci-cd/github-actions-foundry?mtm_campaign=ext-docs\&mtm_kwd=optimism). * **Development tools**: Rely on the built-in [developer explorer](https://docs.tenderly.co/developer-explorer?mtm_campaign=ext-docs\&mtm_kwd=optimism) and debugging tools to analyze test transactions and contract interactions. ## Integration with other products In many cases a decentralized application requires the services of other contracts. For example, [Perpetual v. 2](https://docs.perp.com/docs/guides/integration-guide) cannot function without [Uniswap v. 3](https://uniswap.org/blog/uniswap-v3). * If that is the case, you can use [mainnet forking](/app-developers/reference/tools/supersim/fork). It works with OP Stack chains. * Create a Virtual TestNet to get access to third party contracts (e.g. Uniswap) and it's latest or historical state. * Alternatively, you can connect to our [test network](/op-mainnet/network-information/connecting-to-op#op-sepolia) if those contracts are also deployed there (in many cases they are). # Estimating transaction fees on OP Mainnet Source: https://docs.optimism.io/app-developers/guides/transactions/estimates Learn how to properly estimate the total cost of a transaction on OP Mainnet. <Info> Check out the guide on understanding [Transaction Fees on OP Mainnet](/op-stack/transactions/fees) for an in-depth explanation of how OP Mainnet transaction fees work. </Info> It's important to properly estimate the cost of a transaction on OP Mainnet before submitting it to the network. Here you'll learn how to estimate both of the components that make up the total cost of an OP Mainnet transaction, the [execution gas fee](/op-stack/transactions/fees#execution-gas-fee) and the [L1 data fee](/op-stack/transactions/fees#l1-data-fee). Make sure to read the guide on [Transaction Fees on OP Mainnet](/op-stack/transactions/fees) for a detailed look at how these fees work under the hood. ## Execution gas fee <Info> Estimating the execution gas fee on OP Mainnet is just like estimating the execution gas fee on Ethereum. Steps are provided here for reference and convenience, but you can use the same tooling that you'd use to estimate the execution gas fee for a transaction on Ethereum. </Info> A transaction's execution gas fee is exactly the same fee that you would pay for the same transaction on Ethereum. This fee is equal to the amount of gas used by the transaction multiplied by the gas price attached to the transaction. Refer to the guide on [Transaction Fees on OP Mainnet](/op-stack/transactions/fees#execution-gas-fee) for more information about the execution gas fee. When estimating the execution gas fee for a transaction, you'll need to know the gas limit and the [max fee per gas](https://ethereum.org/en/developers/docs/gas/#maxfee) for the transaction. Your transaction fee will then be the product of these two values. Refer to the guide on [Setting Transaction Gas Parameters on OP Mainnet](./parameters) to learn how to select an appropriate gas limit and max fee per gas for your transaction. <Steps> <Step title="Estimate the gas limit"> Using the same tooling that you'd use to estimate the gas limit for a transaction on Ethereum, estimate the gas limit for your transaction on OP Mainnet. OP Mainnet is designed to be [EVM equivalent](https://web.archive.org/web/20231127160757/https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306) so transactions will use the same amount of gas on OP Mainnet as they would on Ethereum. This means you can feed your transaction to the [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas) JSON-RPC method just like you would on Ethereum. Alternatively, use Tenderly's [`tenderly_estimateGas`](https://docs.tenderly.co/node/rpc-reference/optimism-mainnet/tenderly_estimateGas) for 100% accurate gas estimations. </Step> <Step title="Estimate the max fee per gas"> Like Ethereum, OP Mainnet uses an `EIP-1559` style fee market to determine the current base fee per gas. You can then additionally specify a priority fee (also known as a tip) to incentivize the Sequencer to include your transaction more quickly. Make sure to check out the guide on [Setting Transaction Gas Parameters on OP Mainnet](./parameters) to learn more about how to select an appropriate max fee per gas for your transaction. </Step> </Steps> ## L1 data fee <Info> The Viem library provides a convenient method for estimating the L1 data fee for a transaction. Check out the tutorial on [Estimating Transaction Costs on OP Mainnet](/app-developers/tutorials/transactions/sdk-estimate-costs) to learn how to use the Viem library to estimate the L1 data fee for your transaction. Keep reading if you'd like to learn how to estimate the L1 data fee without the Viem library. </Info> The L1 data fee is a fee paid to the Sequencer for the cost of publishing your transaction to Ethereum. This fee is paid in ETH and is calculated based on the size of your transaction in bytes and the current gas price on Ethereum. Refer to the guide on [Transaction Fees on OP Mainnet](/op-stack/transactions/fees#l1-data-fee) for more information about the L1 data fee. Unlike the execution gas fee, the L1 data fee is an **intrinsic** fee for every transaction. This fee is automatically charged based on the size of your transaction and the current Ethereum gas price. You currently cannot specify a custom L1 data fee for your transaction. <Info> The L1 data fee is paid based on the current Ethereum gas price as tracked within the [`GasPriceOracle`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/src/L2/GasPriceOracle.sol) smart contract. This gas price is updated automatically by the OP Mainnet protocol. Your transaction will be charged the Ethereum gas price seen by the protocol at the time that your transaction is included in an OP Mainnet block. This means that the L1 data fee for your transaction may differ from your estimated L1 data fee. </Info> <Steps> <Step title="Serialize your transaction"> The L1 data fee is calculated based on the size of your serialized transaction in bytes. Most Ethereum tooling will provide a method for serializing a transaction. For instance, Ethers.js provides the [`ethers.utils.serializeTransaction`](https://docs.ethers.org/v5/api/utils/transactions/#utils-serializeTransaction) method. </Step> <Step title="Estimate the L1 data fee"> Once you have serialized your transaction, you can estimate the L1 data fee by calling the [`getL1Fee`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/src/L2/GasPriceOracle.sol#L64-L71) method on the [`GasPriceOracle`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/src/L2/GasPriceOracle.sol) smart contract available on OP Mainnet and all OP Stack chains. This method takes the serialized transaction as input and returns the L1 data fee in wei using the formula described in the [Transaction Fees on OP Mainnet](/op-stack/transactions/fees#l1-data-fee) guide. <Info> Fee estimation is typically performed before the transaction is signed. As a result, the `getL1Fee` method assumes that your input is an **unsigned** Ethereum transaction. </Info> </Step> </Steps> ### Tooling Several tools are available to help you estimate the L1 Data Fee for your transaction. Selecting the right tool for your use case will depend on your specific needs. * [Viem](https://viem.sh/op-stack#getting-started-with-op-stack) provides first-class support for OP Stack chains, including OP Mainnet. You can use Viem to estimate gas costs and send cross-chain transactions (like transactions through the Standard Bridge system). It's strongly recommended to use Viem if you are able to do so as it will provide the best native support at the moment. ### Future proofing The L1 Data Fee formula is subject to change in the future, especially as the data availability landscape evolves. As a result, it's important to future-proof your transaction fee estimation code to ensure that it will continue to function properly as the L1 Data Fee formula changes. * Use existing [tooling](#tooling) to estimate the L1 Data Fee for your transaction if possible. This tooling will be updated to reflect any changes to the L1 Data Fee formula. This way you won't need to modify your code to account for any changes to the formula. * Use the `getL1Fee` method on the `GasPriceOracle` if you are unable to use existing tooling. The `getL1Fee` method will be updated to reflect any changes to the L1 Data Fee formula. It's strongly recommended that you do **not** implement the L1 Data Fee formula yourself. # Integrate Subblocks in your app Source: https://docs.optimism.io/app-developers/guides/transactions/integrating-subblocks Query pre-confirmed Subblocks state from your app using standard JSON-RPC methods with the pending tag, or through viem and ethers. A chain that streams [Subblocks](/op-stack/features/subblocks) publishes a partial block every 200 ms, so your app can show a transaction's result well before the block containing it is sealed. This guide shows how to read that pre-confirmed state over standard Ethereum JSON-RPC and from the viem and ethers libraries. Most apps need only a change of endpoint and the `pending` block tag. * In production, point your app to a subblocks-aware RPC endpoint from your provider of choice. If your provider doesn't support subblocks yet, let us know on [Discord](https://discord.gg/jPQhHTdemH) and we'll work with them to get it added. * To run your own subblocks-aware node, start `op-reth` with `--flashblocks-url=<websocket-url>` pointing at the chain's stream. The node then serves `pending` from the subblock state. OP Mainnet and OP Sepolia stream URLs are listed on the [network information page](/op-mainnet/network-information/connecting-to-op). <Info> This guide covers reading pre-confirmed state through an RPC endpoint, which is what most apps want. If you consume the WebSocket stream directly instead, four payload fields are zeroed and need handling — see the [Subblocks notice](/notices/subblocks). On a Lagoon chain the stream also carries the block's post-execution transaction outside the transaction list — see [the post-execution transaction](/op-stack/features/subblocks#the-post-execution-transaction). </Info> ## Supported RPC methods You read subblock state with the same Ethereum JSON-RPC calls you already use. The difference is using the "pending" tag in some of them to explicitly query the pre-confirmed state instead of the last finalized block. * **`eth_getBlockByNumber`**: Use the `pending` tag to retrieve the latest subblock snapshot. <Accordion title="Sample response"> ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x1234", "hash": "0x...", "transactions": [...] } } ``` </Accordion> * **`eth_call`**: Use the `pending` tag to execute calls against the most recent pre-confirmed state. <Accordion title="Sample request"> ```json theme={null} { "jsonrpc": "2.0", "method": "eth_call", "params": [{"to": "0x...", "data": "0x..."}, "pending"], "id": 1 } ``` </Accordion> * `eth_getBalance` / `eth_getTransactionCount`: Use the `pending` tag to fetch balances or transaction counts respectively as they evolve within the block window. <Accordion title="Sample response for `eth_getBalance`"> ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": "0x0234" } ``` </Accordion> <Accordion title="Sample response for `eth_getTransactionCount`"> ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": "0x1b" // 27 transactions } ``` </Accordion> Other methods, like `eth_getTransactionReceipt`, `eth_getTransactionByHash` or `eth_simulateV1`, return data from pre-confirmed transactions without requiring the `pending` tag. Consult the [Subblocks specification](https://specs.optimism.io/protocol/subblocks.html#json-rpc) for the supported methods and pending-state behavior. ## Libraries You need a subblocks‑aware RPC endpoint to use the following libraries: ### Viem ```ts theme={null} import { createPublicClient, createWalletClient, http, parseEther } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { opSepolia } from 'viem/chains'; import { publicActionsL2, walletActionsL2 } from 'viem/op-stack'; const account = privateKeyToAccount(`0x${process.env.PRIVATE_KEY}`); const walletClient = createWalletClient({ account, chain: opSepolia, transport: http("https://sepolia.optimism.io"), }).extend(walletActionsL2()); const publicClient = createPublicClient({ chain: opSepolia, transport: http("https://sepolia.optimism.io"), }).extend(publicActionsL2()); const submissionTime = new Date(); const hash = await walletClient.sendTransaction({ to: '0x...', value: parseEther('0.0001'), }); // Wait for pre-confirmation const receipt = await publicClient.waitForTransactionReceipt({ hash }); const confirmTime = new Date(); console.log('pre-confirmed in ms:', confirmTime.getTime() - submissionTime.getTime()); ``` ### Ethers ```ts theme={null} import { ethers } from 'ethers'; // Here, provider is a subblocks-enabled RPC provider const provider = new ethers.JsonRpcProvider("https://sepolia.optimism.io"); const wallet = new ethers.Wallet(process.env.PRIVATE_KEY as string, provider); const tx = { to: '0x...', value: ethers.parseEther('0.0001') }; const submission = new Date(); const sent = await wallet.sendTransaction(tx); await sent.wait(0); const confirmed = new Date(); // should represent the transaction (pre)confirmation faster than standard RPC console.log('Pre-confirmed in ms:', confirmed.getTime() - submission.getTime()); // validates the transaction hash returned by the pre-confirmed transaction above const receipt = await provider.getTransactionReceipt(sent.hash); const validated = new Date(); console.log('Receipt validated in ms:', validated.getTime() - submission.getTime()); console.log('Transaction receipt:', receipt); ``` ## Next steps * Understand how subblocks affect [gas usage and large transactions](/app-developers/guides/transactions/subblocks-and-gas-usage). * Learn how subblocks work in the [Subblocks explainer](/op-stack/features/subblocks). * Review the [Subblocks specification](https://specs.optimism.io/protocol/subblocks.html) for wire-format and JSON-RPC details. * Join our [community](https://discord.gg/jPQhHTdemH) to share best practices and get support! # Setting transaction gas parameters on OP Mainnet Source: https://docs.optimism.io/app-developers/guides/transactions/parameters Learn how to set gas parameters for transactions on OP Mainnet. OP Mainnet is designed to be [EVM equivalent](https://web.archive.org/web/20231127160757/https://medium.com/ethereum-optimism/introducing-evm-equivalence-5c2021deb306) which means that it is as compatible with Ethereum as possible, down to the client software used to run OP Mainnet nodes. Like Ethereum, OP Mainnet has an EIP-1559 style fee mechanism that dynamically adjusts a [base fee](https://ethereum.org/en/developers/docs/gas/#base-fee) that acts as the minimum fee that a transaction must pay to be included in a block. OP Mainnet also allows transactions to pay a [priority fee](https://ethereum.org/en/developers/docs/gas/#priority-fee) (also known as a tip) to incentivize the Sequencer to include transactions more quickly. Setting the base fee and the priority fee appropriately is important to ensure that your transactions are included in a timely manner. This guide will walk you through some best practices for determining the base fee and priority fee for your transactions. ## Selecting the base fee The base fee is the minimum fee that a transaction must pay to be included in a block. Transactions that specify a maximum fee per gas that is les
프로젝트로 돌아가기