bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 17쪽
F771bF30b1B98dB8B2c5#writeContract) and click the "Connect to Web3" button.
</Step>
<Step title="Send your greeting">
Put a greeting into the field next to the "sendGreeting" function and click the "Write" button.
You can use any greeting you'd like.
</Step>
<Step title="Wait a few minutes">
It will take a few minutes for your message to reach L2.
Feel free to take a quick break while you wait.
<Info>
You can use viem to programmatically check the status of any message between L1 and L2.
Later on in this tutorial you'll learn how to use viem and the `waitToProve` function to wait for various message statuses.
This same function can be used to wait for a message to be relayed from L1 to L2.
</Info>
</Step>
<Step title="Check the L2 Greeter">
After a few minutes, you should see the greeting on the L2 `Greeter` contract change to the greeting you set.
Open up the [L2 `Greeter` contract on OP Sepolia Etherscan](https://testnet-explorer.optimism.io/address/0x5DE8a2957eddb140567fF90ba5d57bc9769f3055#readContract) and click the "Read Contract" button.
Paste your address into the field next to the "greeting" function and click the "Query" button.
You should see the message you sent from L1.
</Step>
<Info>
Haven't seen your message yet?
You might need to wait a little longer.
L2 transactions triggered on L1 are typically processed within one minute but can occasionally be slightly delayed.
</Info>
</Steps>
## Interact with the L2 Greeter
Now you're going to use the L2 `Greeter` contract to set the greeting on the L1 `Greeter` contract.
You'll send a transaction directly to the L2 `Greeter` contract which will ask the `L2CrossDomainMessenger` to send a message to the L1 `Greeter` contract.
Unlike the previous step, you'll need to relay the message from L2 to L1 yourself.
You'll do this by sending two transactions on Sepolia, one proving transaction and one relaying transaction.
<Steps>
<Step title="Connect to Etherscan">
Just like before, sending a message to the L1 `Greeter` contract via the L2 `Greeter` contract requires that you call the `sendGreeting` function.
Open up the [L2 `Greeter` contract on OP Sepolia Etherscan](https://testnet-explorer.optimism.io/address/0x5DE8a2957eddb140567fF90ba5d57bc9769f3055#writeContract) and click the "Connect to Web3" button.
</Step>
<Step title="Send your greeting">
Put a greeting into the field next to the "sendGreeting" function and click the "Write" button.
You can use any greeting you'd like.
<Info>
Copy the transaction hash from the transaction you just sent.
You'll need this for the next few steps.
Feel free to keep this tab open so you can easily copy the transaction hash later.
</Info>
</Step>
<Step title="Create a demo project">
You're going to use viem to prove and relay your message to L1.
```bash theme={null}
mkdir cross-dom
cd cross-dom
pnpm init
pnpm add viem@^2.51.0
```
</Step>
<Step title="Add environment variables">
Set your private key and transaction hash as environment variables.
```bash theme={null}
export TUTORIAL_PRIVATE_KEY=0x...
export TUTORIAL_TRANSACTION_HASH=0x...
```
</Step>
<Step title="Run the script in a Node REPL">
Start a Node.js REPL with `node` and paste the following script to monitor, prove, and finalize the cross-domain message:
```js theme={null}
const { createPublicClient, http, createWalletClient } = require('viem');
const { optimismSepolia, sepolia } = require('viem/chains');
const { publicActionsL1, publicActionsL2, walletActionsL1, walletActionsL2, getWithdrawals, isSuperGameType } = require('viem/op-stack');
const { privateKeyToAccount } = require('viem/accounts');
const l1Provider = createPublicClient({
chain: sepolia,
transport: http('https://eth-sepolia.g.alchemy.com/v2/your-key')
}).extend(publicActionsL1());
const l2Provider = createPublicClient({
chain: optimismSepolia,
transport: http('https://opt-sepolia.g.alchemy.com/v2/your-key')
}).extend(publicActionsL2());
const account = privateKeyToAccount(process.env.TUTORIAL_PRIVATE_KEY);
const l1Wallet = createWalletClient({
account,
chain: sepolia,
transport: http('https://eth-sepolia.g.alchemy.com/v2/your-key')
}).extend(walletActionsL1());
const l2Wallet = createWalletClient({
account,
chain: optimismSepolia,
transport: http('https://opt-sepolia.g.alchemy.com/v2/your-key')
}).extend(walletActionsL2());
const receipt = await l2Provider.getTransactionReceipt({
hash: process.env.TUTORIAL_TRANSACTION_HASH
});
const withdrawalBlock = await l2Provider.getBlock({
blockNumber: receipt.blockNumber
});
const respectedGameType = await l1Provider.readContract({
abi: [{
inputs: [],
name: 'respectedGameType',
outputs: [{ type: 'uint32' }],
stateMutability: 'view',
type: 'function'
}],
address: l2Provider.chain.contracts.portal[l1Provider.chain.id].address,
functionName: 'respectedGameType'
});
const proveContext = isSuperGameType(Number(respectedGameType))
? { l2Timestamp: withdrawalBlock.timestamp }
: {};
console.log('Waiting for message to be provable...');
await l1Provider.getWithdrawalStatus({
...proveContext,
receipt,
targetChain: l2Provider.chain
});
console.log('Proving message...');
const { game, withdrawal } = await l1Provider.waitToProve({
...proveContext,
receipt,
targetChain: l2Provider.chain
});
const proveArgs = await l2Provider.buildProveWithdrawal({
account,
game,
withdrawal
});
await l1Wallet.proveWithdrawal(proveArgs);
console.log('Waiting for message to be relayable...');
await l1Provider.waitToFinalize({
targetChain: l2Provider.chain,
withdrawalHash: withdrawal.withdrawalHash
});
console.log('Relaying message...');
await l1Wallet.finalizeWithdrawal({
targetChain: l2Wallet.chain,
withdrawal
});
console.log('Message relayed!');
```
</Step>
<Step title="Verify the L1 greeting">
After finalization, open the [L1 `Greeter` contract on Sepolia Etherscan](https://sepolia.etherscan.io/address/0x31A6Dd971306bb72f2ffF771bF30b1B98dB8B2c5#readContract).
Confirm that the greeting has been updated to the message you sent from L2.
</Step>
</Steps>
## How it works
Congratulations! You've successfully sent a message from L1 to L2 and from L2 to L1.
This section explains how the `Greeter` contracts work so you can follow the same pattern to deploy your own contracts.
Luckily, both `Greeter` contracts are exactly the same so it's easy to see how everything comes together.
### The Messenger variable
The `Greeter` contract has a `MESSENGER` variable that keeps track of the `CrossDomainMessenger` contract on the current chain.
Check out the [Contract Addresses page](/op-mainnet/network-information/op-addresses) to see the addresses of the `CrossDomainMessenger` contracts on whatever network you'll be using.
```solidity theme={null}
address public immutable MESSENGER;
```
### The other Greeter variable
The `Greeter` contract also has an `OTHER_GREETER` variable that keeps track of the `Greeter` contract on the other chain.
On L1, this variable is set to the address of the L2 `Greeter` contract, and vice-versa.
```solidity theme={null}
address public immutable OTHER_GREETER;
```
### The Greetings mapping
The `Greeter` contract keeps track of the different greetings that users have sent inside a `greetings` mapping.
By using a mapping, this contract can keep track of greetings from different users at the same time.
```solidity theme={null}
mapping(address => string) public greetings;
```
### The Constructor
The `Greeter` has a simple constructor that sets the `MESSENGER` and `OTHER_GREETER` variables.
```solidity theme={null}
constructor(address messenger, address otherGreeter) {
MESSENGER = messenger;
OTHER_GREETER = otherGreeter;
}
```
### The sendGreeting function
The `sendGreeting` function is the most important function in the `Greeter` contract.
This is what you called earlier to send messages in both directions.
All this function does is use the `sendMessage` function found within the `CrossDomainMessenger` contract to send a message to the `Greeter` contract on the other chain.
```solidity theme={null}
function sendGreeting(string calldata newGreeting) external payable {
ICrossDomainMessenger(MESSENGER).sendMessage(
OTHER_GREETER,
abi.encodeWithSelector(Greeter.setGreeting.selector, msg.sender, newGreeting),
100_000
);
}
```
### The setGreeting function
The `setGreeting` function is the function that actually sets the greeting.
This function is called by the `CrossDomainMessenger` contract on the other chain.
It checks explicitly that the function can only be called by the `CrossDomainMessenger` contract.
It also checks that the `CrossChainMessenger` says that the message came from the `Greeter` contract on the other chain.
Finally, it sets the greeting in the `greetings` mapping.
```solidity theme={null}
function setGreeting(address sender, string calldata newGreeting) external {
require(msg.sender == MESSENGER, "Only messenger");
require(
ICrossDomainMessenger(MESSENGER).xDomainMessageSender() == OTHER_GREETER,
"Only remote greeter"
);
greetings[sender] = newGreeting;
}
```
<Info>
The two `require` statements in this function are important.
Without them, anyone could call this function and set the greeting to whatever they want.
You can follow a similar pattern in your own smart contracts.
</Info>
## Conclusion
You just learned how you can write Solidity contracts on Sepolia and OP Sepolia that can talk to each other.
You can follow the same pattern to write contracts that can talk to each other on Ethereum and OP Stack.
```solidity theme={null}
interface ICrossDomainMessenger {
function sendMessage(address target, bytes calldata message, uint32 gasLimit) external;
function xDomainMessageSender() external view returns (address);
}
```
This sort of cross-chain communication is useful for a variety of reasons.
For example, the [Standard Bridge](/app-developers/guides/bridging/standard-bridge) contracts use this same system to bridge ETH and ERC-20 tokens between Ethereum and OP Stack.
One cool way to take advantage of cross-chain communication is to do most of your heavy lifting on OP Stack and then send a message to Ethereum only when you have important results to share.
This way you can take advantage of the low gas costs on OP Stack while still being able to use Ethereum when you need it.
# Deposit transactions
Source: https://docs.optimism.io/app-developers/tutorials/bridging/deposit-transactions
Learn about using deposit transactions with `supersim`.
Supersim supports [deposit transactions](/op-stack/bridging/deposit-flow). It uses a very lightweight solution without the `op-node` derivation pipeline by listening directly to the `TransactionDeposited` events on the `OptimismPortal` contract and simply forwarding the transaction to the applicable L2.
The execution engine used with Supersim must support the Optimism [deposit transaction type](https://specs.optimism.io/protocol/deposits.html#the-deposited-transaction-type).
## `OptimismPortal`
When starting Supersim, the L1 contracts for each L2 chain are emitted as output to the console. The `L1CrossDomainMessenger`, `L1StandardBridge`, and `OptimismPortal` can be used to initiate deposits in the same manner as one would on a production network like OP Mainnet or Base.
```bash theme={null}
Chain Configuration
-----------------------
L1: Name: Local ChainID: 900 RPC: http://127.0.0.1:8545 LogPath: ...
L2: Predeploy Contracts Spec ( https://specs.optimism.io/protocol/predeploys.html )
* Name: OPChainA ChainID: 901 RPC: http://127.0.0.1:9545 LogPath: ...
L1 Contracts:
- OptimismPortal: 0x37a418800d0c812A9dE83Bc80e993A6b76511B57
- L1CrossDomainMessenger: 0xcd712b03bc6424BF45cE6C29Fc90FFDece228F6E
- L1StandardBridge: 0x8d515eb0e5F293B16B6bBCA8275c060bAe0056B0
...
```
If running Supersim in fork mode, the production contracts will be used for each of the forked networks.
```bash theme={null}
Chain Configuration
-----------------------
L1: Name: mainnet ChainID: 1 RPC: http://127.0.0.1:8545 LogPath: ...
L2: Predeploy Contracts Spec ( https://specs.optimism.io/protocol/predeploys.html )
* Name: op ChainID: 10 RPC: http://127.0.0.1:9545 LogPath: ...
L1 Contracts:
- OptimismPortal: 0xbEb5Fc579115071764c7423A4f12eDde41f106Ed
- L1CrossDomainMessenger: 0x25ace71c97B33Cc4729CF772ae268934F7ab5fA1
- L1StandardBridge: 0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1
* Name: mode ChainID: 34443 RPC: http://127.0.0.1:9546 LogPath: ...
L1 Contracts:
- OptimismPortal: 0x8B34b14c7c7123459Cf3076b8Cb929BE097d0C07
- L1CrossDomainMessenger: 0x95bDCA6c8EdEB69C98Bd5bd17660BaCef1298A6f
- L1StandardBridge: 0x735aDBbE72226BD52e818E7181953f42E3b0FF21
...
```
## Sample Deposit Flow
We'll run through a sample deposit directly with the `OptimismPortal` using cast.
<Steps>
<Step title="Run Supersim">
```bash theme={null}
supersim
```
</Step>
<Step title="Observe OptimismPortal Contract Address">
```bash theme={null}
...
* Name: OPChainA ChainID: 901 ...
L1 Contracts:
- OptimismPortal: 0x37a418800d0c812A9dE83Bc80e993A6b76511B57
...
```
</Step>
<Step title="Send Deposit Transaction On L1">
We'll be using the first pre-funded account to send this deposit of 1 ether
```bash theme={null}
cast send 0x37a418800d0c812A9dE83Bc80e993A6b76511B57 --value 1ether --rpc-url http://localhost:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
```
</Step>
<Step title="Verify With Supersim Logs">
```bash theme={null}
INFO [11-28|13:56:06.756] OptimismPortal#depositTransaction chain.id=901 l2TxHash=0x592d6e13016751332115df1fce59904176bfe447854196ed1b97ee00f14be469
```
</Step>
</Steps>
## Next steps
* See the [transaction guides](/app-developers/guides/transactions/estimates) for more detailed information.
* Questions about Interop? Check out collection of [interop guides](/op-stack/interop/explainer) or check out this [OP Stack interop design video walk-thru](https://www.youtube.com/watch?v=FKc5RgjtGes).
* For more info about how OP Stack interoperability works under the hood, [check out the specs](https://specs.optimism.io/interop/overview.html?utm_source=op-docs\&utm_medium=docs).
# Replaying a failed deposit
Source: https://docs.optimism.io/app-developers/tutorials/bridging/replay-failed-deposit
Learn how deposit replays work by deliberately failing a deposit against a test contract on OP Sepolia and then replaying it with more gas, end to end.
When a deposit transaction fails on L2 — usually because it ran out of gas or the L2 state didn't allow it to succeed — the message isn't lost. `L2CrossDomainMessenger` records it as a failed message, and you can replay it later, optionally with more gas.
In this tutorial, you'll make a deposit fail on purpose against a test contract, then replay it successfully, so you can see the full failure-and-replay cycle end to end. For the concepts behind deposits and why replays are possible, see [Deposit flow](/op-stack/bridging/deposit-flow).
## Before you begin
* [Foundry](https://book.getfoundry.sh/getting-started/installation) installed (this tutorial uses `cast`).
* A test account private key, funded with a small amount of test ETH on both **Ethereum Sepolia** (L1) and **OP Sepolia** (L2).
* An L1 (Ethereum Sepolia) RPC URL — e.g. a free [Infura](https://infura.io) key or another provider.
<Info>
**L1 vs L2 network clarification**
This tutorial involves **two different networks**:
* **L1**: Ethereum Sepolia testnet (`https://sepolia.infura.io/v3/YOUR_KEY`)
* **L2**: OP Sepolia testnet (`https://sepolia.optimism.io`)
You'll send transactions on L1 that trigger actions on L2. Make sure you're using the correct RPC URLs for each step.
</Info>
## Trigger and replay a failed deposit
To see how replays work, you can use [this contract on OP Sepolia](https://testnet-explorer.optimism.io/address/0xEF60cF6C6D0C1c755be104843bb72CDa3D778630#code).
1. Call `stopChanges`, using this Foundry command:
```sh theme={null}
PRIV_KEY=<your private key here>
export ETH_RPC_URL=https://sepolia.optimism.io
GREETER=0xEF60cF6C6D0C1c755be104843bb72CDa3D778630
cast send --private-key $PRIV_KEY $GREETER "stopChanges()"
```
2. Verify that `getStatus()` returns false, meaning changes are not allowed, and see the value of `greet()` using Foundry.
Note that Foundry returns false as zero.
```sh theme={null}
cast call $GREETER "greet()" | cast --to-ascii ; cast call $GREETER "getStatus()"
```
3. Get the calldata.
You can use this Foundry command:
```sh theme={null}
cast calldata "setGreeting(string)" "testing"
```
Or just use this value:
```
0xa41368620000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000
```
4. Send a greeting change as a deposit from L1 (Ethereum Sepolia) to L2 (OP Sepolia).
Use these commands:
```sh theme={null}
# L1 = Ethereum Sepolia
# Get a free Infura key at https://infura.io or use the public RPC below
L1_RPC=https://sepolia.infura.io/v3/YOUR_INFURA_KEY
L1XDM_ADDRESS=0x5086d1eef304eb5284a0f6720f79403b4e9be294
FUNC="sendMessage(address,bytes,uint32)"
CALLDATA=`cast calldata "setGreeting(string)" "testing"`
cast send --rpc-url $L1_RPC --private-key $PRIV_KEY $L1XDM_ADDRESS $FUNC $GREETER $CALLDATA 10000000
```
The transaction will be successful on **L1 (Ethereum Sepolia)**, but then emit a fail event on **L2 (OP Sepolia)**.
5. The next step is to find the hash of the failed relay. There are several ways to do this:
**Method A: Using Etherscan Internal Transactions**
Look in [the internal transactions of the destination contract](https://testnet-explorer.optimism.io/address/0xEF60cF6C6D0C1c755be104843bb72CDa3D778630#internaltx), and select the latest one that appears as a failure. It should be a call to `L2CrossDomainMessenger` at address `0x420...007`.
**Method B: Using Contract Events (if internal transactions aren't visible)**
If you can't see internal transactions on Etherscan, check the [L2CrossDomainMessenger contract events](https://testnet-explorer.optimism.io/address/0x4200000000000000000000000000000000000007#events) and look for `FailedRelayedMessage` events with your contract address.
**Method C: Using cast to query failed messages**
```sh theme={null}
# First, you need the message hash. You can derive it from the L1 transaction, or check events
L2XDM_ADDRESS=0x4200000000000000000000000000000000000007
# Replace MSG_HASH with the actual message hash from the FailedRelayedMessage event
cast call $L2XDM_ADDRESS "failedMessages(bytes32)" $MSG_HASH
```
If the latest internal transaction is a success, it probably means your transaction hasn't relayed yet. Wait until it is, that may take a few minutes.
6. Get the transaction information using Foundry.
<Info>
**Wait for the failed relay transaction**
Make sure you wait for the deposit to be processed on L2 and fail before proceeding. This can take 2-5 minutes. You should see a failed transaction in one of the methods from step 5.
</Info>
```sh theme={null}
TX_HASH=<transaction hash from the failed relay on L2>
L2XDM_ADDRESS=0x4200000000000000000000000000000000000007
REPLAY_DATA=`cast tx $TX_HASH input`
```
7. Call `startChanges()` to allow changes using this Foundry command:
```sh theme={null}
cast send --private-key $PRIV_KEY $GREETER "startChanges()"
```
<Info>
Don't do this prematurely
If you call `startChanges()` too early, it will happen when the message is relayed to L2, and then the initial deposit will be successful and there will be no need to replay it.
</Info>
8. Verify that `getStatus()` returns true, meaning changes are not allowed, and see the value of `greet()`.
Foundry returns true as one.
```sh theme={null}
cast call $GREETER "greet()" | cast --to-ascii ; cast 프로젝트로 돌아가기