Optimism 백서

Optimism

원문

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

ep title="Get the deposit transaction"> You can directly query for the L2 transaction that executed the deposit. ```js theme={null} console.log('Grabbing deposit txn...') const depositTransaction = await l2Client.getTransaction({ hash: depositHash }); console.log(depositTransaction); ``` </Step> </Steps> ## Trace a withdrawal You can use viem's functions to trace a withdrawal. <Steps> <Step title="Get the withdrawal status"> Like deposits, withdrawals can have multiple statuses depending on where they are in the process. ```js theme={null} console.log('Grabbing withdrawal status...') const withdrawalStatus = await l1Client.getTransactionReceipt({ hash: withdrawalHash }); console.log(withdrawalStatus); ``` </Step> <Step title="Get the withdrawal transaction receipt"> Retrieve the L1 transaction receipt for the withdrawal. ```js theme={null} console.log('Grabbing withdrawal receipt...') const withdrawalReceipt = await l1Client.getTransaction({ hash: withdrawalHash }); console.log(withdrawalReceipt); ``` </Step> <Step title="Get the withdrawal transaction"> Directly query for the L1 transaction that executed the withdrawal. ```js theme={null} console.log('Grabbing withdrawal txn...') const withdrawalTransaction = await l1Client.getTransaction({ hash: withdrawalHash }); console.log(withdrawalTransaction); ``` </Step> </Steps> ## Next steps * Check out the tutorial on [bridging ERC-20 tokens with the @eth-optimism/viem package](/app-developers/tutorials/bridging/cross-dom-bridge-erc20) to learn how to create deposits and withdrawals. # Triggering OP Stack transactions from Ethereum Source: https://docs.optimism.io/app-developers/tutorials/transactions/send-tx-from-eth Learn how to force transaction inclusion without the OP Stack Sequencer using Viem. OP Stack currently uses a single-Sequencer block production model. This means that there is only one Sequencer active on the network at any given time. Single-Sequencer models are simpler than their highly decentralized counterparts but they are also more vulnerable to potential downtime. Sequencer downtime must not be able to prevent users from transacting on the network. As a result, OP Stack includes a mechanism for "forcing" transactions to be included in the blockchain. This mechanism involves triggering a transaction on OP Stack by sending a transaction on Ethereum. In this tutorial you'll learn how to trigger a transaction on OP Stack from Ethereum using Viem. You'll use the OP Sepolia testnet, but the same logic will apply to OP Stack. ## Dependencies * [node](https://nodejs.org/en/) * [pnpm](https://pnpm.io/installation) ## Create a demo project You're going to use the library for this tutorial. Since is a [Node.js](https://nodejs.org/en/) library, you'll need to create a Node.js project to use it. <Steps> <Step title="Make a project folder"> ```bash theme={null} mkdir trigger-transaction cd trigger-transaction ``` </Step> <Step title="Initialize the project"> ```bash theme={null} pnpm init ``` </Step> <Step title="Install dependencies"> ```bash theme={null} pnpm add viem ``` </Step> </Steps> ## Get ETH on Sepolia and OP Sepolia This tutorial explains how to bridge tokens from Sepolia to OP Sepolia. You will need to get some ETH on both of these testnets. <TutorialFaucets /> ## Add a private key to your environment You need a private key in order to sign transactions. Set your private key as an environment variable with the `export` command. Make sure this private key corresponds to an address that has ETH on . <Info> Want to create a new wallet for this tutorial? If you have [`cast`](https://book.getfoundry.sh/getting-started/installation) installed you can run `cast wallet new` in your terminal to create a new wallet and get the private key. </Info> ```bash theme={null} export TUTORIAL_PRIVATE_KEY=0x... ``` ## Start the Node REPL You're going to use the Node REPL to interact with . To start the Node REPL, run the following command in your terminal: ```bash theme={null} node ``` This will bring up a Node REPL prompt that allows you to run JavaScript code. ## Import dependencies You need to import some dependencies into your Node REPL session. <Steps> <Step title="Import Viem"> ```js theme={null} const { createPublicClient, createWalletClient, http, parseEther, formatEther } = require('viem'); const { optimismSepolia, sepolia } = require('viem/chains'); const { privateKeyToAccount } = require('viem/accounts'); const { publicActionsL2, publicActionsL1, walletActionsL2, walletActionsL1, getL2TransactionHashes } = require ('viem/op-stack') ``` </Step> </Steps> ## Set session variables You'll need a few variables throughout this tutorial. Let's set those up now. <Steps> <Step title="Load your private key"> ```js theme={null} const privateKey = process.env.TUTORIAL_PRIVATE_KEY; const account = privateKeyToAccount(privateKey); ``` </Step> <Step title="Create the RPC providers and wallets"> ```js theme={null} const l1PublicClient = createPublicClient({ chain: sepolia, transport: http("https://rpc.ankr.com/eth_sepolia") }).extend(publicActionsL1()) const l2PublicClient = createPublicClient({ chain: optimismSepolia, transport: http("https://sepolia.optimism.io") }).extend(publicActionsL2()); const l1WalletClient = createWalletClient({ chain: sepolia, transport: http("https://rpc.ankr.com/eth_sepolia") }).extend(walletActionsL1()); ``` </Step> </Steps> ## Check your initial balance You'll be sending a small amount of ETH as part of this tutorial. Quickly check your balance on OP Sepolia so that you know how much you had at the start of the tutorial. ```js theme={null} const initialBalance = await l2PublicClient.getBalance({ address }); console.log(`Initial balance: ${formatEther(initialBalance)} ETH`); ``` ## Trigger the transaction Now you'll use the `OptimismPortal` contract to trigger a transaction on OP Sepolia by sending a transaction on Sepolia. <Steps> <Step title="Create the OptimismPortal object"> ```js theme={null} const optimismPortalAbi = [ { inputs: [ { internalType: 'uint256', name: '_gasLimit', type: 'uint256' }, { internalType: 'bytes', name: '_data', type: 'bytes' }, ], name: 'depositTransaction', outputs: [], stateMutability: 'payable', type: 'function', }, ]; ``` </Step> <Step title="Estimate the required gas"> When sending transactions via the `OptimismPortal` contract it's important to always include a gas buffer. This is because the `OptimismPortal` charges a variable amount of gas depending on the current demand for L2 transactions triggered via L1. If you do not include a gas buffer, your transactions may fail. ```js theme={null} const optimismPortalAddress = '0x5b47E1A08Ea6d985D6649300584e6722Ec4B1383'; const gasLimit = 100000n; const data = '0x'; const value = parseEther('0.000069420'); const gasEstimate = await l1PublicClient.estimateContractGas({ address: optimismPortalAddress, abi: optimismPortalAbi, functionName: 'depositTransaction', args: [gasLimit, data], value, account: account.address, }); ``` </Step> <Step title="Send the transaction"> Now you'll send the transaction. Note that you are including a buffer of 20% on top of the gas estimate. ```js theme={null} const { request } = await l1PublicClient.simulateContract({ account, address: optimismPortalAddress, abi: optimismPortalAbi, functionName: 'depositTransaction', args: [gasLimit, data], value, gas: gasEstimate * 120n / 100n, // 20% buffer }) const l1TxHash = await l1WalletClient.writeContract(request) console.log(`L1 transaction hash: ${l1TxHash}`) ``` </Step> <Step title="Wait for the L1 transaction"> First you'll need to wait for the L1 transaction to be mined. ```js theme={null} const l1TxHash = await l1WalletClient.writeContract(request) ``` </Step> <Step title="Wait for the L2 transaction"> Now you'll need to wait for the corresponding L2 transaction to be included in a block. This transaction is automatically created as a result of your L1 transaction. Here you'll determine the hash of the L2 transaction and then wait for that transaction to be included in the L2 blockchain. ```js theme={null} const [l2Hash] = getL2TransactionHashes(l1TxHash) console.log(`Corresponding L2 transaction hash: ${l2Hash}`); const l2Receipt = await l2PublicClient.waitForTransactionReceipt({ hash: l2Hash, }); console.log('L2 transaction confirmed:', l2Receipt); ``` </Step> </Steps> ## Check your updated balance You should have a little less ETH on OP Sepolia now. Check your balance to confirm. ```js theme={null} const finalBalance = await l2Wallet.getBalance() console.log(`Final balance: ${formatEther(finalBalance)} ETH`); ``` Make sure that the difference is equal to the amount you were expecting to send. ```js theme={null} const difference = initialBalance - finalBalance console.log(`Difference in balance: ${formatEther(difference)} ETH`); ``` ## Next steps You've successfully triggered a transaction on OP Sepolia by sending a transaction on Sepolia using Viem. Although this tutorial demonstrated the simple example of sending a basic ETH transfer from your L2 address via the OptimismPortal contract, you can use this same technique to trigger any transaction you want. You can trigger smart contracts, send ERC-20 tokens, and more. # Configure the batcher Source: https://docs.optimism.io/chain-operators/guides/configuration/batcher Learn how to configure the op-batcher for your chain, covering the batcher policy, cost tuning, multi-blob transactions, and sequencer throttling. The op-batcher posts L2 sequencer data to the L1, to make it available for verifiers. This guide walks through the policy constraints every OP Stack chain must respect and the settings with the biggest impact on cost and stability. For a catalogue of every CLI flag and environment variable, see the [batcher configuration reference](/chain-operators/reference/batcher-configuration). ## Batcher policy The batcher policy defines high-level constraints and responsibilities regarding how L2 data is posted to L1. Below are the [standard guidelines](/op-stack/protocol/superchain-registry#what-is-a-standard-chain) for configuring the batcher within the OP Stack. | Parameter | Description | Administrator | Requirement | Notes | | - | - | - | - | - | | Data Availability Type | Specifies whether the batcher uses **blobs**, **calldata**, or **auto** to post transaction data to L1. | Batch submitter address | Ethereum (Blobs or Calldata) | - Alternative data availability (Alt-DA) is not yet supported in the standard configuration.<br />- The sequencer can switch at will between blob transactions and calldata, with no restrictions, because both are fully secured by L1. | | Batch Submission Frequency | Determines how frequently the batcher submits aggregated transaction data to L1 (via the batcher transaction). | Batch submitter address | Must target **1,800 L1 blocks** (6 hours on Ethereum, assuming 12s L1 block time) or lower | - Batches must be posted before the sequencing window closes (commonly 12 hours by default).<br />- Leave a buffer for L1 network congestion and data size to ensure that each batch is fully committed in a timely manner. | * **Data Availability Types**: * **Calldata** is generally simpler but can be more expensive on mainnet Ethereum, depending on gas prices. * **Blobs** are typically lower cost when your chain has enough transaction volume to fill large chunks of data. * The `op-batcher` can toggle between these approaches by setting the `--data-availability-type=<blobs|calldata|auto>` flag or with the `OP_BATCHER_DATA_AVAILABILITY_TYPE` env variable. Setting this flag to `auto` will allow the batcher to automatically switch between `calldata` and `blobs` based on the current L1 gas price. * **Batch Submission Frequency** (`OP_BATCHER_MAX_CHANNEL_DURATION` and related flags): * Standard OP Chains frequently target a maximum channel duration between 1–6 hours. * Your chain should never exceed your L2's sequencing window (commonly 12 hours). * If targeting a longer submission window (e.g., 5 or 6 hours), be aware that the [safe head](https://specs.optimism.io/glossary.html#safe-l2-head) can stall up to that duration. Include these high-level "policy" requirements when you set up or modify your `op-batcher` configuration. See the [batcher configuration reference](/chain-operators/reference/batcher-configuration), which explains each CLI flag and environment variable in depth. ## Recommendations ### Set your `OP_BATCHER_MAX_CHANNEL_DURATION` <Info> The default value inside `op-batcher`, if not specified, is still `0`, which means channel duration tracking is disabled. For very low throughput chains, this would mean to fill channels until close to the sequencing window and post the channel to `L1 SUB_SAFETY_MARGIN` L1 blocks before the sequencing window expires. </Info> To minimize costs, we recommend setting your `OP_BATCHER_MAX_CHANNEL_DURATION` to target 5 hours, with a value of `1500` L1 blocks. When non-zero, this parameter is the max time (in L1 blocks, which are 12 seconds each) between which batches will be submitted to the L1. If you have this set to 5 for example, then your batcher will send a batch to the L1 every 5\*12=60 seconds. When using blobs, because 130kb blobs need to be purchased in full, if your chain doesn't generate at least \~130kb of data in those 60 seconds, then you'll be posting only partially full blobs and wasting storage. * We do not recommend setting any values higher than targeting 5 hours, as batches have to be submitted within the sequencing window which defaults to 12 hours for OP chains, otherwise your chain may experience a 12 hour long chain reorg. 5 hours is the longest length of time we recommend that still sits snugly within that 12 hour window to avoid affecting stability. * If your chain fills up full blobs of data before the `OP_BATCHER_MAX_CHANNEL_DURATION` elapses, a batch will be submitted anyways - (e.g. even if the OP Mainnet batcher sets an `OP_BATCHER_MAX_CHANNEL_DURATION` of 5 hours, it will still be submitting batches every few minutes) <Info> While setting an`OP_BATCHER_MAX_CHANNEL_DURATION` of `1500` results in the cheapest fees, it also means that your [safe head](https://specs.optimism.io/glossary.html#safe-l2-head) can stall for up to 5 hours. * This will negatively impact apps on your chain that rely on the safe head for operation. While many apps can likely operate simply by following the unsafe head, often Centralized Exchanges or third party bridges wait until transactions are marked safe before processing deposits and withdrawal. * Thus a larger gap between posting batches can result in significant delays in the operation of certain types of high-security applications. </Info> ### Configure your batcher to use multiple blobs <Info> When there's blob congestion, running with high blob counts can backfire, because you will have a harder time getting blobs included and then fees will bump, which always means a doubling of the priority fees. </Info> The `op-batcher` has the capabilities to send multiple blobs per single blob transaction. This is accomplished by the use of multi-frame channels, see the [specs](https://specs.optimism.io/protocol/derivation.html?utm_source=op-docs\&utm_medium=docs#frame-format) for more technical details on channels and frames. A minimal batcher configuration (with env vars) to enable 6-blob batcher transactions is: ``` - OP_BATCHER_BATCH_TYPE=1 # span batches, optional - OP_BATCHER_DATA_AVAILABILITY_TYPE=blobs - OP_BATCHER_TARGET_NUM_FRAMES=6 # 6 blobs per tx - OP_BATCHER_TXMGR_MIN_BASEFEE=2.0 # 2 gwei, might need to tweak, depending on gas market - OP_BATCHER_TXMGR_MIN_TIP_CAP=2.0 # 2 gwei, might need to tweak, depending on gas market - OP_BATCHER_RESUBMISSION_TIMEOUT=240s # wait 4 min before bumping fees ``` This enables blob transactions and sets the target number of frames to 6, which translates to 6 blobs per transaction. The minimum tip cap and base fee are also lifted to 2 gwei because it is uncertain how easy it will be to get 6-blob transactions included and slightly higher priority fees should help. The resubmission timeout is increased to a few minutes to give more time for inclusion before bumping the fees because current transaction pool implementations require a doubling of fees for blob transaction replacements. Multi-blob transactions are particularly useful for medium to high-throughput chains, where enough transaction volume exists to fill up 6 blobs in a reasonable amount of time. To determine what number of blobs is right for your chain, estimate the compressed batch data your chain produces per channel duration and divide by blob capacity (about 130 KB); [Size your channels](/use-cases/tune-batcher-costs#step-4-size-your-channels) in the Tune batcher costs guide walks through this estimate and the matching fee scalar configuration. Please also refer to the [Post batch data as blobs](/chain-operators/guides/features/blobs) guide for chain operators. ### Set your `--batch-type=1` to use span batches Span batches reduce the overhead of OP Stack chains, introduced in the Delta network upgrade. This is beneficial for sparse and low-throughput OP Stack chains. The overhead is reduced by representing a span of consecutive L2 blocks in a more efficient manner, while preserving the same consistency checks as regular batch data. For step-by-step instructions, including how to confirm Delta is active first, see [Enable span batches](/chain-operators/guides/features/enable-span-batches). ## Batcher sequencer throttling This feature is a batcher-driven sequencer-throttling control loop. This is to avoid sudden spikes in L1 DA-usage consuming too much available gas and causing a backlog in batcher transactions. The batcher can throttle the sequencer's data throughput instantly when it sees too much batcher data built up. There are two throttling knobs: 1. Transaction throttling, which skips individual transactions whose estimated compressed L1 DA usage goes over a certain threshold, and 2. Block throttling, which caps a block's estimated total L1 DA usage and leads to not including transactions during block building that would move the block's L1 DA usage past a certain threshold. **Feature requirements** * This feature is enabled by default and requires the sequencer's `op-reth` node to expose the `miner_setMaxDASize` RPC (enable the `miner` namespace, below). It can be disabled by setting `--throttle.unsafe-da-bytes-lower-threshold` (env var `OP_BATCHER_THROTTLE_UNSAFE_DA_BYTES_LOWER_THRESHOLD`) to 0, which is the only flag you need to change to turn throttling off. The sequencer's `op-reth` node has to be updated first, before updating the batcher, so that the required RPC is available at the time of the batcher restart. * It is required to upgrade to `op-conductor/v0.2.0` if you are using conductor's leader-aware rpc proxy feature. This conductor release includes support for proxying the `miner_setMaxDASize` RPC. **Configuration** <Info> Note that this feature requires the batcher to correctly follow the sequencer at all times, or it would set throttling parameters on a non-sequencer EL client. That means, active sequencer follow mode has to be enabled correctly by listing all the possible sequencers in the L2 rollup and EL endpoint flags. </Info> The batcher is configured for throttling by default with the parameters described below (and corresponding flags which allow the defaults to be overridden): * Backlog of pending block bytes beyond which the batcher will enable throttling on the sequencer via `--throttle.unsafe-da-bytes-lower/upper-threshold` (env var `OP_BATCHER_THROTTLE_UNSAFE_DA_BYTES_LOWER/UPPER_THRESHOLD`): 3\_200\_000 and 12\_800\_000 (batcher backlog
프로젝트로 돌아가기