bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 22쪽
" Hello$$
cast call --rpc-url $URL_CHAIN_B $GREETER_B_ADDRESS "greet()" | cast --to-ascii
```
</Accordion>
4. Install the Optimism Solidity libraries into the project.
```sh theme={null}
cd lib
npm install @eth-optimism/contracts-bedrock
cd ..
echo @eth-optimism/=lib/node_modules/@eth-optimism/ >> remappings.txt
```
5. Create `src/GreetingSender.sol`.
```solidity theme={null}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Predeploys } from "@eth-optimism/contracts-bedrock/src/libraries/Predeploys.sol";
import { IL2ToL2CrossDomainMessenger } from "@eth-optimism/contracts-bedrock/src/L2/IL2ToL2CrossDomainMessenger.sol";
import { Greeter } from "src/Greeter.sol";
contract GreetingSender {
IL2ToL2CrossDomainMessenger public immutable messenger =
IL2ToL2CrossDomainMessenger(Predeploys.L2_TO_L2_CROSS_DOMAIN_MESSENGER);
address immutable greeterAddress;
uint256 immutable greeterChainId;
constructor(address _greeterAddress, uint256 _greeterChainId) {
greeterAddress = _greeterAddress;
greeterChainId = _greeterChainId;
}
function setGreeting(string calldata greeting) public {
bytes memory message = abi.encodeCall(
Greeter.setGreeting,
(greeting)
);
messenger.sendMessage(greeterChainId, greeterAddress, message);
}
}
```
<Accordion title="Explanation">
```solidity theme={null}
function setGreeting(string calldata greeting) public {
bytes memory message = abi.encodeCall(
Greeter.setGreeting,
(greeting)
);
messenger.sendMessage(greeterChainId, greeterAddress, message);
}
```
This function encodes a call to `setGreeting` and sends it to a contract on another chain.
`abi.encodeCall(Greeter.setGreeting, (greeting))` constructs the [calldata](https://docs.soliditylang.org/en/latest/internals/layout_in_calldata.html) by encoding the function selector and parameters.
The encoded message is then passed to `messenger.sendMessage`, which forwards it to the destination contract (`greeterAddress`) on the specified chain (`greeterChainId`).
This ensures that `setGreeting` is executed remotely with the provided `greeting` value (as long as there is an executing message to relay it).
</Accordion>
6. Deploy `GreetingSender` to chain A.
```sh theme={null}
CHAIN_ID_B=`cast chain-id --rpc-url $URL_CHAIN_B`
GREETER_A_ADDRESS=`forge create --rpc-url $URL_CHAIN_A --private-key $PRIVATE_KEY --broadcast GreetingSender --constructor-args $GREETER_B_ADDRESS $CHAIN_ID_B | awk '/Deployed to:/ {print $3}'`
```
</Step>
<Step title="Send a message">
Send a greeting from chain A to chain B.
```sh theme={null}
cast call --rpc-url $URL_CHAIN_B $GREETER_B_ADDRESS "greet()" | cast --to-ascii
cast send --private-key $PRIVATE_KEY --rpc-url $URL_CHAIN_A $GREETER_A_ADDRESS "setGreeting(string)" "Hello from chain A"
sleep 4
cast call --rpc-url $URL_CHAIN_B $GREETER_B_ADDRESS "greet()" | cast --to-ascii
```
The `sleep` call is because it can take up to two seconds until the transaction is included in chain A, and then up to two seconds until the relay transaction is included in chain B.
</Step>
</Steps>
## Sender information
Run this command to view the events to see who called `setGreeting`.
```sh theme={null}
cast logs --rpc-url $URL_CHAIN_B 'SetGreeting(address,string)'
```
The sender information is stored in the second event topic.
However, for cross-chain messages, this value corresponds to the local `L2ToL2CrossDomainMessenger` contract address (`4200000000000000000000000000000000000023`), making it ineffective for identifying the original sender.
In this section we change `Greeter.sol` to emit a separate event in it receives a cross domain message, with the sender's identity (address and chain ID).
<Steps>
<Step title="Modify the Greeter contract">
1. Modify `src/Greeter.sol` to this code.
```solidity theme={null}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Predeploys } from "@eth-optimism/contracts-bedrock/src/libraries/Predeploys.sol";
interface IL2ToL2CrossDomainMessenger {
function crossDomainMessageContext() external view returns (address sender_, uint256 source_);
}
contract Greeter {
IL2ToL2CrossDomainMessenger public immutable messenger =
IL2ToL2CrossDomainMessenger(Predeploys.L2_TO_L2_CROSS_DOMAIN_MESSENGER);
string greeting;
event SetGreeting(
address indexed sender, // msg.sender
string greeting
);
event CrossDomainSetGreeting(
address indexed sender, // Sender on the other side
uint256 indexed chainId, // ChainID of the other side
string greeting
);
function greet() public view returns (string memory) {
return greeting;
}
function setGreeting(string memory _greeting) public {
greeting = _greeting;
emit SetGreeting(msg.sender, _greeting);
if (msg.sender == Predeploys.L2_TO_L2_CROSS_DOMAIN_MESSENGER) {
(address sender, uint256 chainId) =
messenger.crossDomainMessageContext();
emit CrossDomainSetGreeting(sender, chainId, _greeting);
}
}
}
```
<Accordion title="Explanation">
```solidity theme={null}
interface IL2ToL2CrossDomainMessenger {
function crossDomainMessageContext() external view returns (address sender_, uint256 source_);
}
```
This definition isn't part of the [npmjs package](https://www.npmjs.com/package/@eth-optimism/contracts-bedrock) at writing, so we just add it here.
```solidity theme={null}
if (msg.sender == Predeploys.L2_TO_L2_CROSS_DOMAIN_MESSENGER) {
(address sender, uint256 chainId) =
messenger.crossDomainMessageContext();
emit CrossDomainSetGreeting(sender, chainId, _greeting);
}
```
If we see that we got a message from `L2ToL2CrossDomainMessenger`, we call [`L2ToL2CrossDomainMessenger.crossDomainMessageContext`](https://github.com/ethereum-optimism/optimism/blob/develop/packages/contracts-bedrock/src/L2/L2ToL2CrossDomainMessenger.sol#L118-L126).
</Accordion>
2. Redeploy the contracts.
Because the address of `Greeter` is immutable in `GreetingSender`, we need to redeploy both contracts.
```sh theme={null}
GREETER_B_ADDRESS=`forge create --rpc-url $URL_CHAIN_B --private-key $PRIVATE_KEY Greeter --broadcast | awk '/Deployed to:/ {print $3}'`
GREETER_A_ADDRESS=`forge create --rpc-url $URL_CHAIN_A --private-key $PRIVATE_KEY --broadcast GreetingSender --constructor-args $GREETER_B_ADDRESS $CHAIN_ID_B | awk '/Deployed to:/ {print $3}'`
```
</Step>
<Step title="Verify you can see cross chain sender information">
1. Set the greeting through `GreetingSender`.
```sh theme={null}
cast call --rpc-url $URL_CHAIN_B $GREETER_B_ADDRESS "greet()" | cast --to-ascii
cast send --private-key $PRIVATE_KEY --rpc-url $URL_CHAIN_A $GREETER_A_ADDRESS "setGreeting(string)" "Hello from chain A, with a CrossDomainSetGreeting event"
sleep 4
cast call --rpc-url $URL_CHAIN_B $GREETER_B_ADDRESS "greet()" | cast --to-ascii
```
2. Read the log entries.
```sh theme={null}
cast logs --rpc-url $URL_CHAIN_B 'CrossDomainSetGreeting(address,uint256,string)'
echo $GREETER_A_ADDRESS
echo 0x385=`echo 0x385 | cast --to-dec`
echo 0x190a85c0=`echo 0x190a85c0 | cast --to-dec`
```
See that the second topic (the first indexed log parameter) is the same as `$GREETER_A_ADDRESS`.
The third topic can be either `0x385=901`, which is the chain ID for supersim chain A, or `0x190a85c0=420120000`, which is the chain ID for devnet alpha 0.
</Step>
</Steps>
## Next steps
* Review the [OP Stack Interop Explainer](/op-stack/interop/explainer) for answers to common questions about interoperability.
* Read the [Message Passing Explainer](/app-developers/guides/interoperability/message-passing) to understand what happens "under the hood".
* Write a revolutionary app that uses multiple blockchains within the OP Stack ecosystem.
# Estimating transaction costs on OP Stack
Source: https://docs.optimism.io/app-developers/tutorials/transactions/sdk-estimate-costs
Learn how to use viem to estimate the cost of a transaction on OP Stack.
In this tutorial, you'll learn how to use [viem](https://viem.sh/op-stack/) to estimate the cost of a transaction on OP Mainnet.
You'll learn how to estimate the [execution gas fee](/app-developers/transactions/fees#execution-gas-fee) and the [L1 data fee](/app-developers/transactions/fees#l1-data-fee) independently.
You'll also learn how to estimate the total cost of the transaction all at once.
<Info>
Check out the full explainer on [OP Stack transaction fees](/app-developers/guides/transactions/fees) for more information on how OP Mainnet charges fees under the hood.
</Info>
## Supported networks
Viem supports any of the [OP Stack networks](/op-mainnet/network-information/connecting-to-op).
The OP Stack networks are included in Viem by default.
If you want to use a network that isn't included by default, you can add it to Viem's chain configurations.
## 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 op-est-cost-tutorial
cd op-est-cost-tutorial
```
</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 OP Sepolia
This tutorial explains how to estimate transaction costs on OP Sepolia.
You will need to get some ETH on OP Sepolia in order to run the code in this tutorial.
<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.
## Set session variables
You'll need a few variables throughout this tutorial.
Let's set those up now.
<Steps>
<Step title="Import viem and other necessary modules">
```js theme={null}
const { createPublicClient, createWalletClient, http, parseEther, parseGwei, formatEther } = require('viem');
const { privateKeyToAccount } = require('viem/accounts');
const { optimismSepolia } = require('viem/chains');
const { publicActionsL2, walletActionsL2 } = require('viem/op-stack');
```
</Step>
<Step title="Set up the account">
```js theme={null}
const privateKey = process.env.TUTORIAL_PRIVATE_KEY
const account = privateKeyToAccount(privateKey)
```
</Step>
<Step title="Create the public client">
```js theme={null}
const publicClient = createPublicClient({
chain: optimismSepolia,
transport: http("https://sepolia.optimism.io"),
}).extend(publicActionsL2())
```
</Step>
<Step title="Create the wallet client">
```js theme={null}
const walletClientL2 = createWalletClient({
chain: optimismSepolia,
transport: http("https://sepolia.optimism.io"),
}).extend(walletActionsL2())
```
</Step>
</Steps>
## Estimate transaction costs
You're now going to use the Viem to estimate the cost of a transaction on OP Mainnet.
Here you'll estimate the cost of a simple transaction that sends a small amount of ETH from your address to the address `0x1000000000000000000000000000000000000000`.
<Steps>
<Step title="Create the unsigned transaction">
Viem makes it easy to create unsigned transactions so you can estimate the cost of a transaction before asking a user to sign it.
Here you'll create an unsigned transaction that sends a small amount of ETH from your address to the address `0x1000000000000000000000000000000000000000`.
```js theme={null}
const transaction = {
account,
to: '0x1000000000000000000000000000000000000000',
value: parseEther('0.00069420'),
gasPrice: await publicClient.getGasPrice()
}
```
</Step>
<Step title="Estimate the total cost">
With Viem you can estimate the total cost of a transaction using the [estimateTotalFee](https://viem.sh/op-stack/actions/estimateTotalFee) method.
```js theme={null}
const totalEstimate = await publicClient.estimateTotalFee(transaction)
console.log(`Estimated Total Cost: ${formatEther(totalEstimate)} ETH`)
```
</Step>
<Step title="Send the transaction">
Now that you've estimated the total cost of the transaction, go ahead and send it to the network.
This will make it possible to see the actual cost of the transaction to compare to your estimate.
```js theme={null}
const txHash = await walletClientL2.sendTransaction(transaction)
console.log(`Transaction Hash: ${txHash}`)
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })
console.log('receipt', receipt);
```
</Step>
<Step title="Check the actual execution gas fee">
Once you get back the transaction receipt, check the actual execution gas fee.
You can do so by accessing the `gasUsed` and `effectiveGasPrice` from the transaction receipt.
You can then multiply these values to get the actual L2 cost of the transaction
```js theme={null}
const l2CostActual = receipt.gasUsed * receipt.effectiveGasPrice
console.log(`Actual Execution Gas Fee: ${formatEther(l2CostActual)} ETH`)
```
</Step>
<Step title="Check the actual L1 data fee">
You can also check the actual L1 data fee.
```js theme={null}
const l1CostActual = receipt.l1Fee
console.log(`Actual L1 Data Fee: ${formatEther(l1CostActual)} ETH`)
```
</Step>
<Step title="Check the actual total cost">
Sum these two together to get the actual total cost of the transaction.
```js theme={null}
const totalActual = l2CostActual + l1CostActual
console.log(`Actual Total Cost: ${formatEther(totalActual)} ETH`)
```
</Step>
<Step title="Check the difference">
Finally, check the difference between the estimated total cost and the actual total cost.
This will give you a sense of how accurate your estimate was.
Estimates will never be entirely accurate, but they should be close!
```js theme={null}
const difference = totalEstimate >= totalActual ? totalEstimate - totalActual : totalActual - totalEstimate
console.log(`Estimation Difference: ${formatEther(difference)} ETH`)
```
</Step>
</Steps>
<Info>
Estimates will never be entirely accurate due to network conditions and gas price fluctuation, but they should be close to the actual costs.
</Info>
## Next steps
* Always estimate before sending: Estimating costs before sending a transaction helps prevent unexpected fees and failed transactions.
* Account for gas price volatility: Gas prices can change rapidly. Consider adding a buffer to your estimates or implementing a gas price oracle for more accurate pricing.
* Optimize transaction data: Minimize the amount of data in your transactions to reduce L1 data fees.
* Monitor network conditions: Keep an eye on network congestion and adjust your estimates accordingly.
* Use appropriate gas limits: Setting too low a gas limit can cause transactions to fail, while setting it too high can result in unnecessary costs.
* Implement retry mechanisms: If a transaction fails due to underestimated gas, implement a retry mechanism with adjusted gas parameters.
# Tracing deposits and withdrawals
Source: https://docs.optimism.io/app-developers/tutorials/transactions/sdk-trace-txns
Learn how to use the viem library to trace deposits and withdrawals between L1 and L2.
In this tutorial, you'll learn how to use the [viem](https://viem.sh) library to trace a [Standard Bridge](/app-developers/guides/bridging/standard-bridge) deposit or withdrawal between L1 and L2.
You'll specifically learn how to determine the status of a deposit or withdrawal and how to retrieve the transaction receipt for the executed transaction on L1 (for withdrawals) or L2 (for deposits).
## 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 trace-trx
cd trace-trx
```
</Step>
<Step title="Initialize the project">
```bash theme={null}
pnpm init
```
</Step>
<Step title="Install dependencies">
```bash theme={null}
pnpm add viem
```
</Step>
</Steps>
## Add RPC URLs to your environment
You'll be using the `getTransactionReceipt` function from the viem library during this tutorial. This function uses event queries to retrieve the receipt for a deposit or withdrawal.
Since this function uses large event queries, you'll need to use an RPC provider like [Alchemy](https://alchemy.com) that supports indexed event queries.
Grab an L1 and L2 RPC URL for Sepolia and OP Sepolia, respectively.
```bash theme={null}
export L1_RPC_URL="https://YOUR_L1_ SEPOLIA_RPC_URL_HERE"
export L2_RPC_URL="https://YOUR_L2_OP_SEPOLIA_RPC_URL_HERE"
```
## 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.
### Import viem
```js theme={null}
const { createPublicClient, http } = require('viem');
const { optimismSepolia, sepolia } = require('viem/chains');
```
## Set session variables
You'll need a few variables throughout this tutorial. Let's set those up now.
<Steps>
<Step title="Import RPC URLs">
```js theme={null}
const l1RpcUrl = process.env.L1_RPC_URL;
const l2RpcUrl = process.env.L2_RPC_URL;
```
</Step>
<Step title="Set the deposit to trace">
You'll be tracing a specific deposit in this tutorial. Deposit tracing is generally based on the transaction hash of the transaction that triggered the deposit. You can replace this transaction hash with your own if you'd like.
```js theme={null}
const depositHash = '0x5896d6e4a47b465e0d925723bab838c62ef53468139a5e9ba501efd70f90cccb'
```
</Step>
<Step title="Set the withdrawal to trace">
You'll also be tracing a specific withdrawal in this tutorial. Like with deposits, withdrawal tracing is generally based on the transaction hash of the transaction that triggered the withdrawal. You can replace this transaction hash with your own if you'd like.
```js theme={null}
const withdrawalHash = '0x18b8b4022b8d9e380fd89417a2e897adadf31e4f41ca17442870bf89ad024f42'
```
</Step>
<Step title="Create the RPC providers">
```js theme={null}
const l1Client = createPublicClient({
chain: sepolia,
transport: http(l1RpcUrl),
});
const l2Client = createPublicClient({
chain: optimismSepolia,
transport: http(l2RpcUrl),
});
```
</Step>
</Steps>
## Trace a Deposit
You can use viem to trace a deposit.
<Steps>
<Step title="Get the deposit status">
You can query for the deposit status using the transaction hash of the deposit.
```js theme={null}
console.log('Grabbing deposit status...')
const depositStatus = await l2Client.getTransactionReceipt({ hash: depositHash });
console.log(depositStatus);
```
</Step>
<Step title="Get the deposit transaction receipt">
Retrieve the transaction receipt for the deposit using the viem client.
```js theme={null}
console.log('Grabbing deposit receipt...')
const depositReceipt = await l2Client.getTransaction({ hash: depositHash });
console.log(depositReceipt);
```
</Step>
<St프로젝트로 돌아가기