bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 20쪽
an only be invocable by the cross chain messenger
* Since the contract is self-referential, the cross chain sender must be the same contract address
### Hit the ball cross-chain
```solidity theme={null}
function hitBallTo(uint256 _toChainId) public {
...
// Construct a new ball
PingPongBall memory newBall = PingPongBall(ball.rallyCount + 1, block.chainid, msg.sender);
// Delete current reference
delete ball;
// Send to the destination
messenger.sendMessage(_toChainId, address(this), abi.encodeCall(this.receiveBall, (newBall)));
emit BallSent(block.chainid, _toChainId, newBall);
}
```
* Populate a new ball with updated properties
* Delete reference to the current ball so it's no longer hittable
* Invoke the contract on the destination chain matching the `receiveBall` handler defined in (2).
## Takeaways
This is just one of many patterns to use the `L2ToL2CrossDomainMessenger` in your contract to power cross chain calls. Key points to remember:
* **Simple Message Passing**: This design sends simple messages between identical contracts on different chains. Each message contains only the essential game state (rally count, last hitter). More complex systems might involve multiple contracts, intermediary relayers.
* **Cross Chain Sender Verification**: Always verify the sender of cross-chain messages. This includes checking both the immediate caller (the messenger) and the original sender on the source chain.
* **Cross Chain Contract Coordination**: This design uses CREATE2 for consistent contract addresses across chains, simplifying cross-chain verification. Alternative approaches include:
* Beacon proxy patterns for upgradeable contracts
* Post-deployment setup where contract addresses are specified after deployment
# Deploying crosschain event composability (contests)
Source: https://docs.optimism.io/app-developers/tutorials/interoperability/event-contests
Understand how the Contests example composes with cross-chain events, using the CrossL2Inbox to consume events emitted by contracts on any OP Stack chain.
<Info>OP Stack interop is in active development. Some features may be experimental.</Info>
We showcase cross chain composability through the implementation of contests. Leveraging the same underlying mechanism powering [TicTacToe](/app-developers/tutorials/interoperability/event-reads), these contests can permissionlessly integrate with the events emitted by any contract on OP Stack chains.
<Info>
See the [frontend documentation](https://github.com/ethereum-optimism/supersim/tree/main/examples/contests) for how the contests UI is presented to the user.
</Info>
## How it works
Unlike [TicTacToe](/app-developers/tutorials/interoperability/event-reads) which is deployed on every participating chain, the contests are deployed on a single L2, behaving like an application-specific OP Stack chain rather than a horizontally scaled app.
<Steps>
<Step title="Implement contests">
[Contests.sol](https://github.com/ethereum-optimism/supersim/blob/main/contracts/src/contests/Contests.sol) contains the implementation of the contests. We won't go into the details of the implementation here, but instead focus on how the contests can leverage cross chain event reading to compose with other contracts on OP Stack chains.
</Step>
<Step title="Read cross-chain events">
The system predeploy that enables pulling in validated cross-chain events is the [CrossL2Inbox](https://specs.optimism.io/interop/predeploys.html?utm_source=op-docs\&utm_medium=docs#crossl2inbox).
```solidity theme={null}
contract ICrossL2Inbox {
function validateMessage(Identifier calldata _id, bytes32 _msgHash) external view;
}
```
</Step>
<Step title="Create the contest">
The two contest options are detailed below: [BlockHash contest](#blockhash-contest) and [TicTacToe contest](#tictactoe-contest).
#### BlockHash contest
With the existence of an event that emits the blockhash and height of a block, we can create a contest on the parity of the blockhash being even or odd.
```solidity theme={null}
contract BlockHashEmitter {
event BlockHash(uint256 blockHeight, bytes32 blockHash);
function emitBlockHash(uint256 _blockHeight) external {
bytes32 hash = blockhash(_blockHeight);
require(hash != bytes32(0));
emit BlockHash(_blockHeight, hash);
}
}
```
Integrating this emitter into a contest is extremely simple. The `BlockHashContestFactory` is a simple factory that creates a new contest for a given chain and block height.
#### TicTacToe contest
A contest for TicTacToe is created on an accepted game between two players, captured by the emitted `AcceptedGame` event. When decoding the event, the game is uniquely identified by the chain it was created on, `chainId`, and the associated `gameId`. These identifying properties of the game are used to create the resolver for the game.
```solidity theme={null}
contract TicTacToeContestFactory {
Contests public contests;
TicTacToe public tictactoe;
function newContest(Identifier calldata _id, bytes calldata _data) public payable {
// Validate Log
require(_id.origin == address(tictactoe), "not an event from the TicTacToe contract");
CrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_id, keccak256(_data));
bytes32 selector = abi.decode(_data[:32], (bytes32));
require(selector == TicTacToe.AcceptedGame.selector, "incorrect event");
// Decode the event data
(uint256 chainId, uint256 gameId, address creator,) = abi.decode(_data[32:], (uint256, uint256, address, address));
IContestResolver resolver = new TicTacToeGameResolver(contests, tictactoe, chainId, gameId, creator);
contests.newContest{ value: msg.value }(resolver, msg.sender);
}
}
```
</Step>
<Step title="Resolve contest">
A contest is identified by and has its outcome determined by the `IContestResolver` instance. The resolver starts in the `UNDECIDED` state, updated into `YES` or `NO` when resolving itself
with the contest.
```solidity theme={null}
enum ContestOutcome {
UNDECIDED,
YES,
NO
}
interface IContestResolver {
function outcome() external returns (ContestOutcome);
}
```
#### Resolve BlockHash contest
When live, **anyone** can resolve the BlockHash contest by simply providing the right `BlockHash` event to the deployed resolver.
```solidity theme={null}
contract BlockHashContestFactory {
Contests public contests;
BlockHashEmitter public emitter; // Same emitter deployed on every chain
function newContest(uint256 _chainId, uint256 _blockNumber) public payable {
IContestResolver resolver = new BlockHashResolver(contests, emitter, _chainId, _blockNumber);
contests.newContest{ value: msg.value }(resolver, msg.sender);
}
}
contract BlockHashResolver is IContestResolver {
Contests public contests;
ContestOutcome public outcome;
BlockHashEmitter public emitter;
// The target chain & block height
uint256 public chainId;
uint256 public blockNumber;
function resolve(Identifier calldata _id, bytes calldata _data) external {
require(outcome == ContestOutcome.UNDECIDED);
// Validate Log
require(_id.origin == address(emitter), "not an event from the emitter");
require(_id.chainId == chainId, "must match target chain");
CrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_id, keccak256(_data));
bytes32 selector = abi.decode(_data[:32], (bytes32));
require(selector == BlockHashEmitter.BlockHash.selector, "incorrect event");
// Event should correspond to the right contest
uint256 dataBlockNumber = abi.decode(_data[32:64], (uint256));
require(dataBlockNumber == blockNumber, "must match target block height");
// Resolve the contest (yes if odd, no if even)
bytes32 blockHash = abi.decode(_data[64:], (bytes32));
outcome = uint256(blockHash) % 2 != 0 ? ContestOutcome.YES : ContestOutcome.NO;
contests.resolveContest(this);
}
}
```
#### Resolve TicTacToe contest
When live, **anyone** can resolve the TicTacToe contest by providing the `GameWon` or `GameDraw` event of the associated game from the TicTacToe contract.
```solidity theme={null}
contract TicTacToeGameResolver is IContestResolver {
Contests public contests;
ContestOutcome public outcome;
TicTacToe public tictactoe;
// @notice Game for this resolver
Game public game;
constructor(Contests _contest, TicTacToe _tictactoe, uint256 _chainId, uint256 _gameId, address _creator) {
contests = _contest;
tictactoe = _tictactoe;
game = Game({chainId: _chainId, gameId: _gameId, creator: _creator});
outcome = ContestOutcome.UNDECIDED;
}
// @notice resolve this game by providing the game ending event
function resolve(Identifier calldata _id, bytes calldata _data) external {
// Validate Log
require(_id.origin == address(tictactoe));
CrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_id, keccak256(_data));
// Ensure this is a finalizing event
bytes32 selector = abi.decode(_data[:32], (bytes32));
require(selector == TicTacToe.GameWon.selector || selector == TicTacToe.GameDraw.selector, "event not a game outcome");
// Event should correspond to the right game
(uint256 _chainId, uint256 gameId, address winner,,) = abi.decode(_data[32:], (uint256, uint256, address, uint8, uint8));
require(_chainId == game.chainId && gameId == game.gameId);
// Resolve based on if the creator has won (non-draw)
outcome = winner == game.creator && selector != TicTacToe.GameDraw.selector ? ContestOutcome.YES : ContestOutcome.NO;
contests.resolveContest(this);
}
}
```
</Step>
</Steps>
## Takeaways
* Leveraging superchain interop, contracts in the superchain can compose with each other in a similar fashion to how they would on a single chain. No restrictions are placed on the kinds of events a contract can consume via the `CrossL2Inbox`.
* In this example, the `BlockHashContestFactory` and `TicTacToeContestFactory` can be seen as just starting points for the `Contests` app chain. As more contracts and apps are created in the superchain, developers can compose with them in a similar fashion without needing to change the `Contests` contract at all.
# Making cross-chain event reads (tic-tac-toe)
Source: https://docs.optimism.io/app-developers/tutorials/interoperability/event-reads
Understand how a horizontally scalable TicTacToe implementation uses CrossL2Inbox event reads to coordinate gameplay across interop chains.
<Info>OP Stack interop is in active development. Some features may be experimental.</Info>
This page explains a horizontally scalable implementation of TicTacToe. This [implementation](https://github.com/ethereum-optimism/supersim/blob/main/contracts/src/tictactoe/TicTacToe.sol) allows players to play each other from any chain without cross-chain calls, instead relying on cross-chain event reading. Since OP Stack interop can allow for event reading with a 1-block latency, the experience is the **same as a single-chain implementation**.
<Info>
Check out the [frontend documentation](https://github.com/ethereum-optimism/supersim/tree/main/examples/tictactoe) to see how the game UI is presented to the player.
</Info>
## How it works
We use events to define the ordering of a game with players only maintaining a local view. By default, a chain is also a part of its own interoperable dependency set, which means players on the same chain can also play each other **with no code changes**!
The system predeploy that enables pulling in validated cross-chain events is the [CrossL2Inbox](https://specs.optimism.io/interop/predeploys.html?utm_source=op-docs\&utm_medium=docs#crossl2inbox).
```solidity theme={null}
contract ICrossL2Inbox {
function validateMessage(Identifier calldata _id, bytes32 _msgHash) external view;
}
```
This contract relies on a **CREATE2** deployment to ensure a consistent address across all chains, used to assert the origin of the pulled in game event.
<Steps>
<Step title="Intent to play">
A game is uniquely identified by the chain it was started from with a unique nonce. This identifier is included in all event fields such that each player can uniquely reference it locally.
To start a game, a player invokes `newGame` which broadcasts a `NewGame` event that any opponent **on any chain** can react to.
```solidity theme={null}
event NewGame(uint256 chainId, uint256 gameId, address player);
function newGame() external {
emit NewGame(block.chainid, nextGameId, msg.sender);
nextGameId++;
}
```
</Step>
<Step title="Accepting a game">
When a `NewGame` event is observed, any player can declare their intent to play via `acceptGame`, referencing the `NewGame` event. An `AcceptedGame` event is emitted to signal to the creator that a game is ready to begin.
```solidity theme={null}
event AcceptedGame(uint256 chainId, uint256 gameId, address opponent, address player);
function acceptGame(ICrossL2Inbox.Identifier calldata _newGameId, bytes calldata _newGameData) external {
if (_newGameId.origin != address(this)) revert IdOriginNotTicTacToe();
ICrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_newGameId, keccak256(_newGameData));
bytes32 selector = abi.decode(_newGameData[:32], (bytes32));
if (selector != NewGame.selector) revert DataNotNewGame();
...
emit AcceptedGame(chainId, gameId, game.opponent, game.player);
}
```
To prepare for the game, the event data is decoded and a local view of this game is stored.
```solidity theme={null}
(uint256 chainId, uint256 gameId, address opponent) = abi.decode(_newGameData[32:], (uint256, uint256, address));
if (opponent == msg.sender) revert SenderIsOpponent();
// Record Game Metadata (no moves)
Game storage game = games[chainId][gameId][msg.sender];
game.player = msg.sender;
game.opponent = opponent;
game.gameId = gameId;
game.lastOpponentId = _newGameId;
game.movesLeft = 9;
emit AcceptedGame(chainId, gameId, game.opponent, game.player);
```
</Step>
<Step title="Starting the game">
As `AcceptedGame` events are emitted, the player must pick one opponent to play. The opponent's `AcceptedGame` event is used to instantiate the game and play the starting move via the `MovePlayed` event.
```solidity theme={null}
event MovePlayed(uint256 chainId, uint256 gameId, address player, uint8 _x, uint8 _y);
function startGame(ICrossL2Inbox.Identifier calldata _acceptedGameId, bytes calldata _acceptedGameData, uint8 _x, uint8 _y) external {
if (_acceptedGameId.origin != address(this)) revert IdOriginNotTicTacToe();
ICrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_acceptedGameId, keccak256(_acceptedGameData));
bytes32 selector = abi.decode(_acceptedGameData[:32], (bytes32));
if (selector != AcceptedGame.selector) revert DataNotAcceptedGame();
...
emit MovePlayed(chainId, gameId, game.player, _x, _y);
```
The event fields contain the information required to perform the necessary validation.
* The game identifier for lookup
* The caller is the appropriate player
* The player is accepting from the same starting chain
```solidity theme={null}
(uint256 chainId, uint256 gameId, address player, address opponent) = // player, opponent swapped in local view
abi.decode(_acceptedGameData[32:], (uint256, uint256, address, address));
// The accepted game was started from this chain, from the sender
if (chainId != block.chainid) revert GameChainMismatch();
if (msg.sender != player) revert SenderNotPlayer();
// Game has not already been started with an opponent.
Game storage game = games[chainId][gameId][msg.sender];
if (game.opponent != address(0)) revert GameStarted();
// Store local view of this game
...
// Locally record the move by the player with 1
game.moves[_x][_y] = 1;
game.lastOpponentId = _acceptedGameId;
emit MovePlayed(chainId, gameId, game.player, _x, _y);
```
</Step>
<Step title="Making moves">
Once a game is started, players can continually make moves by invoking `makeMove`, reacting to a `MovePlayed` event of their opponent.
```solidity theme={null}
function makeMove(ICrossL2Inbox.Identifier calldata _movePlayedId, bytes calldata _movePlayedData, uint8 _x, uint8 _y) external {
if (_movePlayedId.origin != address(this)) revert IdOriginNotTicTacToe();
ICrossL2Inbox(Predeploys.CROSS_L2_INBOX).validateMessage(_movePlayedId, keccak256(_movePlayedData));
bytes32 selector = abi.decode(_movePlayedData[:32], (bytes32));
if (selector != MovePlayed.selector) revert DataNotMovePlayed();
}
```
Similar to `acceptGame`, validation is performed and the move of their opponent is first locally recorded.
* The game identifier for lookup
* The caller is the player for this game
* The opponent event corresponds to the same game
* Ordering is enforced by ensuring that the supplied event is always forward progressing.
```solidity theme={null}
(uint256 chainId, uint256 gameId,, uint8 oppX, uint8 oppY) = abi.decode(_movePlayedData[32:], (uint256, uint256, address, uint8, uint8));
// Game was instantiated for this player & the move is for the same game
Game storage game = games[chainId][gameId][msg.sender];
if (game.player != msg.sender) revert GameNotExists();
if (game.gameId != gameId) revert GameNotExists();
// The move played event is forward progressing from the last observed event
if (_movePlayedId.chainId != game.lastOpponentId.chainId) revert IdChainMismatch();
if (_movePlayedId.blockNumber <= game.lastOpponentId.blockNumber) revert MoveNotForwardProgressing();
game.lastOpponentId = _movePlayedId;
// Mark the opponents move
game.moves[oppX][oppY] = 2;
game.movesLeft--;
```
When a move is played we check if the game has been drawn or won, determining the subsequent event to emit.
The `makeMove` function is only callable when an opponent has a new `MovePlayed` event. Therefore, if the game is won or drawn, it cannot be progressed any further by the opponent.
```solidity theme={null}
// Make the players move
game.moves[_x][_y] = 1;
game.movesLeft--;
// Determine the status of the game
if (_isGameWon(game)) {
emit GameWon(chainId, gameId, game.player, _x, _y);
} else if (game.movesLeft == 0) {
emit GameDraw(chainId, gameId, game.player, _x, _y);
} else {
emit MovePlayed(chainId, gameId, game.player, _x, _y);
}
```
</Step>
</Steps>
## Takeaways
Leveraging superchain interop, we can build new types of horizontally scalable contracts that do not rely on hub/spoke messaging with relayers.
* As new chains are added to the superchain, this contract can be installed by anyone and immediately playable with no necessary code changes. The frontend simply needs to react the addition of a new chain.
* The concept of a "chain" can be completely abstracted away from the user. When connecting their wallet, the frontend can simply pick the chain which the user has funds on with the lowest gas fees.
* Event reading enables a new level of composability for cross-chain interactions. Imagine [contests](/app-developers/tutorials/interoperability/event-contests) contract that resolves based on the outcome of a TicTacToe game via the `GameWon` or `GameLost` event without the need for a trusted oracle, nor permission or native integration with the TicTacToe contract.
# Relay transactions manually
Source: https://docs.optimism.io/app-developers/tutorials/interoperability/manual-relay
Learn to relay transactions directly by sending the correct transaction.
<Info>OP Stack interop is in active development. Some features may be experimental.</Info>
<Note>Messages are relayed automatically in the interop devnet.</Note>
## Overview
Learn to relay transactions directly by sending the correct transaction.
<Accordion title="About this tutorial">
**Prerequisite technical knowledge**
* Familiarity with blockchain concepts
* Familiarity with [Foundry](https://book.getfoundry.sh/getting-started/installation), especially `cast`
**What you'll learn**
* How to use `cast` to relay transactions when autorelay does not work
* How to relay transactions using JavaScript
**Development environment requiremen프로젝트로 돌아가기