bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 75쪽
rdered execution, you must change this function. By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
Function which retrieves the next nonce for a given source endpoint and sender address. The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement. Is required by the off-chain executor to determine the OApp expects msg execution is ordered. This is also enforced by the OApp.
| Input | Type | Description |
| --- | --- | --- |
| `_srcEid` | `uint32` | The source endpoint ID. |
| `_sender` | `bytes32` | The sender address. |
Returns: next nonce (`uint64`).
**<>Source code▼**
```vyper
from ..modules.oapp_vyper.src import OApp # main module
exports: (
OApp.endpoint,
OApp.peers,
OApp.setPeer,
OApp.setDelegate,
OApp.isComposeMsgSender,
OApp.allowInitializePath,
OApp.nextNonce,
)
```
```vyper
@external
@pure
def nextNonce(_srcEid: uint32, _sender: bytes32) -> uint64:
"""
@notice Retrieves the next nonce for a given source endpoint and sender address.
@dev Vyper-specific: If your app relies on ordered execution, you must change this function.
@param _srcEid The source endpoint ID.
@param _sender The sender address.
@return nonce The next nonce.
@dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
@dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
@dev This is also enforced by the OApp.
@dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
"""
return 0
```
**▶Example▼**
```shell
>>> LZBlockRelay.nextNonce(30110, 0x000000000000000000000000FacEFeeD696BFC0ebe7EaD3FFBb9a56290d31752)
0
```
* * *
<a id="block-hash-operations"></a>
## Block Hash Operations
This section covers the core cross-chain and block hash relay logic. These functions are responsible for requesting, broadcasting, and receiving block hashes.
info
Currently, only block hashes received via trusted LayerZero channels are committed to the oracle. Later on, more channels can be added.
<a id="request_block_hash"></a>
### `request_block_hash`
`LZBlockRelay.request_block_hash(_target_eids: DynArray[uint32, MAX_N_BROADCAST], _target_fees: DynArray[uint256, MAX_N_BROADCAST], _lz_receive_gas_limit: uint128, _read_gas_limit: uint128, _block_number: uint256 = 0)`
Function to request a block hash from mainnet and broadcast it to specified targets. User must ensure `msg.value` is sufficient. The caller covers read fee (`quote_read_fee`) and broadcast fee (`quote_broadcast_fees`).
| Input | Type | Description |
| --- | --- | --- |
| `_target_eids` | `DynArray[uint32, MAX_N_BROADCAST]` | List of chain IDs to broadcast to |
| `_target_fees` | `DynArray[uint256, MAX_N_BROADCAST]` | List of fees per chain (must match \_target\_eids length) |
| `_lz_receive_gas_limit` | `uint128` | Gas limit for lzReceive (same for all targets) |
| `_read_gas_limit` | `uint128` | Gas limit for read operation |
| `_block_number` | `uint256` | Optional block number (0 means latest) |
**<>Source code▼**
```vyper
@external
@payable
def request_block_hash(
_target_eids: DynArray[uint32, MAX_N_BROADCAST],
_target_fees: DynArray[uint256, MAX_N_BROADCAST],
_lz_receive_gas_limit: uint128,
_read_gas_limit: uint128,
_block_number: uint256 = 0,
):
"""
@notice Request block hash from mainnet and broadcast to specified targets
@param _target_eids List of chain IDs to broadcast to
@param _target_fees List of fees per chain (must match _target_eids length)
@param _lz_receive_gas_limit Gas limit for lzReceive (same for all targets)
@param _read_gas_limit Gas limit for read operation
@param _block_number Optional block number (0 means latest)
@dev User must ensure msg.value is sufficient:
- must cover read fee (quote_read_fee)
- must cover broadcast fees (quote_broadcast_fees)
"""
assert self.read_enabled, "Read not enabled"
assert len(_target_eids) == len(_target_fees), "Length mismatch"
self._request_block_hash(
_block_number,
_target_eids,
_target_fees,
_lz_receive_gas_limit,
_read_gas_limit,
)
@internal
@payable
def _request_block_hash(
_block_number: uint256,
_target_eids: DynArray[uint32, MAX_N_BROADCAST],
_target_fees: DynArray[uint256, MAX_N_BROADCAST],
_lz_receive_gas_limit: uint128,
_read_gas_limit: uint128,
):
"""
@notice Internal function to request block hash from mainnet and broadcast to specified targets
@param _block_number Block number to request
@param _target_eids Target EIDs to broadcast to
@param _target_fees Target fees to pay per broadcast
@param _lz_receive_gas_limit Gas limit for lzReceive
@param _read_gas_limit Gas limit for read operation
"""
# Store target EIDs and fees for lzReceive
cached_targets: DynArray[BroadcastTarget, MAX_N_BROADCAST] = []
sum_target_fees: uint256 = 0
for i: uint256 in range(0, len(_target_eids), bound=MAX_N_BROADCAST):
cached_targets.append(BroadcastTarget(eid=_target_eids[i], fee=_target_fees[i]))
sum_target_fees += _target_fees[i]
assert sum_target_fees <= msg.value, "Insufficient value" # dev: check is here because we sum here
message: Bytes[OApp.MAX_MESSAGE_SIZE] = self._prepare_read_request(_block_number)
# Create options using OptionsBuilder module
options: Bytes[OptionsBuilder.MAX_OPTIONS_TOTAL_SIZE] = OptionsBuilder.newOptions()
options = OptionsBuilder.addExecutorLzReadOption(
options, _read_gas_limit, READ_RETURN_SIZE, convert(sum_target_fees, uint128)
)
# Send message
fees: OApp.MessagingFee = OApp.MessagingFee(nativeFee=msg.value, lzTokenFee=0)
# Fees = read fee + broadcast fees (value of read return message)
receipt: OApp.MessagingReceipt = OApp._lzSend(
self.read_channel, message, options, fees, msg.sender # dev: refund excess fee to sender
)
# Store targets for lzReceive using receipt.guid as key
self.broadcast_data[receipt.guid] = BroadcastData(
targets=cached_targets,
gas_limit=_lz_receive_gas_limit,
)
```
**▶Example▼**
```shell
>>> LZBlockRelay.request_block_hash([30110], [1000000000000000], 200000, 200000, 0)
```
<a id="broadcast_latest_block"></a>
### `broadcast_latest_block`
`LZBlockRelay.broadcast_latest_block(_target_eids: DynArray[uint32, MAX_N_BROADCAST], _target_fees: DynArray[uint256, MAX_N_BROADCAST], _lz_receive_gas_limit: uint128)`
info
Only broadcast what was received via lzRead to prevent potentially malicious hashes from other sources
Function to broadcast the latest confirmed block hash to specified chains.
| Input | Type | Description |
| --- | --- | --- |
| `_target_eids` | `DynArray[uint32, MAX_N_BROADCAST]` | List of chain IDs to broadcast to |
| `_target_fees` | `DynArray[uint256, MAX_N_BROADCAST]` | List of fees per chain (must match \_target\_eids length) |
| `_lz_receive_gas_limit` | `uint128` | Gas limit for lzReceive (same for all targets) |
Emits: `BlockHashBroadcast` event.
**<>Source code▼**
```vyper
@external
@payable
def broadcast_latest_block(
_target_eids: DynArray[uint32, MAX_N_BROADCAST],
_target_fees: DynArray[uint256, MAX_N_BROADCAST],
_lz_receive_gas_limit: uint128,
):
"""
@notice Broadcast latest confirmed block hash to specified chains
@param _target_eids List of chain IDs to broadcast to
@param _target_fees List of fees per chain (must match _target_eids length)
@param _lz_receive_gas_limit Gas limit for lzReceive (same for all targets)
@dev Only broadcast what was received via lzRead to prevent potentially malicious hashes from other sources
"""
assert self.read_enabled, "Can only broadcast from read-enabled chains"
assert self.block_oracle != empty(IBlockOracle), "Oracle not configured"
assert len(_target_eids) == len(_target_fees), "Length mismatch"
# Get latest block from oracle
block_number: uint256 = staticcall self.block_oracle.last_confirmed_block_number()
block_hash: bytes32 = staticcall self.block_oracle.get_block_hash(block_number)
assert block_hash != empty(bytes32), "No confirmed blocks"
# Only broadcast if this block was received via lzRead
assert self.received_blocks[block_number] == block_hash, "Unknown source"
# Prepare broadcast targets
broadcast_targets: DynArray[BroadcastTarget, MAX_N_BROADCAST] = []
for i: uint256 in range(0, len(_target_eids), bound=MAX_N_BROADCAST):
broadcast_targets.append(BroadcastTarget(eid=_target_eids[i], fee=_target_fees[i]))
self._broadcast_block(
block_number,
block_hash,
BroadcastData(targets=broadcast_targets, gas_limit=_lz_receive_gas_limit),
msg.sender,
)
```
**▶Example▼**
```shell
>>> LZBlockRelay.broadcast_latest_block([30110], [1000000000000000], 200000)
```
<a id="lzreceive"></a>
### `lzReceive`
`LZBlockRelay.lzReceive(_origin: OApp.Origin, _guid: bytes32, _message: Bytes[OApp.MAX_MESSAGE_SIZE], _executor: address, _extraData: Bytes[OApp.MAX_EXTRA_DATA_SIZE])`
Handles incoming LayerZero messages, including block hash read responses from mainnet and block hash broadcasts from other chains. Verifies the message source, commits the block hash to the local BlockOracle, and, if appropriate, rebroadcasts the hash to additional chains. Only block hashes received via trusted LayerZero channels are committed.
This function may emit events such as block hash commit or broadcast events, depending on the message type and contract state.
| Input | Type | Description |
| --- | --- | --- |
| `_origin` | `OApp.Origin` | Struct containing the source endpoint ID (`srcEid`), sender address, and nonce. Used to verify the message source. |
| `_guid` | `bytes32` | Global unique identifier for the message, used for tracking and rebroadcast logic. |
| `_message` | `Bytes[OApp.MAX_MESSAGE_SIZE]` | Encoded message payload containing the block number and block hash. |
| `_executor` | `address` | Address of the executor for the message. |
| `_extraData` | `Bytes[OApp.MAX_EXTRA_DATA_SIZE]` | Additional data passed by the executor, used for advanced LayerZero features. |
**<>Source code▼**
```vyper
@payable
@external
def lzReceive(
_origin: OApp.Origin,
_guid: bytes32,
_message: Bytes[OApp.MAX_MESSAGE_SIZE],
_executor: address,
_extraData: Bytes[OApp.MAX_EXTRA_DATA_SIZE],
):
"""
@notice Handle messages: read responses, and regular messages
@dev Two types of messages:
1. Read responses (from read channel)
2. Regular messages (block hash broadcasts from other chains)
@param _origin Origin information containing srcEid, sender, and nonce
@param _guid Global unique identifier for the message
@param _message The encoded message payload containing block number and hash
@param _executor Address of the executor for the message
@param _extraData Additional data passed by the executor
"""
# Verify message source
OApp._lzReceive(_origin, _guid, _message, _executor, _extraData)
if _origin.srcEid == self.read_channel:
# Only handle read response if read is enabled
assert self.read_enabled, "Read not enabled"
# Decode block hash and number from response
block_number: uint256 = 0
block_hash: bytes32 = empty(bytes32)
block_number, block_hash = abi_decode(_message, (uint256, bytes32))
if block_hash == empty(bytes32):
return # Invalid response
# Store received block hash
self.received_blocks[block_number] = block_hash
# Commit block hash to oracle
self._commit_block(block_number, block_hash)
broadcast_data: BroadcastData = self.broadcast_data[_guid]
if len(broadcast_data.targets) > 0:
# Verify that attached value covers requested broadcast fees
total_fee: uint256 = 0
for target: BroadcastTarget in broadcast_data.targets:
total_fee += target.fee
assert msg.value >= total_fee, "Insufficient msg.value"
# Perform broadcast
self._broadcast_block(
block_number,
block_hash,
broadcast_data,
self, # dev: refund excess fee to self
)
else:
# Regular message - decode and commit block hash
block_number: uint256 = 0
block_hash: bytes32 = empty(bytes32)
block_number, block_hash = abi_decode(_message, (uint256, bytes32))
self._commit_block(block_number, block_hash)
```
```vyper
struct Origin:
srcEid: uint32
sender: bytes32
nonce: uint64
@internal
def _lzReceive(
_origin: Origin,
_guid: bytes32,
_message: Bytes[MAX_MESSAGE_SIZE],
_executor: address,
_extraData: Bytes[MAX_EXTRA_DATA_SIZE],
):
"""
@dev Entry point for receiving messages or packets from the endpoint.
@param _origin The origin information containing the source endpoint and sender address.
@param _guid The unique identifier for the received LayerZero message.
@param _message The payload of the received message.
@param _executor The address of the executor for the received message.
@param _extraData Additional arbitrary data provided by the corresponding executor.
"""
# Verify that the sender is the endpoint
assert msg.sender == endpoint.address, "OApp: only endpoint"
# Verify that the message comes from a trusted peer
assert self._getPeerOrRevert(_origin.srcEid) == _origin.sender, "OApp: invalid sender"
```
**▶Example▼**
```shell
# Called by the LayerZero endpoint, not directly by users
>>> LZBlockRelay.lzReceive(origin, guid, message, executor, extra_data)
```
* * *
<a id="fee-quoting"></a>
## Fee Quoting
<a id="quote_read_fee"></a>
### `quote_read_fee`
`LZBlockRelay.quote_read_fee(_read_gas_limit: uint128, _value: uint128) -> uint256: view`
Quotes the fee required for reading a block hash from mainnet via LayerZero. Only callable if read is enabled.
| Input | Type | Description |
| --- | --- | --- |
| `_read_gas_limit` | `uint128` | Gas to be provided in return message |
| `_value` | `uint128` | Value to be provided in return message |
Returns: Fee in native tokens required for the read operation (`uint256`).
**<>Source code▼**
```vyper
@external
@view
def quote_read_fee(
_read_gas_limit: uint128,
_value: uint128,
) -> uint256:
"""
@notice Quote fee for reading block hash from mainnet
@param _read_gas_limit Gas to be provided in return message
@param _value Value to be provided in return message
@return Fee in native tokens required for the read operation
"""
assert self.read_enabled, "Read not enabled - call set_read_config"
message: Bytes[OApp.MAX_MESSAGE_SIZE] = self._prepare_read_request(0) # dev: 0 for latest block
# Create options using OptionsBuilder module
options: Bytes[OptionsBuilder.MAX_OPTIONS_TOTAL_SIZE] = OptionsBuilder.newOptions()
options = OptionsBuilder.addExecutorLzReadOption(
options, _read_gas_limit, READ_RETURN_SIZE, _value
)
return OApp._quote(
self.read_channel,
message,
options,
False,
).nativeFee
```
```vyper
@internal
@pure
def newOptions() -> Bytes[MAX_OPTIONS_TOTAL_SIZE]:
"""
@notice Creates a new options container with type 3.
@return options The newly created options container.
"""
options: Bytes[MAX_OPTIONS_TOTAL_SIZE] = concat(convert(TYPE_3, bytes2), b"")
return options
@internal
@pure
def addExecutorOption(
_options: Bytes[MAX_OPTIONS_TOTAL_SIZE],
_optionType: uint8,
_option: Bytes[MAX_OPTION_SINGLE_SIZE],
) -> Bytes[MAX_OPTIONS_TOTAL_SIZE]:
"""
@dev Adds an executor option to the existing options.
@param _options The existing options container.
@param _optionType The type of the executor option.
@param _option The encoded data for the executor option.
@return options The updated options container.
"""
assert convert(slice(_options, 0, 2), uint16) == TYPE_3, "OApp: invalid option type"
# Account for header bytes: 1 worker + 2 size + 1 type = 4 bytes
assert (len(_options) + len(_option) + 4 <= MAX_OPTIONS_TOTAL_SIZE), "OApp: options size exceeded"
return concat(
convert(_options, Bytes[MAX_OPTIONS_TOTAL_SIZE - MAX_OPTION_SINGLE_SIZE - 4]), # downcast Bytes size, -4 for header
convert(EXECUTOR_WORKER_ID, bytes1),
convert(convert(len(_option) + 1, uint16), bytes2), # +1 for optionType
convert(_optionType, bytes1),
_option,
)
```
```vyper
interface ILayerZeroEndpointV2:
def quote(_params: MessagingParams, _sender: address) -> MessagingFee: view
def send(_params: MessagingParams, _refundAddress: address) -> MessagingReceipt: payable
def setDelegate(_delegate: address): nonpayable
def eid() -> uint32: view
def lzToken() -> address: view
# Mapping to store peers associated with corresponding endpoints
peers: public(HashMap[uint32, bytes32])
@internal
@view
def _quote(
_dstEid: uint32,
_message: Bytes[MAX_MESSAGE_SIZE],
_options: Bytes[MAX_OPTIONS_TOTAL_SIZE],
_payInLzToken: bool,
) -> MessagingFee:
"""
@dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
@param _dstEid The destination endpoint ID.
@param _message The message payload.
@param _options Additional options for the message.
@param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
@return fee The calculated MessagingFee for the message.
- nativeFee: The native fee for the message.
- lzTokenFee: The LZ token fee for the message.
"""
return staticcall endpoint.quote(
MessagingParams(
dstEid=_dstEid,
receiver=self._getPeerOrRevert(_dstEid),
message=_message,
options=_options,
payInLzToken=_payInLzToken,
),
self,
)
@view
@internal
def _getPeerOrRevert(_eid: uint32) -> bytes32:
"""
@notice Internal function to get the peer address associated with a specific endpoint;
reverts if NOT set.
@param _eid The endpoint ID.
@return peer The address of the peer associated with the specified endpoint.
"""
peer: bytes32 = self.peers[_eid]
assert peer != empty(bytes32), "OApp: no peer"
return peer
```
**▶Example▼**
```shell
>>> LZBlockRelay.quote_read_fee(200000, 0)
1000000000000000
```
<a id="quote_broadcast_fees"></a>
### `quote_broadcast_fees`
`LZBlockRelay.quote_broadcast_fees(_target_eids: DynArray[uint32, MAX_N_BROADCAST], _lz_receive_gas_limit: uint128) -> DynArray[uint256, MAX_N_BROADCAST]: view`
Estimates the LayerZero fee required to broadcast a block hash to each specified target chain. Useful for integrators to determine the cost of broadcasting to multiple chains before submitting a transaction. Only targets with a configured peer will return a nonzero fee.
| Input | Type | Description |
| --- | --- | --- |
| `_target_eids` | `DynArray[uint32, MAX_N_BROADCAST]` | List of target chain endpoint IDs to quote broadcast fees for. |
| `_lz_receive_gas_limit` | `uint128` | Gas limit to be provided for the lzReceive call on each target. |
Returns: an array of fees in native tokens, one per target chain, with zero for any target not configured (`DynArray[uint256, MAX_N_BROADCAST]`).
**<>Source code▼**
```vyper
@external
@view
def quote_broadcast_fees(
_target_eids: DynArray[uint32, MAX_N_BROADCAST],
_lz_receive_gas_limit: uint128,
) -> DynArray[uint256, MAX_N_BROADCAST]:
"""
@notice Quote fees for broadcasting block hash to specified targets
@param _target_eids List of chain IDs to broadcast to
@param _lz_receive_gas_limit Gas limit for lzReceive
@return Array of fees per target chain (0 if target not configured)
"""
# Prepare dummy broadcast message (uint256 number, bytes32 hash)
message: Bytes[OApp.MAX_MESSAGE_SIZE] = abi_encode(empty(uint256), empty(bytes32))
# Prepare array of fees per chain
fees: DynArray[uint256, MAX_N_BROADCAST] = []
# Prepare options (same for all targets)
options: Bytes[OptionsBuilder.MAX_OPTIONS_TOTAL_SIZE] = OptionsBuilder.newOptions()
options = OptionsBuilder.addExecutorLzReceiveOption(options, _lz_receive_gas_limit, 0)
# Cycle through targets
for eid: uint32 in _target_eids:
target: bytes32 = OApp.peers[eid] # Use peers directly
if target == empty(bytes32):
fees.append(0)
continue
# Get fee for target EID and append to array
fees.append(OApp._quote(eid, message, options, False).nativeFee)
return fees
```
```vyper
from . import VyperConstants as constants
MAX_OPTIONS_TOTAL_SIZE: constant(uint256) = constants.MAX_OPTIONS_TOTAL_SIZE
MAX_OPTION_SINGLE_SIZE: constant(uint256) = constants.MAX_OPTION_SINGLE_SIZE
@internal
@pure
def newOptions() -> Bytes[MAX_OPTIONS_TOTAL_SIZE]:
"""
@notice Creates a new options container w프로젝트로 돌아가기