Transactions
Token Transfers
Internal Transactions
Coin Balance History
Logs
Code
Read Contract
Write Contract
Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- DeliveryRouter
- Optimization enabled
- false
- Compiler version
- v0.8.28+commit.7893614a
- EVM Version
- Verified at
- 2026-11-19T13:51:03.628407Z
Constructor Arguments
000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f700000000000000000000000070499adebb11efd915e3b69e700c331778628707000000000000000000000000e73c08fcda3aba51009b5804d2c464229cd22db4000000000000000000000000f71cbaa5a165fad2ffff6b0d68e84d67b1f75eac
Arg [0] (address) : 0x571f96605921f76a24cf1388c2caf126b15b09f7
Arg [1] (address) : 0x70499adebb11efd915e3b69e700c331778628707
Arg [2] (address) : 0xe73c08fcda3aba51009b5804d2c464229cd22db4
Arg [3] (address) : 0xf71cbaa5a165fad2ffff6b0d68e84d67b1f75eac
src/hardened/mediator/DeliveryRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {MessageBridge} from "../MessageBridge.sol";
import {ITokenMediator} from "./ITokenMediator.sol";
import {IWETH} from "./IWETH.sol";
import {ExactGasCall} from "./ExactGasCall.sol";
/// @title DeliveryRouter
/// @notice The one router of the bridge, on both chains. On the source chain it wraps the native coin and sends it
/// (`wrapAndRelayTokens`, `relayTokensAndCall`). On the destination chain it delivers a bridged message, pays a tip for
/// it, and unwraps the wrapped native token. It needs no change to the message bridge or the mediator. The sender states the delivery terms in a `FeeDirector`.
/// Layers. The message bridge is neutral and anyone can use it. The mediator is shared by everyone, so it is immutable
/// and trusts no router. This router is the third layer: a frontend chooses which router it points at, and a new
/// router can replace this one with no change to the bridge or the mediator. Neither of them names a router. The
/// mediator gives the callback of the router exactly the gas that the sender stated in the relay (`callbackGas`), and
/// everything in this contract (the fee, the follow-up call and its gas) runs inside that gas.
/// @dev Flow. 1: a sender relays tokens with `relayTokensAndCall` to this router on the destination chain, with an
/// encoded `FeeDirector` as data. 2: anyone calls `executeMessage`. The router stores the starting gas in one slot
/// (`DELIVERY_SLOT`), which marks a router delivery, and executes the message on the bridge. 3: the mediator releases
/// the tokens to the router and calls `onTokenBridged`. 4: the router reads the slot, computes the tip, pays the
/// immutable `rewardAddress`, and pays the rest to the recipient. When the slot is not set, because someone executed
/// the message on the bridge directly, the recipient gets everything and the router takes no tip. A data field of 20
/// bytes is the legacy form: the address that receives the unwrapped native coin, with no tip.
///
/// Source side. `wrapAndRelayTokens` and `relayTokensAndCall` follow `WETHOmnibridgeRouter` of OmniBridge
/// (`contracts/helpers/WETHOmnibridgeRouter.sol`) without its owner, its `claimTokens` and its destination role. They
/// wrap the coin and relay the wrapped token with `relayTokens` or `relayTokensAndCall` of the mediator. The mediator
/// pays the receiver only, and a release that the receiver cannot take is final. This router has no fallback option.
/// A relay with a call passes the gas of the callback on to the mediator. A receiver that is the zero address or this
/// router is refused. The router sends nothing that it holds: the wrap and the relay run in one call. There is no second
/// router for the unwrap: the `UNWRAP` flag and the 20 byte legacy data of `onTokenBridged` do it, so the bridge needs one contract on each chain. The router holds no standing approval: each
/// wrap approves the mediator for exactly the amount that it wraps, and the mediator takes all of it in the same call, so
/// the allowance ends at zero.
///
/// Design choices.
/// - There is no owner, no `claimTokens` and no validator filter. Any account may call `executeMessage`. The tip
/// always goes to the immutable `rewardAddress`, and the caller names nothing, so a copy of a delivery gains the
/// copier nothing: a block builder or a searcher who front-runs a delivery pays the gas and the reward address still
/// gets the tip. The bridge stays permissionless. Anyone may call `MessageBridge.executeMessage` directly. The
/// router then sees no starting gas, takes no tip, and the recipient gets everything, so the user loses nothing.
/// - The tip does not go to the account that calls, and the caller names no one to receive it. The tip goes to
/// `rewardAddress`, which has no setter and no owner.
/// - The reward address is an account that can refuse the tip, so its payment never blocks the payment of the
/// recipient: when it cannot receive its tip, the recipient gets the tip as well. A native coin that the recipient
/// cannot receive is paid as the wrapped token.
/// - The router never reads `tx.origin` or `msg.sender` of `executeMessage`, so a generic Multicall3 contract
/// (`aggregate3` with `allowFailure`) can batch many deliveries, and the block proof, in one transaction. The router
/// knows nothing about batching. A failed call never reverts the others.
/// - The gas based tip is measured in the callback, which reads `startingGas - gasleft()`, where
/// `startingGas` is stored at the entry of `executeMessage`, adds the fixed overhead that covers the rest of the
/// run and, when a call follows, the `callGas` of the terms, caps the tip at the smaller of `limit` and the value,
/// and pays one transfer to the reward address and one to the recipient. The measure is the gas that the delivery
/// used up to the callback: the proof, the bridge and the mediator. A deliverer can choose a costlier proof route
/// (a longer ancestry branch), so a sender must still expect the tip to reach `limit`: `limit` is the price ceiling,
/// and it is the only hard bound on a gas based tip. The tip goes to the fixed reward address, so a stranger gains
/// nothing from it.
/// - `EXCLUDE_PRIORITY` prices gas at `block.basefee`. On a chain that reports a base fee of 0 (BSC) the gas based tip
/// is then zero. The interfaces refuse `EXCLUDE_PRIORITY` for a chain that is configured as having no base fee.
/// - The slot uses regular storage (the compiler target has no transient storage), so it is set and cleared with the
/// value 1, which keeps the slot non-zero after the first use. It holds the starting gas and no address.
/// - There is no `EIP1559_ENABLED` switch. The router reads `block.basefee`.
/// - An unwrap flag on a token that is not the wrapped native token is ignored: the
/// recipient gets the token. The 20 byte legacy form pays the token to the receiver for any token that is not the
/// wrapped native token, and it never reverts for that reason.
/// - Every delivery that pays its recipient emits `Delivered`, with what the router received, the fee, what the
/// recipient received and how. An explorer reads the fee from it, so the router keeps no record of its own.
///
/// Nothing is owed and nothing is recorded. The mediator calls `onTokenBridged` after it paid the router, and it keeps no
/// hold on a failed call: the tokens stay with the router. So a revert in the callback would strand them, and the router
/// never reverts there. Instead it hands off what it cannot deliver to the immutable `failedDeliveryAddress`, and emits
/// `DeliveryFailed`. The tip still goes to the reward address first, whenever the delivery path takes a tip.
/// - The token refuses the payout to a valid recipient (a blocklist, a revert), the coin and the wrapped token are both
/// refused: the router hands off the amount that it could not deliver.
/// - The terms decode but name the zero address or the router itself as the recipient. The router takes the tip by the
/// terms, as for any delivery, and hands off the rest.
/// - The data has no known shape: shorter than a director, or a recipient word with bits above 160, which `abi.decode`
/// would refuse. No tip can be computed, so the router hands off the whole value.
/// - The data is a 20 byte legacy receiver, and the token is not the wrapped native token. The router pays the token to
/// that receiver, with no fee, and hands off the value when the token refuses the receiver.
/// A hand-off that `failedDeliveryAddress` cannot take (a token that blocks it) stays in the router for good, and the
/// router emits `HandOffRefused`. The router keeps no record of it, and it has no `claim`. A plain relay is the one thing
/// that the router cannot see: the mediator pays the router with no callback when a sender names the router as the
/// receiver with `relayTokens`, or when a callback fails. Anyone may call `sweep` to hand the whole balance of a token to
/// `failedDeliveryAddress`.
/// A recipient payout hook can make the bridge deliver another message while a delivery runs, so the mediator calls
/// `onTokenBridged` again. The router detects that with the state of its reentrancy guard and does not revert. It hands
/// the whole value of that nested callback off with the reason `Reentered`, after the tip when the terms decode and a
/// router delivery runs, as the token and with no unwrap. `sweep` keeps the guard and refuses a reentrant call.
///
/// The call after a delivery. The data of `onTokenBridged` is the 160 byte director. Optional bytes may follow it: a 20
/// byte target and then the call data, which fill the rest of the data. A director with no extra bytes, and a director
/// with fewer than 20 extra bytes, mean delivery only. When the router paid the recipient in full (the token, or the
/// native coin, or the wrapped token that replaced a refused coin), it makes one call to the target from itself, with the
/// call data and no native value. The target may differ from the recipient. The call gets exactly `callGas` of the
/// director (`ExactGasCall`). When the gas left cannot give it `callGas` under the 63/64 rule plus `CALL_GAS_RESERVE`,
/// which the router keeps to finish, the callback reverts: the mediator gave the callback the gas that the sender
/// stated, so this means the sender's `callbackGas` is too small for its own `callGas`, and the mediator records
/// `CallbackFailed` with the tokens left in the router (anyone may `sweep` them). A call that fails with its `callGas`
/// never reverts the delivery and moves no tokens: the router emits `CallFailed`, and the recipient keeps the tokens.
/// The router skips the call when the tip left nothing to pay the recipient, and when a payment failed and the amount
/// was handed off. The router reads no data that the target returns. The call comes from the router, so it can reach
/// only what the router holds at that moment. After the payments that is stray tokens, which anyone may already sweep.
/// The router holds no allowance for the target to use.
///
/// The gas based tip counts the call. The router takes the tip before the payments and the call, so a measure of the gas
/// that ran so far cannot cover the call. When a call is requested, the router adds `callGas`, the gas that the sender
/// gave the call.
contract DeliveryRouter is ReentrancyGuard {
using SafeERC20 for IERC20;
/// @notice What the sender of the tokens asks for. The data is five words: the recipient, the settings
/// flag bits, the limit, the multiplier and the gas of the follow-up call.
/// @param recipient Who receives the tokens after the tip.
/// @param settings Flag bits. Bit 0 (`FIXED_FEE`): the tip is `limit`. Bit 1 (`UNWRAP`): unwrap the wrapped native
/// token to the native coin. Bit 2 (`EXCLUDE_PRIORITY`): price gas at the base fee only, with no priority fee. Bit 3
/// (`MULTIPLIER_OF_TOTAL`): the tip is `value * multiplier / 1e18`. With bit 0 and bit 3 clear, the tip is the gas
/// based fee. Bit 0 wins over bit 3.
/// @param limit The fixed tip, or the price ceiling of the gas based tip. A gas based tip is computed from the gas
/// that the transaction of the deliverer makes available, which the deliverer chooses, so expect it to reach `limit`.
/// @param multiplier Scaled by 1e18: the share of the value, or the factor on the gas cost.
/// @param callGas The gas that the follow-up call gets, exactly. It is read only when a call follows the director.
struct FeeDirector {
address recipient;
uint256 settings;
uint256 limit;
uint256 multiplier;
uint256 callGas;
}
/// @dev Whether the data asks for a call after the delivery.
enum CallRequest {
None,
Requested
}
/// @dev How a payout travels: as the token, or as the native coin after an unwrap.
enum Payout {
Token,
Native
}
/// @notice How the recipient received a payout. `None` is never emitted: it means that the payout failed and the
/// router handed the amount off. `Wrapped`: the unwrap was asked for, the recipient refused the native coin, and
/// it received the wrapped token instead.
enum PaidAs {
None,
Token,
Native,
Wrapped
}
/// @dev Which price a gas based fee uses.
enum GasPrice {
Transaction,
BaseFee
}
/// @notice The value of `settings` bit 0: the tip is `limit`.
uint256 public constant FIXED_FEE = 1;
/// @notice The value of `settings` bit 1: unwrap to the native coin. It applies to the wrapped native token only.
uint256 public constant UNWRAP = 2;
/// @notice The value of `settings` bit 2: price gas at the base fee only, with no priority fee.
uint256 public constant EXCLUDE_PRIORITY = 4;
/// @notice The value of `settings` bit 3: the tip is `value * multiplier / 1e18`.
uint256 public constant MULTIPLIER_OF_TOTAL = 8;
/// @notice Gas added to the measured gas of a token payout, for the transfers after the measure and a margin.
uint256 public constant TOKEN_GAS_OVERHEAD = 100_000;
/// @notice Gas added to the measured gas of a native coin payout. It covers two coin sends to new accounts and the
/// `Delivered` event (about 101,000 gas measured as an upper bound).
uint256 public constant NATIVE_GAS_OVERHEAD = 105_000;
/// @notice The gas that the router gives an account that receives the native coin: the recipient or the reward address. It
/// is enough for the `receive` function of a smart-contract wallet, and it is a bound: a receiver cannot burn more,
/// so the fallback (wrap again and send the wrapped token) always has gas.
uint256 public constant NATIVE_SEND_GAS = 50_000;
/// @notice The gas that the router keeps for itself after the call that follows a delivery: the event of a failed
/// call and the exit of the callback. The call needs this much gas left on top of `callGas` and its 63/64 share.
uint256 public constant CALL_GAS_RESERVE = 10_000;
/// @notice The slot that holds the starting gas (low 96 bits) while a message runs through `executeMessage`. It
/// holds 1 at all other times, which means that no router delivery runs.
bytes32 public constant DELIVERY_SLOT = keccak256(abi.encode("deliveryrouter.delivery"));
uint256 private constant NOT_RUNNING = 1;
/// @dev The length of an encoded `FeeDirector`: five words.
uint256 private constant DIRECTOR_LENGTH = 160;
/// @dev The length of the target of the call: one address.
uint256 private constant TARGET_LENGTH = 20;
/// @dev Where the call data starts in the data: after the director and the target.
uint256 private constant CALL_DATA_OFFSET = DIRECTOR_LENGTH + TARGET_LENGTH;
/// @notice The receiver of a relay is the zero address or this router.
error InvalidReceiver(address receiver);
/// @notice A relay with a call needs data, because the mediator calls only when there is data.
error EmptyData();
/// @notice The router holds none of the token.
error NothingToSweep(address token);
/// @notice The reward address of the constructor is the zero address.
error ZeroRewardAddress();
/// @notice The caller of `onTokenBridged` is not the mediator.
error NotMediator(address caller);
/// @notice A message is running already through this router.
error DeliveryInProgress();
/// @notice The coin came from an account that is not the wrapped token.
error NotWrappedTokenSender(address sender);
/// @notice The failed delivery address of the constructor is the zero address.
error ZeroFailedDeliveryAddress();
/// @dev Why the router handed off an amount.
enum Reason {
PayoutRefused,
InvalidTerms,
Reentered
}
/// @notice Emitted on every hand-off to `failedDeliveryAddress`. `recipient` is the account that the terms named,
/// or the zero address when the data has no known shape.
event DeliveryFailed(address indexed token, address indexed recipient, uint256 amount, Reason reason);
/// @notice Emitted when `sweep` hands the balance of a token off to `failedDeliveryAddress`.
event Swept(address indexed token, uint256 amount);
/// @notice Emitted when the token refuses a push to `failedDeliveryAddress`, for a hand-off or for `sweep`. The
/// amount stays in the router, with no record.
event HandOffRefused(address indexed token, uint256 amount);
/// @notice Emitted when the call after a delivery fails with the gas that the sender gave it. `gasGiven` is that
/// gas, the `callGas` of the director.
event CallFailed(address indexed target, address indexed recipient, uint256 gasGiven);
/// @notice Emitted on every successful delivery: the recipient received its payout. It is emitted after the
/// payments and before the call that follows, so a failed call adds `CallFailed` after it.
/// @param token The token that the mediator released to the router (the wrapped native token for an unwrap).
/// @param recipient The recipient that the terms (or the 20 byte legacy data) named.
/// @param feeTo The account that received the fee: `rewardAddress`, or the zero address when no fee was paid.
/// @param amount What the router received for this delivery: `fee + paidOut`.
/// @param fee What `feeTo` received. Zero when the message ran on the bridge directly, when the terms ask for no
/// fee, for the legacy data, and when the reward address refused the fee (it then stays with the recipient).
/// @param paidOut What the recipient received.
/// @param paidAs As the token, the native coin, or the wrapped token after a refused coin.
/// @param callTarget The target of the call that follows, or the zero address when no call follows.
event Delivered(
address indexed token,
address indexed recipient,
address indexed feeTo,
uint256 amount,
uint256 fee,
uint256 paidOut,
PaidAs paidAs,
address callTarget
);
/// @notice The mediator on this chain.
ITokenMediator public immutable bridge;
/// @notice The wrapped native token that `UNWRAP` unwraps.
IWETH public immutable wNative;
/// @notice The only address that receives a tip. It has no setter and no owner.
address public immutable rewardAddress;
/// @notice Where the router hands off what it cannot deliver. It may equal `rewardAddress`. It has no setter and no
/// owner.
address public immutable failedDeliveryAddress;
/// @param bridge_ The mediator on this chain.
/// @param wNative_ The wrapped native token of this chain.
/// @param rewardAddress_ The address that receives the tips. It cannot be the zero address.
/// @param failedDeliveryAddress_ The address that receives what the router cannot deliver. It cannot be the zero
/// address. It may equal `rewardAddress_`.
constructor(ITokenMediator bridge_, IWETH wNative_, address rewardAddress_, address failedDeliveryAddress_) {
if (rewardAddress_ == address(0)) revert ZeroRewardAddress();
if (failedDeliveryAddress_ == address(0)) revert ZeroFailedDeliveryAddress();
bridge = bridge_;
wNative = wNative_;
rewardAddress = rewardAddress_;
failedDeliveryAddress = failedDeliveryAddress_;
}
/// @notice Wraps the coin and relays it to the caller on the other chain.
function wrapAndRelayTokens() external payable {
_wrapAndRelay(msg.sender, "", 0);
}
/// @notice Wraps the coin and relays it to `receiver` on the other chain.
function wrapAndRelayTokens(address receiver) external payable {
_wrapAndRelay(receiver, "", 0);
}
/// @notice Wraps the coin, relays it to `receiver` and calls `onTokenBridged` on it with `data` and exactly
/// `callbackGas`. Name a `DeliveryRouter` on the other chain as the receiver, with its terms as data, to pay a tip or
/// to get the native coin back there.
/// @param callbackGas The gas of the callback on the other chain. The mediator refuses zero.
function relayTokensAndCall(address receiver, bytes calldata data, uint256 callbackGas) external payable {
if (data.length == 0) revert EmptyData();
_wrapAndRelay(receiver, data, callbackGas);
}
/// @notice Executes a message on the message bridge, and takes the tip of any tokens that it delivers to this
/// router, for `rewardAddress`. Anyone may call it. It reverts when the delivery fails, so the caller sees the
/// error.
/// @param proof The evidence that `MessageBridge.executeMessage` verifies. The router forwards it and does not read it.
function executeMessage(MessageBridge.MessageProof calldata proof) external {
if (_startingGas() > NOT_RUNNING) revert DeliveryInProgress();
_storeStartingGas(uint256(uint96(gasleft())));
MessageBridge(address(bridge.bridgeContract())).executeMessage(proof);
_storeStartingGas(NOT_RUNNING);
}
/// @notice The callback of the mediator. It splits the tokens between the reward address and the recipient, and
/// hands off to `failedDeliveryAddress` what it cannot deliver. It takes a tip only while `executeMessage` runs.
/// @param token The token that the mediator released to the router.
/// @param value The amount that the mediator reports.
/// @param data An encoded `FeeDirector`, or the 20 byte address of a native coin receiver.
/// @dev A call that arrives while another callback runs (a recipient payout hook made the bridge deliver another
/// message) does not revert: the router hands the value off with the reason `Reentered`.
function onTokenBridged(address token, uint256 value, bytes memory data) external {
if (msg.sender != address(bridge)) revert NotMediator(msg.sender);
if (_reentrancyGuardEntered()) {
_handOffReentered(token, _deliverableAmount(token, value), data);
return;
}
_deliver(token, _deliverableAmount(token, value), data);
}
/// @notice Hands the whole balance of a token off to `failedDeliveryAddress`. Anyone may call it. It recovers
/// tokens that reached the router with no callback: a plain relay to the router, a plain transfer, or a callback that
/// failed. It reverts when the router holds none. When the token refuses the push, the router emits `HandOffRefused`
/// and the tokens stay where they are.
/// @param token The token.
function sweep(address token) external nonReentrant {
uint256 amount = IERC20(token).balanceOf(address(this));
if (amount == 0) revert NothingToSweep(token);
if (!_push(token, amount)) return;
emit Swept(token, amount);
}
/// @notice The fee and the amount for the recipient that the router computes.
/// @param token The token that the mediator released.
/// @param value The released amount.
/// @param gasUsed The gas that the whole execution used, for a gas based fee, with the `callGas` of the director
/// added when a call follows. It is not read for a fixed or percent fee.
/// @param director The fee terms.
/// @return fee The fee for the reward address.
/// @return toRecipient The amount for the recipient.
function feeInfo(address token, uint256 value, uint256 gasUsed, FeeDirector calldata director)
external
view
returns (uint256 fee, uint256 toRecipient)
{
bool toNative = director.settings & UNWRAP != 0 && token == address(wNative);
fee = _fee(value, gasUsed, director, toNative ? NATIVE_GAS_OVERHEAD : TOKEN_GAS_OVERHEAD);
toRecipient = value - fee;
}
/// @notice The gas price that a gas based tip uses: the base fee when `excludePriority` is set, else the gas price of
/// the transaction.
/// @param excludePriority True for the base fee only.
function baseFee(bool excludePriority) external view returns (uint256) {
return _gasPrice(excludePriority ? GasPrice.BaseFee : GasPrice.Transaction);
}
/// @notice Accepts the native coin from the wrapped token only, when it unwraps.
receive() external payable {
if (msg.sender != address(wNative)) revert NotWrappedTokenSender(msg.sender);
}
/// @dev Wraps the coin and relays the wrapped token. The approval is for the amount of this call only, and the mediator
/// takes all of it. Empty data means a plain relay, with no gas number.
function _wrapAndRelay(address receiver, bytes memory data, uint256 callbackGas) private {
if (receiver == address(0) || receiver == address(this)) revert InvalidReceiver(receiver);
wNative.deposit{value: msg.value}();
wNative.approve(address(bridge), msg.value);
if (data.length == 0) return bridge.relayTokens(address(wNative), receiver, msg.value);
bridge.relayTokensAndCall(address(wNative), receiver, msg.value, data, callbackGas);
}
/// @dev The delivery of one callback. The guard is held while it runs, so a payout hook or the call after the
/// delivery that makes the mediator call back takes the hand-off path of `onTokenBridged`.
function _deliver(address token, uint256 value, bytes memory data) private nonReentrant {
if (data.length == 20) {
_payLegacy(token, address(bytes20(data)), value);
return;
}
if (!_hasKnownShape(data)) {
_handOff(token, address(0), value, Reason.InvalidTerms);
return;
}
FeeDirector memory director = abi.decode(data, (FeeDirector));
Payout payout = director.settings & UNWRAP != 0 && token == address(wNative) ? Payout.Native : Payout.Token;
if (payout == Payout.Native) wNative.withdraw(value);
CallRequest request = data.length >= CALL_DATA_OFFSET ? CallRequest.Requested : CallRequest.None;
uint256 startingGas = _startingGas();
uint256 toRecipient =
startingGas > NOT_RUNNING ? _takeFee(token, payout, value, director, startingGas, request) : value;
if (toRecipient == 0) {
_emitDelivered(token, director.recipient, value, 0, payout == Payout.Native ? PaidAs.Native : PaidAs.Token, address(0));
return;
}
PaidAs paidAs = _payRecipient(token, payout, director.recipient, toRecipient);
if (paidAs == PaidAs.None) return;
address target = request == CallRequest.Requested ? _target(data) : address(0);
_emitDelivered(token, director.recipient, value, toRecipient, paidAs, target);
if (request == CallRequest.Requested) _callTarget(target, director.recipient, data, director.callGas);
}
/// @dev Emits `Delivered`. The fee is what the recipient did not get: the router pays the reward address first, and
/// a refused fee stays with the recipient.
function _emitDelivered(
address token,
address recipient,
uint256 value,
uint256 paidOut,
PaidAs paidAs,
address target
) private {
uint256 fee = value - paidOut;
emit Delivered(token, recipient, fee == 0 ? address(0) : rewardAddress, value, fee, paidOut, paidAs, target);
}
/// @dev The hand-off of a callback that arrives while another callback runs. The router pays nobody then: it takes
/// the tip when the terms decode and a router delivery runs, and hands the rest off, as the token and with no unwrap.
function _handOffReentered(address token, uint256 value, bytes memory data) private {
if (data.length == 20) {
_handOff(token, address(bytes20(data)), value, Reason.Reentered);
return;
}
if (!_hasKnownShape(data)) {
_handOff(token, address(0), value, Reason.Reentered);
return;
}
FeeDirector memory director = abi.decode(data, (FeeDirector));
uint256 startingGas = _startingGas();
uint256 rest = startingGas > NOT_RUNNING
? _takeFee(token, Payout.Token, value, director, startingGas, CallRequest.None)
: value;
_handOff(token, director.recipient, rest, Reason.Reentered);
}
/// @dev Takes the tip in the callback and pays it to the reward address. A tip that the reward address refuses
/// stays with the recipient. The measure is the gas that ran since the entry of `executeMessage`. When a call is
/// requested, the measure adds `callGas`, because the call runs after the tip.
/// @return toRecipient What the recipient receives.
function _takeFee(
address token,
Payout payout,
uint256 value,
FeeDirector memory director,
uint256 startingGas,
CallRequest request
) private returns (uint256 toRecipient) {
uint256 overheadGas = payout == Payout.Native ? NATIVE_GAS_OVERHEAD : TOKEN_GAS_OVERHEAD;
uint256 gasUsed = startingGas - gasleft();
if (request == CallRequest.Requested) gasUsed += director.callGas;
uint256 fee = _fee(value, gasUsed, director, overheadGas);
if (fee == 0 || !_tryPay(token, payout, rewardAddress, fee)) return value;
return value - fee;
}
/// @dev Makes the call after a delivery: from the router, with no native value, to the target at the start of the
/// bytes after the director, with the call data that follows. It reads no answer, so a target cannot spend gas on a
/// large one. It gets exactly `callGas` (`ExactGasCall`, with `CALL_GAS_RESERVE` kept for the work after it): too
/// little gas reverts, and a failure with `callGas` emits `CallFailed` and changes nothing else.
function _callTarget(address target, address recipient, bytes memory data, uint256 callGas) private {
if (!ExactGasCall.callWithExactGas(target, callGas, CALL_GAS_RESERVE, data, CALL_DATA_OFFSET)) {
emit CallFailed(target, recipient, callGas);
}
}
/// @dev The target of the call: the 20 bytes after the director.
function _target(bytes memory data) private pure returns (address target) {
uint256 targetOffset = 32 + DIRECTOR_LENGTH;
assembly ("memory-safe") {
target := shr(96, mload(add(data, targetOffset)))
}
}
function _startingGas() private view returns (uint256 stored) {
bytes32 slot = DELIVERY_SLOT;
assembly {
stored := sload(slot)
}
}
function _storeStartingGas(uint256 value) private {
bytes32 slot = DELIVERY_SLOT;
assembly {
sstore(slot, value)
}
}
/// @dev True when `abi.decode` reads the data as a `FeeDirector` without a revert: five words, and a recipient word
/// with no bits above 160.
function _hasKnownShape(bytes memory data) private pure returns (bool) {
return data.length >= DIRECTOR_LENGTH && !_hasDirtyRecipientWord(data);
}
/// @dev True when the first word of the data has bits above 160. `abi.decode` reverts on such a word, and the callback
/// must never revert, so the router treats the data as having no known shape.
function _hasDirtyRecipientWord(bytes memory data) private pure returns (bool) {
uint256 firstWord;
assembly {
firstWord := mload(add(data, 32))
}
return firstWord >> 160 != 0;
}
/// @dev The fee, never above the value. Fixed: `limit`. Share: `value * multiplier / 1e18`. Otherwise gas based:
/// the gas used, plus the overhead, times the multiplier and the gas price, with `limit` as the cap.
function _fee(uint256 value, uint256 gasUsed, FeeDirector memory director, uint256 overheadGas)
private
view
returns (uint256 fee)
{
if (director.settings & FIXED_FEE != 0) {
fee = director.limit;
} else if (director.settings & MULTIPLIER_OF_TOTAL != 0) {
fee = value * director.multiplier / 1 ether;
} else {
GasPrice price = director.settings & EXCLUDE_PRIORITY != 0 ? GasPrice.BaseFee : GasPrice.Transaction;
fee = (gasUsed + overheadGas) * director.multiplier * _gasPrice(price) / 1 ether;
if (fee > director.limit) fee = director.limit;
}
if (fee > value) fee = value;
}
function _gasPrice(GasPrice price) private view returns (uint256) {
return price == GasPrice.BaseFee ? block.basefee : tx.gasprice;
}
/// @dev Pays without reverting. Tokens and coins both report whether the payee took them.
function _tryPay(address token, Payout payout, address to, uint256 amount) private returns (bool) {
if (payout == Payout.Token) return IERC20(token).trySafeTransfer(to, amount);
(bool sent,) = to.call{value: amount, gas: NATIVE_SEND_GAS}("");
return sent;
}
/// @dev Pays the recipient as the payout says.
/// @return How the recipient received the amount, or `None` when the router handed it off.
function _payRecipient(address token, Payout payout, address recipient, uint256 amount) private returns (PaidAs) {
if (payout == Payout.Native) return _payNative(recipient, amount);
return _payToken(token, recipient, amount) ? PaidAs.Token : PaidAs.None;
}
/// @dev Sends the unwrapped coin. A receiver that refuses it gets the wrapped token. A receiver that refuses both,
/// and an invalid recipient, cause a hand-off of the wrapped token.
/// @return How the recipient received the amount (the coin or the wrapped token), or `None` after a hand-off.
function _payNative(address recipient, uint256 amount) private returns (PaidAs) {
if (!_canReceive(recipient)) {
wNative.deposit{value: amount}();
_handOff(address(wNative), recipient, amount, Reason.InvalidTerms);
return PaidAs.None;
}
PaidAs paidAs = _trySendNative(recipient, amount);
if (paidAs == PaidAs.None) _handOff(address(wNative), recipient, amount, Reason.PayoutRefused);
return paidAs;
}
/// @dev Sends the coin, and on a refusal wraps it again and sends the wrapped token. When it returns `None` the
/// router holds the amount as the wrapped token.
function _trySendNative(address to, uint256 amount) private returns (PaidAs) {
(bool sent,) = to.call{value: amount, gas: NATIVE_SEND_GAS}("");
if (sent) return PaidAs.Native;
wNative.deposit{value: amount}();
return IERC20(address(wNative)).trySafeTransfer(to, amount) ? PaidAs.Wrapped : PaidAs.None;
}
/// @dev Pays a token. An invalid recipient, or a token that refuses the recipient, causes a hand-off.
/// @return Whether the recipient received the amount.
function _payToken(address token, address recipient, uint256 amount) private returns (bool) {
if (!_canReceive(recipient)) {
_handOff(token, recipient, amount, Reason.InvalidTerms);
return false;
}
if (IERC20(token).trySafeTransfer(recipient, amount)) return true;
_handOff(token, recipient, amount, Reason.PayoutRefused);
return false;
}
/// @dev The legacy form: the receiver gets the coin for the wrapped native token, and the token itself for any
/// other token, with no fee in both cases.
function _payLegacy(address token, address receiver, uint256 value) private {
PaidAs paidAs;
if (token != address(wNative)) {
paidAs = _payToken(token, receiver, value) ? PaidAs.Token : PaidAs.None;
} else {
wNative.withdraw(value);
paidAs = _payNative(receiver, value);
}
if (paidAs != PaidAs.None) _emitDelivered(token, receiver, value, value, paidAs, address(0));
}
/// @dev An account that can own a payout: not the zero address and not the router, which has no way to pay itself.
function _canReceive(address account) private view returns (bool) {
return account != address(0) && account != address(this);
}
/// @dev The amount that this delivery may use: the balance of the router, up to `value`. A token that takes a cut on
/// transfer delivers less than the mediator reports.
function _deliverableAmount(address token, uint256 value) private view returns (uint256) {
uint256 balance = IERC20(token).balanceOf(address(this));
return balance < value ? balance : value;
}
/// @dev Hands an amount that the router could not deliver off to `failedDeliveryAddress`.
function _handOff(address token, address recipient, uint256 amount, Reason reason) private {
if (amount == 0) return;
emit DeliveryFailed(token, recipient, amount, reason);
_push(token, amount);
}
/// @dev Pushes an amount to `failedDeliveryAddress`. When the token refuses the push, the amount stays in the router
/// and the router emits `HandOffRefused`.
/// @return Whether `failedDeliveryAddress` received the amount.
function _push(address token, uint256 amount) private returns (bool) {
if (IERC20(token).trySafeTransfer(failedDeliveryAddress, amount)) return true;
emit HandOffRefused(token, amount);
return false;
}
}
src/hardened/ReceiptLogs.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {RLPReader} from "./vendor/optimism/rlp/RLPReader.sol";
import {
EmptyItem,
UnexpectedString,
InvalidDataRemainder,
ContentLengthMismatch,
InvalidHeader
} from "./vendor/optimism/rlp/RLPErrors.sol";
/// @title ReceiptLogs
/// @notice Finds one item of an RLP list without a fixed limit on the number of items.
/// @dev The vendored `RLPReader.readList` copies at most 32 items and panics on the 33rd. A receipt can hold many more
/// logs, so a deposit in such a transaction could never be withdrawn. This library steps over the items one by one and
/// returns only the item that the caller asks for. The vendored decoder keeps its length helper private, so this library
/// holds its own header decoder. It applies the same rules as the vendored one: a canonical header, no leading zero in a
/// long length, no long form for a short length, and every item inside the bytes that remain. It returns the vendored
/// `RLPItem` type, so the caller decodes the chosen item with the vendored `readList` and `readBytes`.
library ReceiptLogs {
/// @notice Finds the item at `index` of an RLP list.
/// @dev When the index is past the end, the walk reaches the end of the list and `count` holds the number of items.
/// When the item is found, the walk stops there and `count` is zero: the caller must not read it.
/// @param list The RLP list item. It must be a list that fills the whole item.
/// @param index The position of the wanted item.
/// @return found Whether the list holds an item at `index`.
/// @return item The wanted item, with its header. Empty when `found` is false.
/// @return count The number of items in the list when `found` is false.
function itemAt(RLPReader.RLPItem memory list, uint256 index)
internal
pure
returns (bool found, RLPReader.RLPItem memory item, uint256 count)
{
(uint256 listOffset, uint256 listLength, bool isList) = _header(list.ptr, list.length);
if (!isList) revert UnexpectedString();
if (listOffset + listLength != list.length) revert InvalidDataRemainder();
uint256 base = RLPReader.MemoryPointer.unwrap(list.ptr);
uint256 offset = listOffset;
while (offset < list.length) {
RLPReader.MemoryPointer itemPointer = RLPReader.MemoryPointer.wrap(base + offset);
(uint256 itemOffset, uint256 itemLength,) = _header(itemPointer, list.length - offset);
if (count == index) {
return (true, RLPReader.RLPItem({length: itemOffset + itemLength, ptr: itemPointer}), 0);
}
count += 1;
offset += itemOffset + itemLength;
}
return (false, RLPReader.RLPItem({length: 0, ptr: RLPReader.MemoryPointer.wrap(0)}), count);
}
/// @dev Decodes the header of the item at `pointer`, which has `available` bytes left. Returns the header length,
/// the payload length and whether the item is a list. It reverts on every non-canonical or truncated header.
function _header(RLPReader.MemoryPointer pointer, uint256 available)
private
pure
returns (uint256 headerLength, uint256 payloadLength, bool isList)
{
if (available == 0) revert EmptyItem();
uint256 position = RLPReader.MemoryPointer.unwrap(pointer);
uint256 prefix;
uint256 word;
assembly {
word := mload(add(position, 1))
prefix := byte(0, mload(position))
}
if (prefix <= 0x7f) return (0, 1, false);
if (prefix <= 0xb7) return _shortHeader(prefix - 0x80, word, available, false);
if (prefix <= 0xbf) return _longHeader(prefix - 0xb7, word, available, false);
if (prefix <= 0xf7) return _shortHeader(prefix - 0xc0, word, available, true);
return _longHeader(prefix - 0xf7, word, available, true);
}
/// @dev A header whose payload length is in the prefix byte (at most 55).
function _shortHeader(uint256 length, uint256 word, uint256 available, bool isList)
private
pure
returns (uint256, uint256, bool)
{
if (available <= length) revert ContentLengthMismatch();
// A single byte below 0x80 must be written as itself, never behind a prefix.
if (!isList && length == 1 && (word >> 248) < 0x80) revert InvalidHeader();
return (1, length, isList);
}
/// @dev A header whose payload length follows the prefix byte in `lengthOfLength` bytes.
function _longHeader(uint256 lengthOfLength, uint256 word, uint256 available, bool isList)
private
pure
returns (uint256, uint256, bool)
{
if (available <= lengthOfLength) revert ContentLengthMismatch();
if ((word >> 248) == 0) revert InvalidHeader();
uint256 length = word >> (256 - 8 * lengthOfLength);
if (length <= 55) revert InvalidHeader();
if (available <= lengthOfLength + length) revert ContentLengthMismatch();
return (1 + lengthOfLength, length, isList);
}
}
src/hardened/OpeningProofLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {MerkleTrie} from "./vendor/optimism/trie/MerkleTrie.sol";
import {RLPReader} from "./vendor/optimism/rlp/RLPReader.sol";
import {BeaconProofVerifier} from "./BeaconProofVerifier.sol";
/// @title OpeningProofLib
/// @notice The execution layer part of the opening proof of the message bridge (`openDeposits`): the state root of the
/// proven header, the account of the remote light client, and its `executionBlockHashes` entry. All of it is pure.
/// @dev An external library, linked into `MessageBridge`, so that each contract creation of the bridge stays under the
/// per-transaction gas cap of EIP-7825 (16,777,216). It has no owner and no storage, and its address is fixed in the
/// bytecode of the bridge, so the bridge stays immutable. It reverts with the errors of `BeaconProofVerifier`.
library OpeningProofLib {
/// @dev The index of `stateRoot` in the execution block header list.
uint256 internal constant STATE_ROOT_FIELD = 3;
/// @dev The index of `storageRoot` in an account (nonce, balance, storage root, code hash).
uint256 internal constant ACCOUNT_STORAGE_ROOT_FIELD = 2;
/// @dev The storage slot of the mapping `executionBlockHashes` in `BeaconLightClient`.
uint256 internal constant EXECUTION_BLOCK_HASHES_MAPPING_SLOT = 3;
/// @notice Links 2 to 4 of the opening proof, after the caller checked that `remoteHeaderRlp` hashes to the stored
/// block hash: the header holds a state root; under it, the account of `remoteLightClient` holds a storage root;
/// under that, `executionBlockHashes[storedSlot]` is not zero.
function requireOpeningEntry(
bytes calldata remoteHeaderRlp,
bytes[] calldata accountProof,
uint64 storedSlot,
bytes[] calldata storageProof,
address remoteLightClient
) external pure {
bytes32 stateRoot = headerField(remoteHeaderRlp, STATE_ROOT_FIELD);
bytes memory account =
MerkleTrie.get(abi.encodePacked(keccak256(abi.encodePacked(remoteLightClient))), accountProof, stateRoot);
bytes32 storageRoot = accountStorageRoot(account);
bytes memory entry = MerkleTrie.get(
abi.encodePacked(keccak256(abi.encode(executionBlockHashesSlot(storedSlot)))), storageProof, storageRoot
);
if (RLPReader.readBytes(entry).length == 0) revert BeaconProofVerifier.OpeningEntryEmpty(storedSlot);
}
/// @dev The storage slot of `executionBlockHashes[storedSlot]` in the remote light client: the mapping key and the
/// declared slot of the mapping, hashed together.
function executionBlockHashesSlot(uint64 storedSlot) internal pure returns (bytes32) {
return keccak256(abi.encode(uint256(storedSlot), EXECUTION_BLOCK_HASHES_MAPPING_SLOT));
}
/// @dev The 32-byte item at index `field` of an execution block header.
function headerField(bytes calldata headerRlp, uint256 field) internal pure returns (bytes32) {
RLPReader.RLPItem[] memory fields = RLPReader.readList(headerRlp);
if (fields.length <= field) revert BeaconProofVerifier.OpeningProofMalformed();
bytes memory value = RLPReader.readBytes(fields[field]);
if (value.length != 32) revert BeaconProofVerifier.OpeningProofMalformed();
return bytes32(value);
}
/// @dev The storage root of an account, from its RLP: nonce, balance, storage root and code hash.
function accountStorageRoot(bytes memory account) internal pure returns (bytes32) {
RLPReader.RLPItem[] memory fields = RLPReader.readList(account);
if (fields.length != 4) revert BeaconProofVerifier.OpeningProofMalformed();
bytes memory root = RLPReader.readBytes(fields[ACCOUNT_STORAGE_ROOT_FIELD]);
if (root.length != 32) revert BeaconProofVerifier.OpeningProofMalformed();
return bytes32(root);
}
}
src/hardened/mediator/ITokenMediator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IOmnibridge} from "./IOmnibridge.sol";
import {IAMB} from "../IAMB.sol";
/// @title ITokenMediator
/// @notice The functions of `TokenMediator` that the routers call. `relayTokens` is the OmniBridge function.
/// `relayTokensAndCall` takes one more argument than in OmniBridge: the gas of the callback, which the sender states
/// because there is no default.
interface ITokenMediator is IOmnibridge {
/// @notice Relays tokens of the caller to `receiver` and calls `onTokenBridged` on it on the other chain with exactly
/// `callbackGas`. Zero reverts.
/// @param callbackGas The gas of the callback on the other chain. The delivery reverts when it cannot give that
/// gas, and records `CallbackFailed` when the callback fails with it.
function relayTokensAndCall(address token, address receiver, uint256 value, bytes calldata data, uint256 callbackGas)
external;
function bridgeContract() external view returns (IAMB);
}
src/hardened/SSZ.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice A beacon block header, as in the consensus specification.
struct BeaconBlockHeader {
uint64 slot;
uint64 proposerIndex;
bytes32 parentRoot;
bytes32 stateRoot;
bytes32 bodyRoot;
}
/// @title SSZ
/// @notice The small part of SimpleSerialize that the bridge needs: the hash tree root of a
/// `BeaconBlockHeader`, and the check of a Merkle branch by generalized index.
/// @dev Every hash is SHA-256 through the precompile at address 0x02, which exists on Ethereum and PulseChain.
/// The compiler emits a call to that precompile for `sha256`.
library SSZ {
/// @notice The branch length differs from the depth of the generalized index.
error BranchLengthMismatch(uint256 expected, uint256 actual);
/// @notice The generalized index is zero.
error ZeroGeneralizedIndex();
/// @notice The hash tree root of a beacon block header: five leaves padded to eight.
/// @param header The header.
function hashTreeRoot(BeaconBlockHeader calldata header) internal pure returns (bytes32) {
bytes32 left = _hashPair(
_hashPair(_uint64Leaf(header.slot), _uint64Leaf(header.proposerIndex)),
_hashPair(header.parentRoot, header.stateRoot)
);
bytes32 right = _hashPair(_hashPair(header.bodyRoot, bytes32(0)), _hashPair(bytes32(0), bytes32(0)));
return _hashPair(left, right);
}
/// @notice The hash tree root of a header held in memory.
/// @param header The header.
function hashTreeRootMemory(BeaconBlockHeader memory header) internal pure returns (bytes32) {
bytes32 left = _hashPair(
_hashPair(_uint64Leaf(header.slot), _uint64Leaf(header.proposerIndex)),
_hashPair(header.parentRoot, header.stateRoot)
);
bytes32 right = _hashPair(_hashPair(header.bodyRoot, bytes32(0)), _hashPair(bytes32(0), bytes32(0)));
return _hashPair(left, right);
}
/// @notice Checks that `leaf` sits at `generalizedIndex` under `root`, given the sibling hashes from leaf to root.
/// @dev The branch length must equal the depth of the index, which fixes the tree shape. A branch of another
/// length is an error, not a failed check, so a wrong fork row shows up as a clear revert.
/// @param leaf The leaf value.
/// @param branch The siblings, deepest first.
/// @param generalizedIndex The generalized index of the leaf.
/// @param root The expected root.
function isValidBranch(bytes32 leaf, bytes32[] calldata branch, uint256 generalizedIndex, bytes32 root)
internal
pure
returns (bool)
{
uint256 depth = depthOf(generalizedIndex);
if (branch.length != depth) revert BranchLengthMismatch(depth, branch.length);
bytes32 value = leaf;
for (uint256 level = 0; level < depth; level++) {
bool nodeIsRight = (generalizedIndex >> level) & 1 == 1;
value = nodeIsRight ? _hashPair(branch[level], value) : _hashPair(value, branch[level]);
}
return value == root;
}
/// @notice The same check for a branch held in memory, for evidence that the caller decoded from `bytes`.
/// @param leaf The leaf value.
/// @param branch The siblings, deepest first.
/// @param generalizedIndex The generalized index of the leaf.
/// @param root The expected root.
function isValidBranchMemory(bytes32 leaf, bytes32[] memory branch, uint256 generalizedIndex, bytes32 root)
internal
pure
returns (bool)
{
uint256 depth = depthOf(generalizedIndex);
if (branch.length != depth) revert BranchLengthMismatch(depth, branch.length);
bytes32 value = leaf;
for (uint256 level = 0; level < depth; level++) {
bool nodeIsRight = (generalizedIndex >> level) & 1 == 1;
value = nodeIsRight ? _hashPair(branch[level], value) : _hashPair(value, branch[level]);
}
return value == root;
}
/// @notice The depth of a generalized index: the number of bits below the leading one.
/// @param generalizedIndex The index. It must not be zero.
function depthOf(uint256 generalizedIndex) internal pure returns (uint256 depth) {
if (generalizedIndex == 0) revert ZeroGeneralizedIndex();
while (generalizedIndex > 1) {
generalizedIndex >>= 1;
depth++;
}
}
/// @dev A uint64 leaf is the little-endian bytes of the value, padded on the right with zeros.
function _uint64Leaf(uint64 value) private pure returns (bytes32) {
uint64 swapped = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8);
swapped = ((swapped & 0xFFFF0000FFFF0000) >> 16) | ((swapped & 0x0000FFFF0000FFFF) << 16);
swapped = (swapped >> 32) | (swapped << 32);
return bytes32(uint256(swapped) << 192);
}
function _hashPair(bytes32 left, bytes32 right) private pure returns (bytes32) {
return sha256(abi.encodePacked(left, right));
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
src/hardened/MessageBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IDepositGate} from "./IDepositGate.sol";
import {BeaconBlockHeader} from "./SSZ.sol";
import {BeaconProofVerifier} from "./BeaconProofVerifier.sol";
import {ReceiptProofLib} from "./ReceiptProofLib.sol";
import {AmbMessageCodec} from "./AmbMessageCodec.sol";
import {IAMB} from "./IAMB.sol";
/// @title MessageBridge
/// @notice One end of a two-chain message bridge with the interface of the OmniBridge Arbitrary Message Bridge. A
/// contract sends a message with `requireToPassMessage`. Anyone proves the message on the other chain with
/// `executeMessage`, and the bridge calls the target. The light client and the proof replace the validators of
/// OmniBridge. The bridge has no owner, no executor fee, no refund and no upgrade path.
/// @dev Sending. `requireToPassMessage` and `requireToConfirmMessage` emit `UserRequestForAffirmation` with the message
/// encoding of `AmbMessageCodec`, which is the OmniBridge encoding unchanged. There is no manual lane, so both calls
/// differ only in the data type byte of the message. A send first needs the deposit lock open, then the fork gate
/// admits it (with empty evidence: a keeper confirms the epoch with `BeaconForkGate.confirm`).
///
/// Delivery. `executeMessage` checks a proof of the log, in this order: the anchor, the ancestry, the block hash, the
/// execution header, the receipt (which must record success), the transaction at the same index, the log (emitter and
/// topic) and the message (identifier, version, chains and data type). A message executes once, and only a call
/// that succeeds counts: when the call to the target fails, `executeMessage` reverts with the error of the target, and
/// the message stays `NotDelivered`, so anyone can deliver it again later, with more gas or after the target changed
/// its mind. Messages are independent: the nonce of the sender only makes identifiers unique, and no order exists
/// between messages.
///
/// Gas. A message carries no gas number that the bridge reads. The target gets all the gas that is left (the EVM
/// keeps back one 64th), and if that is not enough the call fails and the delivery reverts. So an executor that gives
/// too little gas loses only its own transaction: it cannot make a message fail for good. The gas field of the
/// OmniBridge encoding stays in the message, always zero, so the encoding keeps its layout. A target that needs a
/// guarantee for a call of its own (a callback, a follow-up call) states the gas of that call in its own data and
/// checks it itself: the bridge knows nothing about the target.
///
/// The context (`messageSender`, `messageId`, `messageSourceChainId`, `transactionHash`) is set during the call to the
/// target and cleared after it. A target trusts a message by checking `msg.sender == bridge` and the pair
/// (`messageSourceChainId()`, `messageSender()`). While a message executes, another `executeMessage` is refused,
/// because it would overwrite the context. A target may send messages meanwhile: sends do not touch the context.
contract MessageBridge is BeaconProofVerifier, IAMB {
/// @notice The terms at deployment: the cutoff and the remote light client.
/// @param cutoffTimestamp Sends revert from this timestamp on. Zero means no cutoff.
/// @param remoteLightClient The light client on the other chain, which tracks the beacon chain of THIS chain and
/// feeds the remote bridge. `openDeposits` reads its storage. It must not be zero.
/// @dev No fork slot is a term: each proof carries the fork proof of its source state (`MessageProof.sourceFork`).
struct BridgeTerms {
uint64 cutoffTimestamp;
address remoteLightClient;
}
/// @notice The evidence for one message. Nothing in it is secret.
/// @param anchorHeader A stored finalized header. Its root must equal `lightClient.headers(slot)`.
/// @param sourceHeader The beacon block that carries the execution block of the sending transaction.
/// @param ancestryBranch The branch from the root of `sourceHeader` to the state root of `anchorHeader`.
/// @param blockHashBranch The branch from the execution block hash to the body root of `sourceHeader`.
/// @param sourceFork The fork proof of the state of `sourceHeader` (under `sourceHeader.stateRoot`). Its proven shape
/// picks the block hash rule: plain takes the payload layout, progressive (Gloas on) takes the bid parent hash.
/// @param executionHeaderRlp The RLP of the execution block header. Its hash must be the proven block hash.
/// @param receiptProof The trie nodes from the receipts root to the receipt.
/// @param receiptIndex The index of the transaction in the block. It is the trie key of the receipt.
/// @param transactionProof The trie nodes from the transactions root to the transaction.
/// @param transactionIndex The trie key of the transaction. It must equal `receiptIndex`.
/// @param logIndex The index of the `UserRequestForAffirmation` log inside the receipt.
struct MessageProof {
BeaconBlockHeader anchorHeader;
BeaconBlockHeader sourceHeader;
bytes32[] ancestryBranch;
bytes32[] blockHashBranch;
ForkProof sourceFork;
bytes executionHeaderRlp;
bytes[] receiptProof;
uint256 receiptIndex;
bytes[] transactionProof;
uint256 transactionIndex;
uint256 logIndex;
}
/// @notice The state of a message on this chain. A message that was never delivered, or whose every delivery
/// reverted, is `NotDelivered`.
/// @dev `InProgress` lasts only inside the call to the target. It is the mark that the bridge sets before the call.
/// There is no failed state: a failed call reverts the delivery.
enum DeliveryStatus {
NotDelivered,
InProgress,
Succeeded
}
/// @notice The topic 0 of `UserRequestForAffirmation`. A message proof matches logs against this value.
/// @dev Solidity 0.8.28 rejects `UserRequestForAffirmation.selector` in a constant. A test pins this value.
bytes32 public constant USER_REQUEST_TOPIC = keccak256("UserRequestForAffirmation(bytes32,bytes)");
/// @dev The call data types that this bridge sends and accepts.
uint8 private constant DATA_TYPE_PASS = AmbMessageCodec.DATA_TYPE_PASS;
uint8 private constant DATA_TYPE_CONFIRM = AmbMessageCodec.DATA_TYPE_CONFIRM;
/// @dev OmniBridge refuses a message whose call data starts with one of these selectors, so that the bridge cannot
/// be made to move tokens of a contract that approved it: `transfer(address,uint256)`,
/// `approve(address,uint256)`, `transferFrom(address,address,uint256)`, `approveAndCall(address,uint256,bytes)` and
/// `transferAndCall(address,uint256,bytes)`.
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
bytes4 private constant APPROVE_SELECTOR = 0x095ea7b3;
bytes4 private constant TRANSFER_FROM_SELECTOR = 0x23b872dd;
bytes4 private constant TRANSFER_AND_CALL_SELECTOR = 0x4000aea0;
bytes4 private constant APPROVE_AND_CALL_SELECTOR = 0xcae9ca51;
/// @notice The call data starts with a selector that the bridge never forwards.
error ForbiddenSelector(bytes4 selector);
/// @notice Sends are closed because the cutoff time passed.
error SendCutoffReached(uint64 cutoff);
/// @notice A message is executing. Another `executeMessage` would overwrite its context.
error MessageInProgress(bytes32 messageId);
/// @notice The receipt index and the transaction index of the proof differ.
error IndexMismatch(uint256 receiptIndex, uint256 transactionIndex);
/// @notice The log event data is not the encoding of one `bytes` value.
error MalformedEventData();
/// @notice The topic holds another message identifier than the message.
error MessageIdMismatch(bytes32 topicMessageId, bytes32 encodedMessageId);
/// @notice The message identifier has another format version than this bridge reads.
error MessageVersionInvalid(bytes32 messageId);
/// @notice The message has a data type that this bridge does not send.
error UnknownDataType(uint8 dataType);
/// @notice The message names another source chain than the remote chain.
error WrongSourceChain(uint64 expected, uint256 actual);
/// @notice The message names another destination chain than this chain.
error WrongDestinationChain(uint64 expected, uint256 actual);
/// @notice The message was already delivered.
error AlreadyDelivered(bytes32 messageId);
/// @notice The call to the target failed and returned no error of its own (for example, it ran out of gas). The
/// message stays `NotDelivered`.
error TargetCallFailed(bytes32 messageId);
/// @notice The identifier of this chain: `block.chainid` at deployment.
uint64 public immutable localChainId;
/// @notice The identifier of the other chain.
uint64 public immutable remoteChainId;
/// @notice The bridge on the other chain.
address public immutable remoteBridge;
/// @notice Sends revert at and after this timestamp. Zero disables the cutoff. Set it at deployment only when a
/// breaking fork of the other chain is already scheduled.
uint64 public immutable sendCutoffTimestamp;
/// @notice The gate that every send calls. It refuses a send that the route cannot deliver.
IDepositGate public immutable depositGate;
/// @dev The version and the bridge part of every message identifier of this bridge.
bytes32 private immutable messageIdPrefix;
// The nonce, the flag and the sender of the context share one storage word.
/// @dev The number of messages sent. It feeds the identifier.
uint64 private _nonce;
/// @notice Whether sends are open. It starts false and `openDeposits` sets it true for good.
bool public depositsOpen;
/// @dev The sender of the message that executes now. Zero outside the call to the target.
address private _activeSender;
/// @dev The identifier of the message that executes now. Zero outside the call to the target.
bytes32 private _activeMessageId;
/// @dev The source transaction hash of the message that executes now. Zero outside the call to the target.
bytes32 private _activeTransactionHash;
mapping(bytes32 messageId => DeliveryStatus) private _deliveries;
/// @dev The `block_roots`, block hash and `historical_summaries` layout tables, in the slots that three separate
/// arrays had before (`BeaconProofVerifier.LayoutTables`).
LayoutTables private _layouts;
/// @param lightClient_ The light client of the remote chain.
/// @param remoteChainId_ The identifier of the other chain.
/// @param remoteBridge_ The bridge on the other chain.
/// @param bridgeTerms The send cutoff and the remote light client. See `BridgeTerms`.
/// @param capellaEra_ `floor(capellaForkSlot / 8192)` of the remote chain. The deploy script checks it.
/// @param depositGate_ The gate that every send calls. It must not be the zero address.
constructor(
address lightClient_,
uint64 remoteChainId_,
address remoteBridge_,
BridgeTerms memory bridgeTerms,
uint64 capellaEra_,
address depositGate_
) BeaconProofVerifier(lightClient_, capellaEra_, bridgeTerms.remoteLightClient) {
if (lightClient_ == address(0)) revert ZeroValue("lightClient");
if (remoteChainId_ == 0) revert ZeroValue("remoteChainId");
if (remoteBridge_ == address(0)) revert ZeroValue("remoteBridge");
if (depositGate_ == address(0)) revert ZeroValue("depositGate");
if (bridgeTerms.remoteLightClient == address(0)) revert ZeroValue("remoteLightClient");
uint64 localChainId_ = uint64(block.chainid);
if (remoteChainId_ == localChainId_) revert RemoteChainIsLocalChain();
localChainId = localChainId_;
remoteChainId = remoteChainId_;
remoteBridge = remoteBridge_;
sendCutoffTimestamp = bridgeTerms.cutoffTimestamp;
depositGate = IDepositGate(depositGate_);
messageIdPrefix = AmbMessageCodec.messageIdPrefix(localChainId_, address(this));
}
// ------------------------------------------------------------------ sending
/// @inheritdoc IAMB
/// @dev `_gas` is accepted for the OmniBridge interface and ignored: delivery gives the target all the gas that is
/// left, and the gas field of the message is zero.
function requireToPassMessage(address _contract, bytes calldata _data, uint256)
external
override
returns (bytes32)
{
return _send(_contract, _data, DATA_TYPE_PASS);
}
/// @inheritdoc IAMB
/// @dev The same as `requireToPassMessage`, with the data type of the manual lane. This bridge has no manual lane.
function requireToConfirmMessage(address _contract, bytes calldata _data, uint256)
external
override
returns (bytes32)
{
return _send(_contract, _data, DATA_TYPE_CONFIRM);
}
/// @dev The checks run in this order: the lock, the cutoff, the selector, the gate. The nonce moves before the gate
/// call, so a gate that calls back cannot cause a repeated identifier. There is no gas check: the gas argument of
/// the interface is not used.
function _send(address target, bytes calldata data, uint8 dataType) private returns (bytes32 id) {
if (!depositsOpen) revert DepositsNotOpen();
if (sendCutoffTimestamp != 0 && block.timestamp >= sendCutoffTimestamp) {
revert SendCutoffReached(sendCutoffTimestamp);
}
_requireForwardableSelector(data);
uint64 nonce = _nonce;
_nonce = nonce + 1;
depositGate.admit("");
id = messageIdPrefix | bytes32(uint256(nonce));
AmbMessageCodec.Header memory header = AmbMessageCodec.Header({
messageId: id,
sender: msg.sender,
executor: target,
gasLimit: 0,
dataType: dataType,
sourceChainId: localChainId,
destinationChainId: remoteChainId
});
emit UserRequestForAffirmation(id, AmbMessageCodec.encode(header, data));
}
/// @dev Reverts when the call data starts with a selector of a token transfer or approval.
function _requireForwardableSelector(bytes calldata data) private pure {
if (data.length < 4) return;
bytes4 selector = bytes4(data[:4]);
if (
selector == TRANSFER_SELECTOR || selector == APPROVE_SELECTOR || selector == TRANSFER_FROM_SELECTOR
|| selector == TRANSFER_AND_CALL_SELECTOR || selector == APPROVE_AND_CALL_SELECTOR
) {
revert ForbiddenSelector(selector);
}
}
// ------------------------------------------------------------------ delivery
/// @notice Delivers a message that a bridge on the other chain sent, given direct evidence. Anyone may call it.
/// @dev A message executes once, with the target and data that the sender fixed, so an executor that runs ahead of
/// another does no harm. The executor pays the gas and gets no fee from the bridge. When the call to the target
/// fails, the delivery reverts with the error of the target (or `TargetCallFailed` when the target returned none),
/// and the message stays `NotDelivered`.
/// @param proof The evidence.
function executeMessage(MessageProof calldata proof) external {
if (_activeMessageId != bytes32(0)) revert MessageInProgress(_activeMessageId);
if (proof.receiptIndex != proof.transactionIndex) {
revert IndexMismatch(proof.receiptIndex, proof.transactionIndex);
}
(bytes memory encoded, bytes32 topicMessageId, bytes32 sourceTransactionHash) = _provenLog(proof);
(AmbMessageCodec.Header memory header, bytes memory data) = AmbMessageCodec.decode(encoded);
_requireAcceptableMessage(header, topicMessageId);
if (_deliveries[header.messageId] != DeliveryStatus.NotDelivered) revert AlreadyDelivered(header.messageId);
_deliveries[header.messageId] = DeliveryStatus.InProgress;
_callTarget(header, data, sourceTransactionHash);
_deliveries[header.messageId] = DeliveryStatus.Succeeded;
emit AffirmationCompleted(header.sender, header.executor, header.messageId, true);
}
/// @dev Checks 1 to 7 and the log, and returns the encoded message of the log, the identifier in its topic and the
/// hash of the transaction. The identifier in the topic and the one in the message are two copies of the same value.
/// Checks 1 to 4 run here; the execution header, the receipt, the transaction and the log run in
/// `ReceiptProofLib.provenLog`, under the block hash proven here.
function _provenLog(MessageProof calldata proof)
private
view
returns (bytes memory encoded, bytes32 topicMessageId, bytes32 sourceTransactionHash)
{
_requireAncestry(proof.anchorHeader, proof.sourceHeader, proof.ancestryBranch);
_requireBlockHashBranch(
keccak256(proof.executionHeaderRlp), proof.sourceHeader, proof.blockHashBranch, proof.sourceFork
);
(topicMessageId, encoded, sourceTransactionHash) = ReceiptProofLib.provenLog(
proof.executionHeaderRlp,
proof.receiptProof,
proof.receiptIndex,
proof.transactionProof,
proof.logIndex,
remoteBridge,
USER_REQUEST_TOPIC
);
}
/// @dev Checks the message against the log and this bridge.
function _requireAcceptableMessage(AmbMessageCodec.Header memory header, bytes32 topicMessageId) private view {
if (header.messageId != topicMessageId) revert MessageIdMismatch(topicMessageId, header.messageId);
if (!AmbMessageCodec.hasValidVersion(header.messageId)) revert MessageVersionInvalid(header.messageId);
if (header.sourceChainId != remoteChainId) revert WrongSourceChain(remoteChainId, header.sourceChainId);
if (header.destinationChainId != localChainId) {
revert WrongDestinationChain(localChainId, header.destinationChainId);
}
if (header.dataType != DATA_TYPE_PASS && header.dataType != DATA_TYPE_CONFIRM) {
revert UnknownDataType(header.dataType);
}
}
/// @dev Sets the context, calls the target with all the gas that is left, and clears the context. A failed call
/// reverts the delivery with the error data of the target. A successful call copies no return data, so a target
/// cannot cost gas with a large answer. The error data of a failed call is copied, at the cost of the delivery that
/// reverts anyway.
function _callTarget(AmbMessageCodec.Header memory header, bytes memory data, bytes32 sourceTransactionHash)
private
{
_activeSender = header.sender;
_activeMessageId = header.messageId;
_activeTransactionHash = sourceTransactionHash;
address target = header.executor;
bool success;
assembly {
success := call(gas(), target, 0, add(data, 32), mload(data), 0, 0)
}
if (!success) _bubble(header.messageId);
_activeSender = address(0);
_activeMessageId = bytes32(0);
_activeTransactionHash = bytes32(0);
}
/// @dev Reverts with the error data of the call that just failed, or with `TargetCallFailed` when it has none.
function _bubble(bytes32 id) private pure {
assembly ("memory-safe") {
let size := returndatasize()
if size {
let pointer := mload(0x40)
returndatacopy(pointer, 0, size)
revert(pointer, size)
}
}
revert TargetCallFailed(id);
}
// ------------------------------------------------------------------ the lock
/// @notice Opens sends for good, given proof that the remote light client has stored a head.
/// @dev A message sent at slot `s` is delivered only if some block hash row covers `s`. A row starts at a stored
/// head that has an execution block hash, and the constructor of the light client stores none. So a message sent
/// before the remote light client stored its first update is lost for ever. `_verifyOpening` checks the proof.
/// After the call, the flag stays true. The call needs no key. A call after the opening returns at once, so two
/// openers do not fail each other.
/// @param proof The evidence.
function openDeposits(OpeningProof calldata proof) external {
if (depositsOpen) return;
bytes32 blockHash = _verifyOpening(proof);
depositsOpen = true;
emit DepositsOpened(proof.remoteSlot, blockHash, proof.storedSlot);
}
// ------------------------------------------------------------------ context and views
/// @inheritdoc IAMB
function messageSender() external view override returns (address) {
return _activeSender;
}
/// @inheritdoc IAMB
function messageId() external view override returns (bytes32) {
return _activeMessageId;
}
/// @inheritdoc IAMB
/// @dev The proven transaction hash of the source chain: the hash of the transaction at the index of the receipt.
function transactionHash() external view override returns (bytes32) {
return _activeTransactionHash;
}
/// @inheritdoc IAMB
/// @dev The source chain is always the remote chain, so the value follows the context: it is zero when no message
/// executes.
function messageSourceChainId() external view override returns (bytes32) {
if (_activeMessageId == bytes32(0)) return bytes32(0);
return bytes32(uint256(remoteChainId));
}
/// @inheritdoc IAMB
/// @dev True once the message was delivered. A delivery whose call fails reverts, so there is no false after an
/// attempt: false means not delivered yet.
function messageCallStatus(bytes32 id) external view override returns (bool) {
return _deliveries[id] == DeliveryStatus.Succeeded;
}
/// @notice The state of a message on this chain.
/// @param id The message identifier.
function deliveryStatus(bytes32 id) external view returns (DeliveryStatus) {
return _deliveries[id];
}
/// @inheritdoc IAMB
/// @dev Always zero: no message ends as a failure on this bridge. Kept for the OmniBridge interface.
function failedMessageDataHash(bytes32) external pure override returns (bytes32) {
return bytes32(0);
}
/// @inheritdoc IAMB
/// @dev Always zero, as `failedMessageDataHash`.
function failedMessageReceiver(bytes32) external pure override returns (address) {
return address(0);
}
/// @inheritdoc IAMB
/// @dev Always zero, as `failedMessageDataHash`.
function failedMessageSender(bytes32) external pure override returns (address) {
return address(0);
}
/// @inheritdoc IAMB
/// @dev The bridge has no gas ceiling for a message: delivery gives the target all the gas that is left. It answers
/// the largest value that the gas field of the encoding can hold, so that an OmniBridge sender that checks its gas
/// against this value passes.
function maxGasPerTx() external pure override returns (uint256) {
return type(uint32).max;
}
/// @inheritdoc IAMB
function sourceChainId() external view override returns (uint256) {
return localChainId;
}
/// @inheritdoc IAMB
function destinationChainId() external view override returns (uint256) {
return remoteChainId;
}
// ------------------------------------------------------------------ storage hook
function _layoutTables() internal view override returns (LayoutTables storage) {
return _layouts;
}
}
src/hardened/mediator/IOmnibridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IOmnibridge
/// @notice The one function of the OmniBridge mediator that the routers of OmniBridge call.
interface IOmnibridge {
function relayTokens(address token, address receiver, uint256 value) external;
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
src/hardened/IAMB.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IAMB
/// @notice The Arbitrary Message Bridge interface, as OmniBridge defines it (`omni/omnibridge`,
/// `contracts/interfaces/IAMB.sol`). `MessageBridge` implements it and adds `executeMessage`. The mediator codes
/// against this interface only and never calls `executeMessage`.
/// @dev `UserRequestForSignature` and `RelayedMessage` stay in the interface for compatibility. A bridge without
/// validators never emits them.
interface IAMB {
/// @notice Emitted by every send. `encodedData` is the Arbitrary Message Bridge message encoding.
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
/// @notice Never emitted by a bridge without validators.
event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData);
/// @notice Emitted on every execution of a message. `MessageBridge` emits it only for a delivery that succeeded: a
/// delivery whose call fails reverts. So `status` is always true there.
event AffirmationCompleted(
address indexed sender, address indexed executor, bytes32 indexed messageId, bool status
);
/// @notice Never emitted by a bridge without validators.
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
/// @notice The sender of the message on the other chain. Set only during the call to the target.
function messageSender() external view returns (address);
/// @notice The ceiling of the gas that a message may ask for. `MessageBridge` reads no gas from a message and answers
/// the width of the gas field.
function maxGasPerTx() external view returns (uint256);
/// @notice The source transaction hash of the message. Set only during the call to the target.
function transactionHash() external view returns (bytes32);
/// @notice The identifier of the message. Set only during the call to the target.
function messageId() external view returns (bytes32);
/// @notice The identifier of the chain that sent the message. Set only during the call to the target.
function messageSourceChainId() external view returns (bytes32);
/// @notice Whether the call to the target of a message succeeded. On `MessageBridge`: whether the message was
/// delivered.
function messageCallStatus(bytes32 _messageId) external view returns (bool);
/// @notice The hash of the data of a message whose call failed. Always zero on `MessageBridge`, where a failed call
/// reverts the delivery.
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
/// @notice The target of a message whose call failed.
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
/// @notice The sender of a message whose call failed.
function failedMessageSender(bytes32 _messageId) external view returns (address);
/// @notice Sends a message to `_contract` on the other chain.
/// @param _contract The target on the other chain.
/// @param _data The call data.
/// @param _gas The gas that the call to the target gets. `MessageBridge` ignores it: the target gets all the gas of
/// the delivery.
/// @return The message identifier.
function requireToPassMessage(address _contract, bytes calldata _data, uint256 _gas) external returns (bytes32);
/// @notice The same as `requireToPassMessage`. This bridge has no separate manual lane.
function requireToConfirmMessage(address _contract, bytes calldata _data, uint256 _gas) external returns (bytes32);
/// @notice The identifier of this chain.
function sourceChainId() external view returns (uint256);
/// @notice The identifier of the other chain.
function destinationChainId() external view returns (uint256);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
src/hardened/IDepositGate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IDepositGate
/// @notice A check that the vault runs first in `deposit`. A gate that reverts refuses the deposit.
interface IDepositGate {
/// @notice Admits a deposit, or reverts.
/// @param evidence Gate-specific evidence. The vault passes the `gateEvidence` of the deposit unchanged.
function admit(bytes calldata evidence) external;
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
src/hardened/IBeaconLightClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IBeaconLightClient
/// @notice The part of the light client that the vault reads.
interface IBeaconLightClient {
/// @notice The finalized beacon header root stored for a slot, or zero.
/// @param slot The beacon slot.
function headers(uint64 slot) external view returns (bytes32);
/// @notice The execution block hash stored for the head at a slot, or zero.
/// @param slot The beacon slot.
function executionBlockHashes(uint64 slot) external view returns (bytes32);
/// @notice Whether the execution block hash sits in a finalized beacon header.
/// @param blockHash The execution block hash.
function isFinalizedExecutionBlock(bytes32 blockHash) external view returns (bool);
/// @notice The genesis validators root of the tracked chain. A fork proof of a state of that chain must prove it.
function genesisValidatorsRoot() external view returns (bytes32);
}
src/hardened/BeaconLayoutLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IBeaconLightClient} from "./IBeaconLightClient.sol";
import {BeaconBlockHeader, SSZ} from "./SSZ.sol";
import {BeaconProofVerifier} from "./BeaconProofVerifier.sol";
import {ForkShape} from "./ForkShape.sol";
/// @dev The era constants, one copy for this library and the public constants of `BeaconProofVerifier`:
/// `SLOTS_PER_HISTORICAL_ROOT`, its log2, and the log2 of `HISTORICAL_ROOTS_LIMIT` (2**24).
uint64 constant ERA_SLOTS = 8192;
uint256 constant ERA_DEPTH = 13;
uint256 constant HISTORICAL_LIST_DEPTH = 24;
/// @title BeaconLayoutLib
/// @notice The fork layout tables of the message bridge: the position rules and the evidence checks of
/// `addBlockRootsLayout`, `addBlockHashLayout` and `addHistoricalSummariesLayout`, the range rule, and the lookups that
/// turn a slot into the validated position of its fork. The rules are documented on `BeaconProofVerifier`.
/// @dev An external library, linked into `MessageBridge`, so that each contract creation of the bridge stays under the
/// per-transaction gas cap of EIP-7825 (16,777,216). It runs with DELEGATECALL in the storage of the bridge: the tables
/// are `storage` arguments that the bridge passes, so they stay in the storage layout of the bridge. It has no owner and
/// no storage of its own, and its address is fixed in the bytecode of the bridge, so the bridge stays immutable. It reverts
/// with the errors of `BeaconProofVerifier` and emits its events, so the bridge looks the same from outside.
library BeaconLayoutLib {
/// @dev The deepest accepted `block_roots` or `historical_summaries` position (the state container only), apart from
/// the fixed Gloas position of `historical_summaries`.
uint256 private constant MAX_BLOCK_ROOTS_DEPTH = 8;
/// @dev The position of `BeaconState.block_roots` in the progressive Gloas state: field 5 is chunk 5, the first leaf of
/// the 16 leaf subtree at node 22, which starts at 352 (`specs/gloas/light-client/sync-protocol.md` fixes the rules,
/// and `lc-core` derives the number from the field list).
uint256 private constant GLOAS_BLOCK_ROOTS_GINDEX = 352;
/// @dev The position of `signed_execution_payload_bid.message.parent_block_hash` in the progressive Gloas
/// `BeaconBlockBody`: field 10 of the body is node 357, `message` is 714, the bid is progressive and its first chunk
/// `parent_block_hash` is 714 * 4 = 2856 (`specs/gloas/light-client/sync-protocol.md`, `EXECUTION_BLOCK_HASH_GINDEX_GLOAS`).
/// The branch has 11 entries. The position is fixed by the progressive layout, so no layout evidence names it.
///
/// The rule for a message source whose state the fork proof shows to be progressive: the source header is a beacon
/// block B AFTER the block of the proven execution block X, and `parent_block_hash` of B equals the hash of X. Why it is
/// sound:
/// `process_execution_payload_bid` asserts `bid.parent_block_hash == state.latest_block_hash`, and `latest_block_hash` is
/// written only by `apply_parent_execution_payload`, from the bid of a parent whose payload the child confirmed. So the
/// `parent_block_hash` of a block of the canonical chain names a payload that the chain accepted. A block on an empty
/// parent names an older accepted payload, which is canonical too. The bid's own `block_hash` is never accepted: that
/// payload may be withheld. B must be an ancestor of the stored head, which the ancestry branch proves.
uint256 private constant GLOAS_BID_PARENT_BLOCK_HASH_GINDEX = 2856;
/// @dev The position of `BeaconState.historical_summaries` in the progressive Gloas state: field 27 is chunk 27, the
/// seventh leaf of the 64 leaf subtree at node 46, which starts at 2944.
uint256 private constant GLOAS_HISTORICAL_SUMMARIES_GINDEX = 2950;
/// @dev The deepest accepted block hash position.
uint256 private constant MAX_BLOCK_HASH_DEPTH = 16;
/// @dev The index of `BeaconState.block_roots` among the state fields.
uint256 private constant BLOCK_ROOTS_FIELD = 5;
/// @dev The index of `BeaconState.historical_summaries` among the state fields (Capella through Fulu).
uint256 private constant HISTORICAL_SUMMARIES_FIELD = 27;
/// @dev The index of `execution_payload` among the `BeaconBlockBody` fields (Capella through Fulu).
uint256 private constant EXECUTION_PAYLOAD_FIELD = 9;
/// @dev The index of `block_hash` among the `ExecutionPayload` fields (Capella through Fulu).
uint256 private constant BLOCK_HASH_FIELD = 12;
// The accepted depths of the `BeaconState` tree are the plain shapes of `ForkShape.allowedShapes` (5, 6 and 7: 32, 64
// or 128 leaves), and the fixed Gloas positions count only while `ForkShape.PROGRESSIVE` is allowed. No second list.
/// @dev The accepted depths of the `BeaconBlockBody` tree (16 or 32 leaves) and of the `ExecutionPayload` tree
/// (16 or 32 leaves).
uint256 private constant MIN_BODY_DEPTH = 4;
uint256 private constant MAX_BODY_DEPTH = 5;
uint256 private constant MIN_PAYLOAD_DEPTH = 4;
uint256 private constant MAX_PAYLOAD_DEPTH = 5;
uint64 private constant SLOTS_PER_HISTORICAL_ROOT = ERA_SLOTS;
uint256 private constant BLOCK_ROOTS_VECTOR_DEPTH = ERA_DEPTH;
uint256 private constant HISTORICAL_SUMMARIES_LIST_DEPTH = HISTORICAL_LIST_DEPTH;
// ------------------------------------------------------------------ adding layouts
/// @notice The body of `BeaconProofVerifier.addBlockRootsLayout`.
function addBlockRootsLayout(
BeaconProofVerifier.SlotRange[] storage table,
IBeaconLightClient lightClient,
uint256 blockRootsGindex,
BeaconProofVerifier.BlockRootsEvidence calldata evidence
) external {
if (blockRootsGindex == 0 || SSZ.depthOf(blockRootsGindex) > MAX_BLOCK_ROOTS_DEPTH) {
revert BeaconProofVerifier.LayoutOutOfBounds(blockRootsGindex);
}
if (!_isBlockRootsPosition(blockRootsGindex)) {
revert BeaconProofVerifier.LayoutPositionInvalid(blockRootsGindex);
}
_requireStoredHeader(lightClient, evidence.laterHeader);
if (evidence.earlierSlotA == evidence.earlierSlotB) {
revert BeaconProofVerifier.EvidenceSlotsEqual(evidence.earlierSlotA);
}
_requireEarlierRoot(
lightClient, evidence.laterHeader, evidence.earlierSlotA, blockRootsGindex, evidence.branchA
);
_requireEarlierRoot(
lightClient, evidence.laterHeader, evidence.earlierSlotB, blockRootsGindex, evidence.branchB
);
(uint64 firstSlot, uint64 lastSlot) = _record(table, blockRootsGindex, evidence.laterHeader.slot);
emit BeaconProofVerifier.BlockRootsLayoutValidated(blockRootsGindex, firstSlot, lastSlot);
}
/// @notice The body of `BeaconProofVerifier.addBlockHashLayout`.
function addBlockHashLayout(
BeaconProofVerifier.SlotRange[] storage table,
IBeaconLightClient lightClient,
uint256 blockHashGindex,
BeaconProofVerifier.BlockHashEvidence calldata evidence
) external {
if (blockHashGindex == 0 || SSZ.depthOf(blockHashGindex) > MAX_BLOCK_HASH_DEPTH) {
revert BeaconProofVerifier.LayoutOutOfBounds(blockHashGindex);
}
if (!_isBlockHashPosition(blockHashGindex)) revert BeaconProofVerifier.LayoutPositionInvalid(blockHashGindex);
_requireStoredHeader(lightClient, evidence.header);
uint64 slot = evidence.header.slot;
bytes32 storedBlockHash = lightClient.executionBlockHashes(slot);
if (storedBlockHash == bytes32(0)) revert BeaconProofVerifier.EvidenceSlotNotStored(slot);
if (_provenShape(lightClient, evidence.header.stateRoot, evidence.fork) == ForkShape.PROGRESSIVE) {
revert BeaconProofVerifier.GloasSlotRefused(slot);
}
if (!SSZ.isValidBranch(storedBlockHash, evidence.branch, blockHashGindex, evidence.header.bodyRoot)) {
revert BeaconProofVerifier.LayoutEvidenceInvalid();
}
(uint64 firstSlot, uint64 lastSlot) = _record(table, blockHashGindex, slot);
emit BeaconProofVerifier.BlockHashLayoutValidated(blockHashGindex, firstSlot, lastSlot);
}
/// @notice The body of `BeaconProofVerifier.addHistoricalSummariesLayout`.
function addHistoricalSummariesLayout(
BeaconProofVerifier.SlotRange[] storage table,
IBeaconLightClient lightClient,
uint64 capellaEra,
uint256 historicalSummariesGindex,
BeaconProofVerifier.HistoricalSummariesEvidence calldata evidence
) external {
if (
historicalSummariesGindex == 0
|| (SSZ.depthOf(historicalSummariesGindex) > MAX_BLOCK_ROOTS_DEPTH
&& historicalSummariesGindex != GLOAS_HISTORICAL_SUMMARIES_GINDEX)
) {
revert BeaconProofVerifier.LayoutOutOfBounds(historicalSummariesGindex);
}
if (!_isHistoricalSummariesPosition(historicalSummariesGindex)) {
revert BeaconProofVerifier.LayoutPositionInvalid(historicalSummariesGindex);
}
_requireStoredHeader(lightClient, evidence.anchorHeader);
uint64 anchorSlot = evidence.anchorHeader.slot;
uint64 earlierSlot = evidence.earlierSlot;
bytes32 storedRoot = lightClient.headers(earlierSlot);
if (storedRoot == bytes32(0)) revert BeaconProofVerifier.EvidenceSlotNotStored(earlierSlot);
if (earlierSlot >= anchorSlot || anchorSlot - earlierSlot <= SLOTS_PER_HISTORICAL_ROOT) {
revert BeaconProofVerifier.EvidenceSlotNotHistorical(earlierSlot, anchorSlot);
}
uint256 leafIndex =
_historicalLeafGindex(historicalSummariesGindex, _eraIndex(capellaEra, earlierSlot), earlierSlot);
if (!SSZ.isValidBranch(storedRoot, evidence.branch, leafIndex, evidence.anchorHeader.stateRoot)) {
revert BeaconProofVerifier.LayoutEvidenceInvalid();
}
(uint64 firstSlot, uint64 lastSlot) = _record(table, historicalSummariesGindex, anchorSlot);
emit BeaconProofVerifier.HistoricalSummariesLayoutValidated(historicalSummariesGindex, firstSlot, lastSlot);
}
/// @dev Records that `gindex` was validated at `slot`, by the range rule (`planRange`): a new row, or a row of the same
/// position that grows to hold the slot. Returns the range of that row after the change.
function _record(BeaconProofVerifier.SlotRange[] storage table, uint256 gindex, uint64 slot)
private
returns (uint64 firstSlot, uint64 lastSlot)
{
BeaconProofVerifier.SlotRange[] memory ranges = table;
uint256 index = planRange(gindex, slot, ranges);
if (index == ranges.length) {
table.push(BeaconProofVerifier.SlotRange({gindex: gindex, firstSlot: slot, lastSlot: slot}));
return (slot, slot);
}
BeaconProofVerifier.SlotRange storage row = table[index];
if (slot < row.firstSlot) row.firstSlot = slot;
if (slot > row.lastSlot) row.lastSlot = slot;
return (row.firstSlot, row.lastSlot);
}
// ------------------------------------------------------------------ checks of a delivery
/// @notice Checks 1 to 3 of a delivery: the anchor is the header that the light client stored for its slot, and the
/// source block is its ancestor. The path comes from the distance: up to 8192 slots is the recent path through
/// `block_roots`, more is the historical path through `historical_summaries`. The prover never picks. Both leaf
/// indices are built by pure functions, and the branch length must be exact (`SSZ.isValidBranch` refuses padding and
/// short branches).
/// @param anchorHeader A header that the light client stored.
/// @param sourceHeader The beacon block that carries the proven execution block.
/// @param branch The branch from the root of `sourceHeader` to the state root of the anchor.
function requireAncestry(
BeaconProofVerifier.LayoutTables storage tables,
IBeaconLightClient lightClient,
uint64 capellaEra,
BeaconBlockHeader calldata anchorHeader,
BeaconBlockHeader calldata sourceHeader,
bytes32[] calldata branch
) external view {
_requireStoredHeader(lightClient, anchorHeader);
uint64 anchorSlot = anchorHeader.slot;
uint64 depositSlot = sourceHeader.slot;
if (depositSlot >= anchorSlot) revert BeaconProofVerifier.DepositNotBeforeAnchor(depositSlot, anchorSlot);
uint256 leafIndex = anchorSlot - depositSlot <= SLOTS_PER_HISTORICAL_ROOT
? _gindexAt(tables.states, anchorSlot) * SLOTS_PER_HISTORICAL_ROOT
+ (depositSlot % SLOTS_PER_HISTORICAL_ROOT)
: _historicalLeafGindex(
_gindexAt(tables.historicals, anchorSlot), _eraIndex(capellaEra, depositSlot), depositSlot
);
bytes32 sourceRoot = SSZ.hashTreeRoot(sourceHeader);
if (!SSZ.isValidBranch(sourceRoot, branch, leafIndex, anchorHeader.stateRoot)) {
revert BeaconProofVerifier.AncestryBranchInvalid();
}
}
/// @notice Check 4 of a delivery: the execution block hash sits in the body of the source header. The fork proof of the
/// source state picks the rule first. A plain shape (before Gloas) takes the validated payload block hash position of
/// the slot. The progressive shape (Gloas on) takes the bid `parent_block_hash` at the fixed index 2856 (see
/// `GLOAS_BID_PARENT_BLOCK_HASH_GINDEX`). The state root comes from the source header, whose root check 3 already tied
/// to a stored head, so the prover cannot pick another state.
function requireBlockHash(
BeaconProofVerifier.SlotRange[] storage bodies,
IBeaconLightClient lightClient,
bytes32 blockHash,
BeaconBlockHeader calldata sourceHeader,
bytes32[] calldata branch,
BeaconProofVerifier.ForkProof calldata sourceFork
) external view {
uint256 gindex = _provenShape(lightClient, sourceHeader.stateRoot, sourceFork) == ForkShape.PROGRESSIVE
? GLOAS_BID_PARENT_BLOCK_HASH_GINDEX
: _gindexAt(bodies, sourceHeader.slot);
if (!SSZ.isValidBranch(blockHash, branch, gindex, sourceHeader.bodyRoot)) {
revert BeaconProofVerifier.BlockHashBranchInvalid();
}
}
/// @dev The shape of the state under `stateRoot`, by the rule of the deposit gate (`ForkShape.judge`), with the genesis
/// validators root of the light client. Reverts unless the shape is in `ForkShape.allowedShapes`.
///
/// Why the prover cannot claim the other shape. The genesis validators root leaf of each shape lies where the other
/// shapes hold a fixed leaf or a hash: every plain position (33, 65, 129) lies under node 4, which is the leaf
/// `genesis_time` in the progressive state, and the progressive position 40 is the root of `eth1_data` (depth 5) or an
/// inner node (depth 6, 7) of a plain state. So a valid branch for the wrong shape needs a SHA-256 preimage.
function _provenShape(
IBeaconLightClient lightClient,
bytes32 stateRoot,
BeaconProofVerifier.ForkProof calldata fork
) private view returns (uint8) {
(ForkShape.Verdict verdict, uint8 shape) = ForkShape.judge(
stateRoot,
fork.version,
fork.versionBranch,
fork.genesisValidatorsRootBranch,
lightClient.genesisValidatorsRoot()
);
if (verdict != ForkShape.Verdict.Allowed) revert BeaconProofVerifier.ForkShapeProofInvalid(uint8(verdict));
return shape;
}
/// @dev The validated position of a layout table whose slot range contains `slot`.
function _gindexAt(BeaconProofVerifier.SlotRange[] storage table, uint64 slot) private view returns (uint256) {
for (uint256 i = 0; i < table.length; i++) {
BeaconProofVerifier.SlotRange storage row = table[i];
if (row.firstSlot <= slot && slot <= row.lastSlot) return row.gindex;
}
revert BeaconProofVerifier.LayoutNotValidated(slot);
}
// ------------------------------------------------------------------ rules (internal, also used by tests)
/// @dev The range rule. Returns the index of the range of `gindex` that grows to hold `slot`, or `ranges.length`
/// when a new range must start. A range grows only when the grown range overlaps no range of another position, so
/// ranges of different positions never overlap. Reverts when `slot` is already inside the range of another position.
function planRange(uint256 gindex, uint64 slot, BeaconProofVerifier.SlotRange[] memory ranges)
internal
pure
returns (uint256)
{
for (uint256 i = 0; i < ranges.length; i++) {
if (ranges[i].gindex == gindex) continue;
if (ranges[i].firstSlot <= slot && slot <= ranges[i].lastSlot) {
revert BeaconProofVerifier.LayoutRangeConflict(slot);
}
}
for (uint256 i = 0; i < ranges.length; i++) {
if (ranges[i].gindex != gindex) continue;
uint64 low = slot < ranges[i].firstSlot ? slot : ranges[i].firstSlot;
uint64 high = slot > ranges[i].lastSlot ? slot : ranges[i].lastSlot;
if (_overlapsOtherPosition(gindex, low, high, ranges)) continue;
return i;
}
return ranges.length;
}
/// @dev Whether a range of a position other than `gindex` shares a slot with `low` to `high`.
function _overlapsOtherPosition(
uint256 gindex,
uint64 low,
uint64 high,
BeaconProofVerifier.SlotRange[] memory ranges
) private pure returns (bool) {
for (uint256 i = 0; i < ranges.length; i++) {
if (ranges[i].gindex == gindex) continue;
if (ranges[i].firstSlot <= high && low <= ranges[i].lastSlot) return true;
}
return false;
}
/// @dev Whether `gindex` is `BeaconState.block_roots` in a state of an allowed shape: field 5 of a plain tree (37, 69,
/// 133 for depth 5, 6, 7), or 352 in the progressive state.
function _isBlockRootsPosition(uint256 gindex) private pure returns (bool) {
return _isStateFieldPosition(gindex, BLOCK_ROOTS_FIELD, GLOAS_BLOCK_ROOTS_GINDEX);
}
/// @dev Whether `gindex` is `BeaconState.historical_summaries` in a state of an allowed shape: field 27 of a plain tree
/// (59, 91, 155), or 2950 in the progressive state.
function _isHistoricalSummariesPosition(uint256 gindex) private pure returns (bool) {
return _isStateFieldPosition(gindex, HISTORICAL_SUMMARIES_FIELD, GLOAS_HISTORICAL_SUMMARIES_GINDEX);
}
/// @dev Whether `gindex` is the position of a state field for one of the shapes of `ForkShape.allowedShapes`, the list
/// of the deposit gate: `2**shape + fieldIndex` for a plain shape, `progressiveGindex` for the progressive one. A shape
/// added to or removed from that list adds or removes its positions here, with no second list.
function _isStateFieldPosition(uint256 gindex, uint256 fieldIndex, uint256 progressiveGindex)
private
pure
returns (bool)
{
uint8[] memory shapes = ForkShape.allowedShapes();
for (uint256 i = 0; i < shapes.length; i++) {
uint256 position =
shapes[i] == ForkShape.PROGRESSIVE ? progressiveGindex : (uint256(1) << shapes[i]) + fieldIndex;
if (gindex == position) return true;
}
return false;
}
/// @dev Whether `gindex` is `ExecutionPayload.block_hash` inside `BeaconBlockBody.execution_payload`:
/// `(2**bodyDepth + 9) * 2**payloadDepth + 12`, with both depths in 4 to 5.
function _isBlockHashPosition(uint256 gindex) private pure returns (bool) {
for (uint256 bodyDepth = MIN_BODY_DEPTH; bodyDepth <= MAX_BODY_DEPTH; bodyDepth++) {
uint256 payloadField = (uint256(1) << bodyDepth) + EXECUTION_PAYLOAD_FIELD;
for (uint256 payloadDepth = MIN_PAYLOAD_DEPTH; payloadDepth <= MAX_PAYLOAD_DEPTH; payloadDepth++) {
if (gindex == (payloadField << payloadDepth) + BLOCK_HASH_FIELD) return true;
}
}
return false;
}
/// @dev A header must equal the finalized header that the light client stored for its slot.
function _requireStoredHeader(IBeaconLightClient lightClient, BeaconBlockHeader calldata header) private view {
bytes32 headerRoot = SSZ.hashTreeRoot(header);
bytes32 stored = lightClient.headers(header.slot);
if (stored == bytes32(0) || stored != headerRoot) {
revert BeaconProofVerifier.AnchorNotStored(header.slot, headerRoot);
}
}
/// @dev The stored root at `earlierSlot` must be the leaf at the candidate position under the later state root.
function _requireEarlierRoot(
IBeaconLightClient lightClient,
BeaconBlockHeader calldata later,
uint64 earlierSlot,
uint256 blockRootsGindex,
bytes32[] calldata branch
) private view {
if (earlierSlot >= later.slot || later.slot - earlierSlot > SLOTS_PER_HISTORICAL_ROOT) {
revert BeaconProofVerifier.EvidenceSlotOutOfWindow(earlierSlot, later.slot);
}
bytes32 storedRoot = lightClient.headers(earlierSlot);
if (storedRoot == bytes32(0)) revert BeaconProofVerifier.EvidenceSlotNotStored(earlierSlot);
uint256 elementIndex = blockRootsGindex * SLOTS_PER_HISTORICAL_ROOT + (earlierSlot % SLOTS_PER_HISTORICAL_ROOT);
if (!SSZ.isValidBranch(storedRoot, branch, elementIndex, later.stateRoot)) {
revert BeaconProofVerifier.LayoutEvidenceInvalid();
}
}
/// @dev The index of the summary of a slot's era: `era - capellaEra`. The era must be at or after `capellaEra`
/// and the index must fit the list of 2**24 entries.
function _eraIndex(uint64 capellaEra, uint64 slot) private pure returns (uint64) {
uint64 era = slot / SLOTS_PER_HISTORICAL_ROOT;
if (era < capellaEra) revert BeaconProofVerifier.DepositBeforeCapellaEra(era, capellaEra);
uint64 index = era - capellaEra;
if (uint256(index) >= (uint256(1) << HISTORICAL_SUMMARIES_LIST_DEPTH)) {
revert BeaconProofVerifier.HistoricalIndexOutOfRange(index);
}
return index;
}
/// @dev The historical path. Built in this order, from the index `g` of `historical_summaries` in `BeaconState`:
/// 1. `g` is the field. 2. `g = g * 2`: the list data root, past the length mix-in.
/// 3. `g = g * 2**24 + index`: the list position. 4. `g = g * 2 + 0`: `HistoricalSummary.block_summary_root`.
/// 5. `g = g * 2**13 + depositSlot % 8192`: the position inside that era's `block_roots`.
function _historicalLeafGindex(uint256 historicalSummariesGindex, uint64 index, uint64 depositSlot)
private
pure
returns (uint256 gindex)
{
gindex = historicalSummariesGindex;
gindex = gindex * 2;
gindex = gindex * (uint256(1) << HISTORICAL_SUMMARIES_LIST_DEPTH) + index;
gindex = gindex * 2 + 0;
gindex = gindex * (uint256(1) << BLOCK_ROOTS_VECTOR_DEPTH) + (depositSlot % SLOTS_PER_HISTORICAL_ROOT);
}
}
src/hardened/AmbMessageCodec.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @title AmbMessageCodec
/// @notice The Arbitrary Message Bridge message encoding, byte for byte as OmniBridge has it.
/// @dev Sources, read on 2026-10-24 at commit 908a48107919d4ab127f9af07d44d47eac91547e of
/// `poanetwork/tokenbridge-contracts`:
/// - `contracts/upgradeable_contracts/arbitrary_message/MessageDelivery.sol`: `_packHeader` writes the message, and
/// `_getNewMessageId` builds the message identifier.
/// - `contracts/libraries/ArbitraryMessage.sol`: `unpackData` reads it, and its comment lists the offsets.
/// - `contracts/upgradeable_contracts/arbitrary_message/VersionableAMB.sol`: `MESSAGE_PACKING_VERSION`.
/// - `contracts/upgradeable_contracts/arbitrary_message/BasicAMB.sol`: `_setChainIds` fixes the chain identifier
/// lengths (the fewest bytes that hold the value, so leading zero bytes are not kept).
///
/// The layout, with offsets in bytes:
///
/// 0 : 32 bytes message identifier
/// 32 : 20 bytes sender
/// 52 : 20 bytes executor (the target)
/// 72 : 4 bytes gas limit (uint32)
/// 76 : 1 byte length X of the source chain identifier
/// 77 : 1 byte length Y of the destination chain identifier
/// 78 : 1 byte data type (0x00 for `requireToPassMessage`, 0x80 for `requireToConfirmMessage`)
/// 79 : X bytes source chain identifier
/// 79 + X : Y bytes destination chain identifier
/// 79 + X + Y : the rest, the call data
///
/// The message identifier is `MESSAGE_PACKING_VERSION | (keccak256(chainId, bridge) & BRIDGE_ID_MASK) | nonce`, where
/// `chainId` is the 32 byte source chain identifier, `bridge` is the 20 byte address of the sending bridge, and the
/// nonce takes the lowest 8 bytes. The bytes 4 to 23 of the hash are kept. The nonce only makes identifiers unique.
library AmbMessageCodec {
/// @notice The message is shorter than its header says, or a chain identifier length is not 1 to 32.
error MalformedMessage();
/// @notice The message format version. It stands in the top 4 bytes of every message identifier.
bytes32 internal constant MESSAGE_PACKING_VERSION = bytes32(uint256(0x00050000) << 224);
/// @notice The bytes of the hash of (chain identifier, bridge) that stand in the message identifier.
bytes32 internal constant BRIDGE_ID_MASK = 0x00000000ffffffffffffffffffffffffffffffffffffffff0000000000000000;
/// @notice The data type of a message sent with `requireToPassMessage`.
uint8 internal constant DATA_TYPE_PASS = 0x00;
/// @notice The data type of a message sent with `requireToConfirmMessage`.
uint8 internal constant DATA_TYPE_CONFIRM = 0x80;
/// @dev The fixed part of the header: 32 + 20 + 20 + 4 + 1 + 1 + 1 bytes.
uint256 private constant FIXED_HEADER_LENGTH = 79;
/// @notice The fields of a message, without the call data.
struct Header {
bytes32 messageId;
address sender;
address executor;
uint32 gasLimit;
uint8 dataType;
uint256 sourceChainId;
uint256 destinationChainId;
}
/// @notice The bytes of a message identifier that no bridge writes and a receiver checks: the version.
/// @param messageId The identifier.
function hasValidVersion(bytes32 messageId) internal pure returns (bool) {
return messageId & 0xffffffff00000000000000000000000000000000000000000000000000000000 == MESSAGE_PACKING_VERSION;
}
/// @notice The identifier prefix of a bridge: the version and the bridge part. Add the nonce to get an identifier.
/// @param sourceChainId The chain identifier of the sending bridge.
/// @param bridge The address of the sending bridge.
function messageIdPrefix(uint256 sourceChainId, address bridge) internal pure returns (bytes32) {
return MESSAGE_PACKING_VERSION | (keccak256(abi.encodePacked(sourceChainId, bridge)) & BRIDGE_ID_MASK);
}
/// @notice Writes a message.
/// @param header The fields. `gasLimit` and the chain identifiers are written as the format says.
/// @param data The call data.
function encode(Header memory header, bytes calldata data) internal pure returns (bytes memory) {
uint256 sourceLength = chainIdLength(header.sourceChainId);
uint256 destinationLength = chainIdLength(header.destinationChainId);
return abi.encodePacked(
header.messageId,
header.sender,
header.executor,
header.gasLimit,
uint8(sourceLength),
uint8(destinationLength),
header.dataType,
_chainIdBytes(header.sourceChainId, sourceLength),
_chainIdBytes(header.destinationChainId, destinationLength),
data
);
}
/// @notice Reads a message.
/// @param encoded The message, as `encode` writes it.
/// @return header The fields.
/// @return data The call data. It is a copy.
function decode(bytes memory encoded) internal view returns (Header memory header, bytes memory data) {
if (encoded.length < FIXED_HEADER_LENGTH) revert MalformedMessage();
uint256 sourceLength;
uint256 destinationLength;
assembly {
mstore(header, mload(add(encoded, 32)))
mstore(add(header, 32), shr(96, mload(add(encoded, 64))))
mstore(add(header, 64), shr(96, mload(add(encoded, 84))))
mstore(add(header, 96), shr(224, mload(add(encoded, 104))))
sourceLength := byte(0, mload(add(encoded, 108)))
destinationLength := byte(0, mload(add(encoded, 109)))
mstore(add(header, 128), byte(0, mload(add(encoded, 110))))
}
if (sourceLength == 0 || sourceLength > 32 || destinationLength == 0 || destinationLength > 32) {
revert MalformedMessage();
}
uint256 dataStart = FIXED_HEADER_LENGTH + sourceLength + destinationLength;
if (encoded.length < dataStart) revert MalformedMessage();
uint256 destinationStart = FIXED_HEADER_LENGTH + sourceLength;
assembly {
mstore(
add(header, 160),
shr(sub(256, shl(3, sourceLength)), mload(add(encoded, add(32, FIXED_HEADER_LENGTH))))
)
mstore(
add(header, 192),
shr(sub(256, shl(3, destinationLength)), mload(add(encoded, add(32, destinationStart))))
)
}
data = _copy(encoded, dataStart);
}
/// @notice The fewest bytes that hold a chain identifier: 1 to 32 (an identifier of zero takes one byte).
/// @param chainId The chain identifier.
function chainIdLength(uint256 chainId) internal pure returns (uint256 length) {
length = 1;
while (length < 32 && chainId >> (8 * length) != 0) {
length++;
}
}
/// @dev The low `length` bytes of `chainId`, most significant first.
function _chainIdBytes(uint256 chainId, uint256 length) private pure returns (bytes memory encoded) {
encoded = new bytes(length);
for (uint256 i = 0; i < length; i++) {
encoded[length - 1 - i] = bytes1(uint8(chainId >> (8 * i)));
}
}
/// @dev The bytes of `source` from `start` to its end, in new memory. The copy goes through the identity precompile.
function _copy(bytes memory source, uint256 start) private view returns (bytes memory copy) {
uint256 length = source.length - start;
copy = new bytes(length);
bool ok;
assembly {
ok := staticcall(gas(), 4, add(add(source, 32), start), length, add(copy, 32), length)
}
if (!ok) revert MalformedMessage();
}
}
src/hardened/vendor/optimism/Bytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Bytes
/// @notice Bytes is a library for manipulating byte arrays.
library Bytes {
/// @custom:attribution https://github.com/GNSPS/solidity-bytes-utils
/// @notice Slices a byte array with a given starting index and length. Returns a new byte array
/// as opposed to a pointer to the original array. Will throw if trying to slice more
/// bytes than exist in the array.
/// @param _bytes Byte array to slice.
/// @param _start Starting index of the slice.
/// @param _length Length of the slice.
/// @return Slice of the input byte array.
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
}
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/// @notice Slices a byte array with a given starting index up to the end of the original byte
/// array. Returns a new array rather than a pointer to the original.
/// @param _bytes Byte array to slice.
/// @param _start Starting index of the slice.
/// @return Slice of the input byte array.
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
/// @notice Converts a byte array into a nibble array by splitting each byte into two nibbles.
/// Resulting nibble array will be exactly twice as long as the input byte array.
/// @param _bytes Input byte array to convert.
/// @return Resulting nibble array.
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory _nibbles;
assembly {
// Grab a free memory offset for the new array
_nibbles := mload(0x40)
// Load the length of the passed bytes array from memory
let bytesLength := mload(_bytes)
// Calculate the length of the new nibble array
// This is the length of the input array times 2
let nibblesLength := shl(0x01, bytesLength)
// Update the free memory pointer to allocate memory for the new array.
// To do this, we add the length of the new array + 32 bytes for the array length
// rounded up to the nearest 32 byte boundary to the current free memory pointer.
mstore(0x40, add(_nibbles, and(not(0x1F), add(nibblesLength, 0x3F))))
// Store the length of the new array in memory
mstore(_nibbles, nibblesLength)
// Store the memory offset of the _bytes array's contents on the stack
let bytesStart := add(_bytes, 0x20)
// Store the memory offset of the nibbles array's contents on the stack
let nibblesStart := add(_nibbles, 0x20)
// Loop through each byte in the input array
for { let i := 0x00 } lt(i, bytesLength) { i := add(i, 0x01) } {
// Get the starting offset of the next 2 bytes in the nibbles array
let offset := add(nibblesStart, shl(0x01, i))
// Load the byte at the current index within the `_bytes` array
let b := byte(0x00, mload(add(bytesStart, i)))
// Pull out the first nibble and store it in the new array
mstore8(offset, shr(0x04, b))
// Pull out the second nibble and store it in the new array
mstore8(add(offset, 0x01), and(b, 0x0F))
}
}
return _nibbles;
}
/// @notice Compares two byte arrays by comparing their keccak256 hashes.
/// @param _bytes First byte array to compare.
/// @param _other Second byte array to compare.
/// @return True if the two byte arrays are equal, false otherwise.
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
src/hardened/ReceiptProofLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {MerkleTrie} from "./vendor/optimism/trie/MerkleTrie.sol";
import {RLPReader} from "./vendor/optimism/rlp/RLPReader.sol";
import {ReceiptLogs} from "./ReceiptLogs.sol";
import {BeaconProofVerifier} from "./BeaconProofVerifier.sol";
/// @title ReceiptProofLib
/// @notice The execution layer checks of a delivery of the message bridge: the receipt, the transaction and the log of a
/// message (checks 5 to 7 and the log of `executeMessage`). All of it is pure: it reads only its arguments.
/// @dev An external library, linked into `MessageBridge`. It exists so that each contract creation of the bridge stays
/// under the per-transaction gas cap of EIP-7825 (16,777,216): a library is deployed by a transaction of its own. A linked
/// library has no owner and no storage, and its address is fixed in the bytecode of the bridge, so the bridge stays
/// immutable. It reverts with the errors of `BeaconProofVerifier` (and `MalformedEventData` of the bridge, declared here
/// with the same signature), so the errors of a delivery are the same as before the split.
library ReceiptProofLib {
/// @notice The log event data is not the encoding of one `bytes` value. The same error as
/// `MessageBridge.MalformedEventData`.
error MalformedEventData();
/// @dev The index of `transactionsRoot` in the execution block header list.
uint256 internal constant TRANSACTIONS_ROOT_FIELD = 4;
/// @dev The index of `receiptsRoot` in the execution block header list.
uint256 internal constant RECEIPTS_ROOT_FIELD = 5;
/// @notice The receipt, the transaction and the log of a message, under an execution header whose hash the caller
/// proved. Returns the identifier in the topic of the log, the encoded message of its data and the hash of the
/// transaction at the index of the receipt.
/// @dev Checks 5 to 7, then the log: the header roots, the receipt (which must record success), the transaction at
/// the same trie key, the log at `logIndex`, its emitter (`emitter`), its topic 0 (`topic`) and two topics, and the
/// event data (one `bytes` value in its one encoding). The caller checks `receiptIndex == transactionIndex` first.
function provenLog(
bytes calldata executionHeaderRlp,
bytes[] calldata receiptProof,
uint256 receiptIndex,
bytes[] calldata transactionProof,
uint256 logIndex,
address emitter,
bytes32 topic
) external pure returns (bytes32 topicMessageId, bytes memory encoded, bytes32 sourceTransactionHash) {
bytes memory receipt;
(receipt, sourceTransactionHash) =
_receiptAndTransaction(executionHeaderRlp, receiptProof, receiptIndex, transactionProof);
(topicMessageId, encoded) = _messageOf(receiptLog(receipt, logIndex), emitter, topic);
}
/// @dev Checks 5 and 6: the receipt and the hash of the transaction at the trie key `index`, under the roots of the
/// execution header.
function _receiptAndTransaction(
bytes calldata executionHeaderRlp,
bytes[] calldata receiptProof,
uint256 index,
bytes[] calldata transactionProof
) private pure returns (bytes memory receipt, bytes32 transactionHash) {
RLPReader.RLPItem[] memory headerItems = RLPReader.readList(executionHeaderRlp);
bytes32 receiptsRoot = headerRoot(headerItems, RECEIPTS_ROOT_FIELD);
bytes32 transactionsRoot = headerRoot(headerItems, TRANSACTIONS_ROOT_FIELD);
bytes memory key = encodeUint(index);
receipt = MerkleTrie.get(key, receiptProof, receiptsRoot);
transactionHash = keccak256(MerkleTrie.get(key, transactionProof, transactionsRoot));
}
/// @dev Checks the emitter and the topics of a log, then returns the identifier of its topic and the message of
/// its data.
function _messageOf(RLPReader.RLPItem memory log, address emitter, bytes32 topic)
private
pure
returns (bytes32 topicMessageId, bytes memory encoded)
{
RLPReader.RLPItem[] memory logFields = logFieldsOf(log);
requireEmitter(logFields[0], emitter);
RLPReader.RLPItem[] memory topics = RLPReader.readList(logFields[1]);
if (topics.length == 0) revert BeaconProofVerifier.WrongEventTopic(bytes32(0));
bytes32 topic0 = toBytes32(RLPReader.readBytes(topics[0]));
if (topic0 != topic) revert BeaconProofVerifier.WrongEventTopic(topic0);
if (topics.length != 2) revert BeaconProofVerifier.MalformedLog();
topicMessageId = toBytes32(RLPReader.readBytes(topics[1]));
encoded = decodeBytes(RLPReader.readBytes(logFields[2]));
}
// ------------------------------------------------------------------ steps (internal, also used by tests)
/// @dev A 32-byte root of the execution header: the item at `field`. Reverts on a short header or a wrong width.
function headerRoot(RLPReader.RLPItem[] memory fields, uint256 field) internal pure returns (bytes32) {
if (fields.length <= field) revert BeaconProofVerifier.MalformedExecutionHeader();
bytes memory root = RLPReader.readBytes(fields[field]);
if (root.length != 32) revert BeaconProofVerifier.MalformedExecutionHeader();
return bytes32(root);
}
/// @dev Checks 6 and 7, up to the log. The receipt is an EIP-2718 envelope. It must record success. Returns the
/// log at `logIndex`. The receipt may hold more than 32 logs.
function receiptLog(bytes memory receipt, uint256 logIndex) internal pure returns (RLPReader.RLPItem memory) {
RLPReader.RLPItem[] memory fields = RLPReader.readList(receiptPayload(receipt));
if (fields.length != 4) revert BeaconProofVerifier.MalformedReceipt();
bytes memory status = RLPReader.readBytes(fields[0]);
if (status.length != 1 || status[0] != 0x01) revert BeaconProofVerifier.ReceiptFailed();
(bool logFound, RLPReader.RLPItem memory log, uint256 logCount) = ReceiptLogs.itemAt(fields[3], logIndex);
if (!logFound) revert BeaconProofVerifier.LogIndexOutOfRange(logIndex, logCount);
return log;
}
/// @dev The three fields of a log: emitter, topics and data.
function logFieldsOf(RLPReader.RLPItem memory log) internal pure returns (RLPReader.RLPItem[] memory fields) {
fields = RLPReader.readList(log);
if (fields.length != 3) revert BeaconProofVerifier.MalformedLog();
}
/// @dev Requires that the emitter item of a log is `expected`.
function requireEmitter(RLPReader.RLPItem memory emitterItem, address expected) internal pure {
bytes memory emitter = RLPReader.readBytes(emitterItem);
if (emitter.length != 20) revert BeaconProofVerifier.MalformedLog();
address emitterAddress = address(bytes20(emitter));
if (emitterAddress != expected) revert BeaconProofVerifier.WrongEmitter(expected, emitterAddress);
}
/// @dev Reads the event data, which is `abi.encode(bytes)`: the offset 32, the length, the bytes padded to a word.
/// Any other layout is refused, so one message has one encoding.
function decodeBytes(bytes memory eventData) internal pure returns (bytes memory) {
if (eventData.length < 64) revert MalformedEventData();
(uint256 offset, uint256 length) = abi.decode(eventData, (uint256, uint256));
if (offset != 32) revert MalformedEventData();
if (eventData.length != 64 + ((length + 31) / 32) * 32) revert MalformedEventData();
return abi.decode(eventData, (bytes));
}
/// @dev Strips the EIP-2718 type byte. Legacy receipts start with a list prefix (at least 0xc0). The result is an
/// RLP item that points one byte into the receipt, so no byte is copied. A receipt of only a type byte gives an
/// item of length zero, which the reader refuses.
function receiptPayload(bytes memory receipt) internal pure returns (RLPReader.RLPItem memory payload) {
if (receipt.length == 0) revert BeaconProofVerifier.MalformedReceipt();
uint8 first = uint8(receipt[0]);
payload = RLPReader.toRLPItem(receipt);
if (first >= 0xc0) return payload;
if (first < 0x01 || first > 0x04) revert BeaconProofVerifier.MalformedReceipt();
payload.length -= 1;
payload.ptr = RLPReader.MemoryPointer.wrap(RLPReader.MemoryPointer.unwrap(payload.ptr) + 1);
}
function toBytes32(bytes memory value) internal pure returns (bytes32) {
if (value.length != 32) revert BeaconProofVerifier.MalformedLog();
return bytes32(value);
}
/// @dev The RLP encoding of an unsigned integer, which is the receipts trie key of a transaction index.
function encodeUint(uint256 value) internal pure returns (bytes memory) {
if (value == 0) return hex"80";
if (value < 0x80) return abi.encodePacked(uint8(value));
uint256 length;
for (uint256 rest = value; rest > 0; rest >>= 8) {
length++;
}
bytes memory encoded = new bytes(length + 1);
encoded[0] = bytes1(uint8(0x80 + length));
for (uint256 i = 0; i < length; i++) {
encoded[length - i] = bytes1(uint8(value >> (8 * i)));
}
return encoded;
}
}
src/hardened/vendor/optimism/rlp/RLPErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The length of an RLP item must be greater than zero to be decodable
error EmptyItem();
/// @notice The decoded item type for list is not a list item
error UnexpectedString();
/// @notice The RLP item has an invalid data remainder
error InvalidDataRemainder();
/// @notice Decoded item type for bytes is not a string item
error UnexpectedList();
/// @notice The length of the content must be greater than the RLP item length
error ContentLengthMismatch();
/// @notice Invalid RLP header for RLP item
error InvalidHeader();
src/hardened/BeaconProofVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IBeaconLightClient} from "./IBeaconLightClient.sol";
import {BeaconBlockHeader, SSZ} from "./SSZ.sol";
import {OpeningProofLib} from "./OpeningProofLib.sol";
import {BeaconLayoutLib, ERA_SLOTS, ERA_DEPTH, HISTORICAL_LIST_DEPTH} from "./BeaconLayoutLib.sol";
/// @title BeaconProofVerifier
/// @notice The proof checks that every contract of this bridge shares: it reads a log of the other chain through the
/// light client. It holds the anchor, ancestry and block hash checks, the fork layout table, the receipt and log
/// decoding, and the opening proof of the deposit lock. A contract on top of it adds the check of its own log.
/// @dev Fork layouts. The generalized indices of `state.block_roots`, of `state.historical_summaries` and of the
/// execution block hash depend on the fork of the source chain. The contract holds no fixed table. Anyone may add a
/// layout with `addBlockRootsLayout`, `addHistoricalSummariesLayout` and `addBlockHashLayout`. Two checks guard each
/// call. First, the candidate must be the position of the named field itself in a state or body tree of a known shape
/// (see the position rules below). Second, the chain's own stored data must prove it: the candidate position must map
/// stored header roots (or the stored execution block hash) to the stored state (or body) root.
///
/// The first check is needed because the second is not enough alone. Other fields hold values that a block proposer
/// chooses: the list `eth1_data_votes` has the same tree shape as `block_roots`, and `graffiti` or
/// `eth1_data.block_hash` can hold a copy of the execution block hash. A proposer could place stored header roots or
/// a stored block hash there, get that position accepted, and then forge logs. So only the position of the real field
/// is accepted.
///
/// Gloas. From Gloas on, `BeaconState` is a progressive container (EIP-7495, EIP-7916), so a field no longer sits at
/// `2**depth + index`. Its position is one fixed number, which later forks keep. `block_roots` sits at 352 and
/// `historical_summaries` at 2950. The position rules take those two numbers next to the depth rule, and no other
/// number of a deeper tree: the rule for an older fork is not looser. The body of a Gloas block holds a bid and no payload,
/// so no layout position of the block hash exists for a Gloas block. A message source whose state has the progressive
/// shape is a beacon block B after the execution block X, and the fixed index 2856 (the bid `parent_block_hash` of B)
/// must equal the hash of X.
///
/// The fork rule comes from proof, not from a date. The contract holds no fork slot. Each message carries a `ForkProof` of
/// the state of its source header, and each block hash layout evidence carries one of the state of its header. The proof
/// is judged by `ForkShape.judge`, the rule that `BeaconForkGate` applies to deposits, with the genesis validators root of
/// the light client. The proven shape picks the rule: the progressive shape takes the bid rule, a plain depth takes the
/// validated payload layout. A shape outside `ForkShape.allowedShapes` has no accepted proof, so a block of a fork on
/// which the gate seals is never proven. The `block_roots` and `historical_summaries` position rules read the same list.
/// So the gate and this contract follow one list, and a fork takes effect here with its first block, at whatever slot it
/// activates.
///
/// Ancestry has two paths, chosen from the two slots. A block at most 8192 slots below the anchor is proven through
/// `state.block_roots`. An older block is proven through `state.historical_summaries`, which holds the root of every
/// completed era of 8192 block roots since Capella. So a stored head may be any distance past the one before it.
/// A layout is usable only for the slots between the first and the last slot at which it was validated. A range
/// never covers a slot where another position was validated, and ranges of different positions never overlap. So a
/// position validated, then replaced, then validated again leaves the slots between without a layout, and each
/// lookup has one answer. Layouts move only when a container crosses a power-of-two field count; then a new route
/// (light client and bridge) is deployed beside the old one, and the old route keeps paying what it can still prove.
/// This is the immutability trade-off of hole H-19.
///
/// The layout tables live in the storage of the contract on top, so that it keeps control of its storage layout. This
/// contract reaches them through one hook, `_layoutTables`. The three tables share one row type, `SlotRange`.
///
/// Split for the gas cap. The execution layer checks of a delivery (receipt, transaction, log) are in the external
/// library `ReceiptProofLib`, the account and storage proofs of the opening in `OpeningProofLib`, and the anchor, the
/// ancestry, the fork proof, the block hash branch and the layout rules in `BeaconLayoutLib`, so that the creation of the
/// contract on top and of each library stays under the per-transaction gas cap of EIP-7825 (16,777,216). Both are linked: no owner, no storage of their own, their addresses fixed in the
/// bytecode. The layout library runs in the storage of the contract on top, with the tables passed as `storage`
/// arguments. The errors and the events stay declared here, and the libraries use them, so nothing changes outside.
abstract contract BeaconProofVerifier {
/// @notice One row of a layout table: a validated position and the slots at which it was validated. The three tables
/// share this one type (`LayoutTables`), so the range rule and the lookups are one code for all three.
/// @param gindex The validated generalized index: of `BeaconState.block_roots` (table `states`), of
/// `BeaconBlockBody.execution_payload.block_hash` (table `bodies`), or of `BeaconState.historical_summaries` (table
/// `historicals`).
/// @param firstSlot The lowest slot at which the position was validated: a state slot, or a header slot for `bodies`.
/// @param lastSlot The highest slot at which the position was validated.
struct SlotRange {
uint256 gindex;
uint64 firstSlot;
uint64 lastSlot;
}
/// @notice Evidence for a `block_roots` position: two stored earlier headers under one stored later state.
/// @param laterHeader A stored header. Its `stateRoot` holds the block roots.
/// @param earlierSlotA A stored slot before and within 8192 slots of the later header.
/// @param earlierSlotB Another such slot.
/// @param branchA The branch from the stored root at `earlierSlotA` to the later state root.
/// @param branchB The branch from the stored root at `earlierSlotB` to the later state root.
struct BlockRootsEvidence {
BeaconBlockHeader laterHeader;
uint64 earlierSlotA;
uint64 earlierSlotB;
bytes32[] branchA;
bytes32[] branchB;
}
/// @notice The three layout tables of the contract on top, in one storage variable, so that one storage argument
/// reaches all three in `BeaconLayoutLib`. Three dynamic arrays take three consecutive slots, the same slots as three
/// array variables declared in this order.
/// @param states The validated `block_roots` positions, by state slot.
/// @param bodies The validated block hash positions, by header slot.
/// @param historicals The validated `historical_summaries` positions, by state slot.
struct LayoutTables {
SlotRange[] states;
SlotRange[] bodies;
SlotRange[] historicals;
}
/// @notice A proof of the fork of one beacon state: `fork.current_version` and `genesis_validators_root` under the same
/// state root. `ForkShape.judge` reads it and returns the shape of the state tree. The version is not judged by name.
/// @param version The claimed `fork.current_version` of the state.
/// @param versionBranch The branch of the version leaf, deepest first: `Fork.previous_version`, the node over
/// `Fork.epoch`, then the state levels. 7 entries for plain depth 5 and for the progressive state, 8 for depth 6, 9 for
/// depth 7.
/// @param genesisValidatorsRootBranch The branch of `genesis_validators_root` (state field 1), deepest first: as many
/// entries as the plain depth, or 5 for the progressive state. Its leaf is `lightClient.genesisValidatorsRoot()`.
struct ForkProof {
bytes4 version;
bytes32[] versionBranch;
bytes32[] genesisValidatorsRootBranch;
}
/// @notice Evidence for a block hash position: a stored header whose body holds its stored execution block hash.
/// @param header A stored header.
/// @param branch The branch from the stored execution block hash to the body root of the header.
/// @param fork The fork proof of the state of `header`. It must prove a plain shape: the body of a header whose state is
/// progressive (Gloas on) holds no payload.
struct BlockHashEvidence {
BeaconBlockHeader header;
bytes32[] branch;
ForkProof fork;
}
/// @notice Evidence for a `historical_summaries` position: a stored header in a completed era, proven at the claimed
/// position under a later stored anchor's state root.
/// @param anchorHeader A stored header. Its `stateRoot` holds `historical_summaries`.
/// @param earlierSlot A stored slot more than 8192 slots below the anchor, in an era at or after `capellaEra`.
/// @param branch The branch from the stored root at `earlierSlot` to the anchor state root. Its length is exact.
struct HistoricalSummariesEvidence {
BeaconBlockHeader anchorHeader;
uint64 earlierSlot;
bytes32[] branch;
}
/// @notice The evidence for `openDeposits`: a block of the remote chain whose hash the light client stored, and the
/// storage of the remote light client under the state root of that block.
/// @param remoteSlot A slot at which the light client of this vault stored an execution block hash.
/// @param remoteHeaderRlp The RLP of the execution block header whose hash is stored at `remoteSlot`.
/// @param accountProof The state trie proof of the account of `remoteLightClient`.
/// @param storedSlot A slot whose `executionBlockHashes` entry in the remote light client is not zero.
/// @param storageProof The storage trie proof of that entry.
struct OpeningProof {
uint64 remoteSlot;
bytes remoteHeaderRlp;
bytes[] accountProof;
uint64 storedSlot;
bytes[] storageProof;
}
/// @notice The length of `state.block_roots`. A deposit block at most this far below its anchor uses the recent path.
uint64 public constant SLOTS_PER_HISTORICAL_ROOT = ERA_SLOTS;
/// @notice `log2(SLOTS_PER_HISTORICAL_ROOT)`: the depth of the `block_roots` vector.
uint256 public constant BLOCK_ROOTS_VECTOR_DEPTH = ERA_DEPTH;
/// @notice `log2(HISTORICAL_ROOTS_LIMIT)` with `HISTORICAL_ROOTS_LIMIT = 2**24`: the depth of the
/// `historical_summaries` list below its data node.
uint256 public constant HISTORICAL_SUMMARIES_LIST_DEPTH = HISTORICAL_LIST_DEPTH;
// The position rules, the fork positions and the depths are constants of `BeaconLayoutLib`; the execution header and
// account field indices are constants of `ReceiptProofLib` and `OpeningProofLib`. One copy of each, in the code that
// reads it.
/// @notice A constructor argument is zero.
error ZeroValue(string name);
/// @notice The remote chain is the local chain.
error RemoteChainIsLocalChain();
/// @notice Deposits are closed until `openDeposits` proves that the other chain can pay them.
error DepositsNotOpen();
/// @notice The light client of this vault stored no execution block hash at the slot of the opening proof.
error OpeningSlotNotStored(uint64 slot);
/// @notice The header in the opening proof does not hash to the stored execution block hash.
error OpeningHeaderMismatch(bytes32 expected, bytes32 actual);
/// @notice The header, the account or the storage entry of the opening proof does not decode to the expected fields.
error OpeningProofMalformed();
/// @notice The proven entry of the remote light client is empty.
error OpeningEntryEmpty(uint64 storedSlot);
/// @notice The anchor header is not the finalized header stored for its slot.
error AnchorNotStored(uint64 slot, bytes32 anchorRoot);
/// @notice The deposit block is not strictly before the anchor.
error DepositNotBeforeAnchor(uint64 depositSlot, uint64 anchorSlot);
/// @notice The deposit era is before `capellaEra`, so no historical summary covers it.
error DepositBeforeCapellaEra(uint64 depositEra, uint64 capellaEra);
/// @notice The era index does not fit in the summaries list (2**24 entries). It would spill into a neighbour.
error HistoricalIndexOutOfRange(uint64 index);
/// @notice A `historical_summaries` evidence slot is not more than 8192 slots below its anchor.
error EvidenceSlotNotHistorical(uint64 earlierSlot, uint64 anchorSlot);
/// @notice `addBlockHashLayout` was given a header whose state the fork proof shows to be progressive (Gloas on). The
/// stored hash of such a slot is `latest_block_hash`, not the payload of the block of that slot, and the body holds
/// only a bid. A message source of that shape takes no layout: it reads the fixed bid index.
error GloasSlotRefused(uint64 slot);
/// @notice The fork proof proves no allowed shape under the state root. `verdict` is the `ForkShape.Verdict`: 1 no
/// valid version branch, 2 no valid genesis validators root branch, 3 a version branch length of no allowed shape.
error ForkShapeProofInvalid(uint8 verdict);
/// @notice The slot lies inside the validated range of another position, so a layout cannot be validated there.
error LayoutRangeConflict(uint64 slot);
/// @notice No validated layout covers the slot. Anyone can add one with evidence.
error LayoutNotValidated(uint64 slot);
/// @notice A candidate position is zero or deeper than the bound.
error LayoutOutOfBounds(uint256 gindex);
/// @notice A layout evidence slot holds no stored header.
error EvidenceSlotNotStored(uint64 slot);
/// @notice The two earlier slots of the evidence are the same slot.
error EvidenceSlotsEqual(uint64 slot);
/// @notice An earlier slot is not before the later header, or lies more than 8192 slots below it.
error EvidenceSlotOutOfWindow(uint64 earlierSlot, uint64 laterSlot);
/// @notice The evidence does not prove the candidate position.
error LayoutEvidenceInvalid();
/// @notice The ancestry branch does not lead from the deposit header to the anchor state.
error AncestryBranchInvalid();
/// @notice The block hash branch does not lead from the execution block hash to the deposit header body.
error BlockHashBranchInvalid();
/// @notice The execution header does not decode to a header with a receipts root.
error MalformedExecutionHeader();
/// @notice The receipt has an unsupported type byte or does not decode.
error MalformedReceipt();
/// @notice The receipt records a failed transaction.
error ReceiptFailed();
/// @notice The log index is past the end of the receipt's logs.
error LogIndexOutOfRange(uint256 logIndex, uint256 logCount);
/// @notice A candidate position is not the position of the named field in any accepted tree shape.
error LayoutPositionInvalid(uint256 gindex);
/// @notice The log was not emitted by the remote vault.
error WrongEmitter(address expected, address actual);
/// @notice The log is not a `DepositInitiated` log.
error WrongEventTopic(bytes32 actual);
/// @notice The log has the deposit topic but not the deposit layout.
error MalformedLog();
/// @notice Emitted when a validated `block_roots` position is added or its validated range grows.
event BlockRootsLayoutValidated(uint256 indexed blockRootsGindex, uint64 firstSlot, uint64 lastSlot);
/// @notice Emitted when a validated block hash position is added or its validated range grows.
event BlockHashLayoutValidated(uint256 indexed blockHashGindex, uint64 firstSlot, uint64 lastSlot);
/// @notice Emitted when a validated `historical_summaries` position is added or its validated range grows.
event HistoricalSummariesLayoutValidated(
uint256 indexed historicalSummariesGindex, uint64 firstSlot, uint64 lastSlot
);
/// @notice Emitted once, when `openDeposits` proves the condition. Deposits stay open from then on.
/// @param remoteSlot The slot at which the light client of this vault stored the proven block of the remote chain.
/// @param remoteBlockHash The hash of that block.
/// @param storedSlot The slot whose execution block hash the remote light client had stored in that block.
event DepositsOpened(uint64 indexed remoteSlot, bytes32 indexed remoteBlockHash, uint64 storedSlot);
/// @notice The light client that tracks the finalized chain of the remote chain.
IBeaconLightClient public immutable lightClient;
/// @notice `floor(capellaForkSlot / 8192)` of the remote chain: the era of the first `historical_summaries` entry.
/// Ethereum 758 (Capella slot 6209536), PulseChain 0 (Capella epoch 3, slot 96). Zero is valid.
uint64 public immutable capellaEra;
/// @notice The light client on the other chain. It tracks the beacon chain of this chain and feeds the remote contract.
address public immutable remoteLightClient;
// Gloas. From the Gloas fork of the remote chain on, `lightClient.executionBlockHashes(slot)` holds
// `state.latest_block_hash` of the finalized state: the newest payload that a block confirmed BEFORE the slot, not the
// payload of the slot, and the body of a Gloas block holds a bid and no payload. So `addBlockHashLayout` refuses a
// header whose state is proven progressive, and a message source of that shape reads the bid `parent_block_hash` of a
// LATER block (`BeaconLayoutLib.GLOAS_BID_PARENT_BLOCK_HASH_GINDEX`). A Gloas head is used through the opening proof,
// which checks an execution header RLP against the stored hash. No slot of the fork is configured: the fork proof of
// each header decides (see the notes of the contract).
/// @param lightClient_ The light client of the remote chain.
/// @param capellaEra_ `floor(capellaForkSlot / 8192)` of the remote chain. The deploy script checks it.
/// @param remoteLightClient_ The light client on the other chain. `openDeposits` reads its storage.
/// @dev The constructor only stores. The contract on top checks the values, in the order of its own arguments.
constructor(address lightClient_, uint64 capellaEra_, address remoteLightClient_) {
lightClient = IBeaconLightClient(lightClient_);
capellaEra = capellaEra_;
remoteLightClient = remoteLightClient_;
}
// ------------------------------------------------------------------ storage hook
/// @dev The three layout tables. The contract on top declares one `LayoutTables` variable, so it keeps control of its
/// storage layout.
function _layoutTables() internal view virtual returns (LayoutTables storage);
// ------------------------------------------------------------------ opening proof
/// @dev Checks the opening proof and returns the block hash that it proved. The contract on top sets its own flag and
/// emits `DepositsOpened`. The proof walks four links. 1: its light client stored the execution block hash of a
/// block of the other chain at `remoteSlot`. 2: the header in the proof hashes to that block hash, and it holds a
/// state root. 3: under that state root, the account of `remoteLightClient` holds a storage root. 4: under that
/// storage root, `executionBlockHashes[storedSlot]` is not zero. Only `update` writes that entry, so one update was
/// stored, at a head that the other beacon chain had already finalized. That block is final on the other chain and
/// final in the light client of this contract, so no reorganization undoes it. A message sent now lies after that
/// head, because a head is never later than the clock of the chain that stored it. Links 2 to 4 are in
/// `OpeningProofLib.requireOpeningEntry`.
function _verifyOpening(OpeningProof calldata proof) internal view returns (bytes32 blockHash) {
blockHash = lightClient.executionBlockHashes(proof.remoteSlot);
if (blockHash == bytes32(0)) revert OpeningSlotNotStored(proof.remoteSlot);
bytes32 actual = keccak256(proof.remoteHeaderRlp);
if (actual != blockHash) revert OpeningHeaderMismatch(blockHash, actual);
OpeningProofLib.requireOpeningEntry(
proof.remoteHeaderRlp, proof.accountProof, proof.storedSlot, proof.storageProof, remoteLightClient
);
}
// ------------------------------------------------------------------ proof checks
/// @dev Checks 1 to 3: the anchor is a stored header and the source block is its ancestor. The rules run in
/// `BeaconLayoutLib.requireAncestry`, over the layout tables of this contract.
/// @param anchorHeader A header that the light client stored.
/// @param sourceHeader The beacon block that carries the proven execution block.
/// @param branch The branch from the root of `sourceHeader` to the state root of the anchor.
function _requireAncestry(
BeaconBlockHeader calldata anchorHeader,
BeaconBlockHeader calldata sourceHeader,
bytes32[] calldata branch
) internal view {
BeaconLayoutLib.requireAncestry(_layoutTables(), lightClient, capellaEra, anchorHeader, sourceHeader, branch);
}
/// @dev Check 4. The fork proof of the source state picks the rule, then the execution block hash must sit in the body
/// of the source header. A plain shape (before Gloas) takes the validated payload block hash position. The progressive
/// shape (Gloas on) takes the bid `parent_block_hash` at the fixed index 2856 (see
/// `BeaconLayoutLib.GLOAS_BID_PARENT_BLOCK_HASH_GINDEX`). The rule runs in `BeaconLayoutLib.requireBlockHash`.
/// @param blockHash The execution block hash to prove.
/// @param sourceHeader The beacon block that carries the proven execution block. Check 3 proved it.
/// @param branch The branch from `blockHash` to the body root of `sourceHeader`.
/// @param sourceFork The fork proof of the state of `sourceHeader`.
function _requireBlockHashBranch(
bytes32 blockHash,
BeaconBlockHeader calldata sourceHeader,
bytes32[] calldata branch,
ForkProof calldata sourceFork
) internal view {
BeaconLayoutLib.requireBlockHash(_layoutTables().bodies, lightClient, blockHash, sourceHeader, branch, sourceFork);
}
/// @notice Adds a `block_roots` position, or widens its validated range, given evidence from stored data.
/// @dev Open to anyone. The position must be the `block_roots` field itself: `2**d + 5` with `d` a plain shape of
/// `ForkShape.allowedShapes` (5 to 7), or 352 while the progressive shape is allowed (Gloas). Any other position
/// reverts with `LayoutPositionInvalid`, even when the evidence would match (for example the position of
/// `eth1_data_votes`, whose entries a proposer writes). The position is accepted only when, under the stored later
/// state root, the leaf at
/// `blockRootsGindex * 8192 + slot % 8192` equals the light client's stored header root, for two different
/// stored earlier slots. A wrong position cannot match. The position is then usable for the later header's slot.
/// The rules run in `BeaconLayoutLib.addBlockRootsLayout`.
/// @param blockRootsGindex The candidate generalized index of `BeaconState.block_roots`.
/// @param evidence Two stored earlier headers under one stored later state.
function addBlockRootsLayout(uint256 blockRootsGindex, BlockRootsEvidence calldata evidence) external {
BeaconLayoutLib.addBlockRootsLayout(_layoutTables().states, lightClient, blockRootsGindex, evidence);
}
/// @notice Adds a block hash position, or widens its validated range, given evidence from stored data.
/// @dev Open to anyone. The position must be the block hash field itself: `(2**db + 9) * 2**dp + 12` with `db` and
/// `dp` in 4 to 5, which is 412, 668, 812 or 1324. Any other position reverts with `LayoutPositionInvalid`, even when
/// the evidence would match (for example `graffiti` at 18, or `eth1_data.block_hash` at 70, which a proposer can
/// fill with a copy of the block hash). The position is accepted only when, under the body root of a stored header, the leaf at
/// `blockHashGindex` equals the light client's stored execution block hash of that header. The fork proof of the state
/// of the header must prove a plain shape. A header whose state is progressive (Gloas on) is refused with
/// `GloasSlotRefused`: in a Gloas body, 668 and 1324 lie under `graffiti`, where a proposer could place the stored hash.
/// The rules run in `BeaconLayoutLib.addBlockHashLayout`.
/// @param blockHashGindex The candidate generalized index of `BeaconBlockBody.execution_payload.block_hash`.
/// @param evidence A stored header, the branch to its body root, and the fork proof of its state.
function addBlockHashLayout(uint256 blockHashGindex, BlockHashEvidence calldata evidence) external {
BeaconLayoutLib.addBlockHashLayout(_layoutTables().bodies, lightClient, blockHashGindex, evidence);
}
/// @notice Adds a `historical_summaries` position, or widens its validated range, given evidence from stored data.
/// @dev Open to anyone. The position is accepted only when, under the stored anchor state root, the leaf at the
/// historical index of the candidate equals the light client's stored header root at `earlierSlot`. The index is
/// built as `withdraw` builds it, so the candidate must also fit the era formula. A candidate that is another
/// state field (`block_roots`, `finalized_checkpoint.root`, `latest_block_header`) or a list of another depth
/// cannot match. The position is then usable for the anchor's slot. The rules run in
/// `BeaconLayoutLib.addHistoricalSummariesLayout`.
/// @param historicalSummariesGindex The candidate generalized index of `BeaconState.historical_summaries`.
/// @param evidence A stored anchor, a stored earlier slot in a completed era, and the branch between them.
function addHistoricalSummariesLayout(
uint256 historicalSummariesGindex,
HistoricalSummariesEvidence calldata evidence
) external {
BeaconLayoutLib.addHistoricalSummariesLayout(
_layoutTables().historicals, lightClient, capellaEra, historicalSummariesGindex, evidence
);
}
/// @notice The validated `block_roots` positions and their slot ranges.
function stateLayouts() external view returns (SlotRange[] memory) {
return _layoutTables().states;
}
/// @notice The validated `historical_summaries` positions and their slot ranges.
function historicalLayouts() external view returns (SlotRange[] memory) {
return _layoutTables().historicals;
}
/// @notice The validated block hash positions and their slot ranges.
function bodyLayouts() external view returns (SlotRange[] memory) {
return _layoutTables().bodies;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/hardened/mediator/ExactGasCall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title ExactGasCall
/// @notice A call that gets exactly the gas that a sender stated, or none at all. The rule is the same wherever a
/// sender states a gas number for a call (the callback of the mediator, the follow-up call of a router): not enough gas
/// reverts the whole delivery, so it can run again with more gas; a callee that fails with the gas it was promised is
/// a recorded failure, and the delivery completes.
/// @dev Two checks, one on each side of the call.
/// (a) Before the call. The EVM forwards at most 63/64 of the gas left, so the call can receive `gasAmount` only when
/// `gasleft() >= gasAmount + gasAmount / 63`. The caller adds `reserve`, the gas that it needs after the call. Less
/// gas reverts with `InsufficientGas`.
/// (b) After a failed call. A few operations run between check (a) and the call (the address access, the memory of
/// the arguments), so the callee may still have received a little less than `gasAmount`. When it did, and failed,
/// the gas left is below `gasAmount / 63`: with the full amount forwarded it is at least that much. So a failed call
/// that leaves less than `gasAmount / 63` reverts with `CallOutOfGas`. A failed call that leaves more ran with the
/// gas that it was promised.
/// The call copies no return data, so a callee cannot spend the gas of the caller with a large answer or a large
/// error.
library ExactGasCall {
/// @notice The gas left cannot give the call its gas under the 63/64 rule, plus the reserve of the caller.
error InsufficientGas(uint256 available, uint256 required);
/// @notice The call failed after it received less than its gas. The delivery can run again with more gas.
error CallOutOfGas(uint256 gasAmount);
/// @notice Calls `target` with exactly `gasAmount`, no native value, and the bytes of `data` from `start` on.
/// @param target The callee.
/// @param gasAmount The gas that the callee gets.
/// @param reserve The gas that the caller needs after the call. Check (a) adds it.
/// @param data The memory that holds the call data.
/// @param start The offset of the call data in `data`. The call data runs to the end of `data`.
/// @return success Whether the call succeeded.
function callWithExactGas(address target, uint256 gasAmount, uint256 reserve, bytes memory data, uint256 start)
internal
returns (bool success)
{
uint256 required = gasAmount + gasAmount / 63 + reserve;
uint256 available = gasleft();
if (available < required) revert InsufficientGas(available, required);
uint256 length = data.length - start;
assembly ("memory-safe") {
success := call(gasAmount, target, 0, add(add(data, 32), start), length, 0, 0)
}
if (!success && gasleft() < gasAmount / 63) revert CallOutOfGas(gasAmount);
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
src/hardened/vendor/optimism/trie/MerkleTrie.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { Bytes } from "../Bytes.sol";
import { RLPReader } from "../rlp/RLPReader.sol";
/// @title MerkleTrie
/// @notice MerkleTrie is a small library for verifying standard Ethereum Merkle-Patricia trie
/// inclusion proofs. By default, this library assumes a hexary trie. One can change the
/// trie radix constant to support other trie radixes.
library MerkleTrie {
/// @notice Struct representing a node in the trie.
/// @custom:field encoded The RLP-encoded node.
/// @custom:field decoded The RLP-decoded node.
struct TrieNode {
bytes encoded;
RLPReader.RLPItem[] decoded;
}
/// @notice Determines the number of elements per branch node.
uint256 internal constant TREE_RADIX = 16;
/// @notice Branch nodes have TREE_RADIX elements and one value element.
uint256 internal constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
/// @notice Leaf nodes and extension nodes have two elements, a `path` and a `value`.
uint256 internal constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
/// @notice Prefix for even-nibbled extension node paths.
uint8 internal constant PREFIX_EXTENSION_EVEN = 0;
/// @notice Prefix for odd-nibbled extension node paths.
uint8 internal constant PREFIX_EXTENSION_ODD = 1;
/// @notice Prefix for even-nibbled leaf node paths.
uint8 internal constant PREFIX_LEAF_EVEN = 2;
/// @notice Prefix for odd-nibbled leaf node paths.
uint8 internal constant PREFIX_LEAF_ODD = 3;
/// @notice Verifies a proof that a given key/value pair is present in the trie.
/// @param _key Key of the node to search for, as a hex string.
/// @param _value Value of the node to search for, as a hex string.
/// @param _proof Merkle trie inclusion proof for the desired node. Unlike traditional Merkle
/// trees, this proof is executed top-down and consists of a list of RLP-encoded
/// nodes that make a path down to the target node.
/// @param _root Known root of the Merkle trie. Used to verify that the included proof is
/// correctly constructed.
/// @return valid_ Whether or not the proof is valid.
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes[] memory _proof,
bytes32 _root
)
internal
pure
returns (bool valid_)
{
valid_ = Bytes.equal(_value, get(_key, _proof, _root));
}
/// @notice Retrieves the value associated with a given key.
/// @param _key Key to search for, as hex bytes.
/// @param _proof Merkle trie inclusion proof for the key.
/// @param _root Known root of the Merkle trie.
/// @return value_ Value of the key if it exists.
function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {
require(_key.length > 0, "MerkleTrie: empty key");
TrieNode[] memory proof = _parseProof(_proof);
bytes memory key = Bytes.toNibbles(_key);
bytes memory currentNodeID = abi.encodePacked(_root);
uint256 currentKeyIndex = 0;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < proof.length; i++) {
TrieNode memory currentNode = proof[i];
// Key index should never exceed total key length or we'll be out of bounds.
require(currentKeyIndex <= key.length, "MerkleTrie: key index exceeds total key length");
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),
"MerkleTrie: invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),
"MerkleTrie: invalid large internal hash"
);
} else {
// Nodes smaller than 32 bytes aren't hashed.
require(Bytes.equal(currentNode.encoded, currentNodeID), "MerkleTrie: invalid internal node hash");
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// Value is the last element of the decoded list (for branch nodes). There's
// some ambiguity in the Merkle trie specification because bytes(0) is a
// valid value to place into the trie, but for branch nodes bytes(0) can exist
// even when the value wasn't explicitly placed there. Geth treats a value of
// bytes(0) as "key does not exist" and so we do the same.
value_ = RLPReader.readBytes(currentNode.decoded[TREE_RADIX]);
require(value_.length > 0, "MerkleTrie: value length must be greater than zero (branch)");
// Extra proof elements are not allowed.
require(i == proof.length - 1, "MerkleTrie: value node must be last node in proof (branch)");
return value_;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIndex += 1;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - (prefix % 2);
bytes memory pathRemainder = Bytes.slice(path, offset);
bytes memory keyRemainder = Bytes.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
// Whether this is a leaf node or an extension node, the path remainder MUST be a
// prefix of the key remainder (or be equal to the key remainder) or the proof is
// considered invalid.
require(
pathRemainder.length == sharedNibbleLength,
"MerkleTrie: path remainder must share all nibbles with key"
);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
// Prefix of 2 or 3 means this is a leaf node. For the leaf node to be valid,
// the key remainder must be exactly equal to the path remainder. We already
// did the necessary byte comparison, so it's more efficient here to check that
// the key remainder length equals the shared nibble length, which implies
// equality with the path remainder (since we already did the same check with
// the path remainder and the shared nibble length).
require(
keyRemainder.length == sharedNibbleLength,
"MerkleTrie: key remainder must be identical to path remainder"
);
// Our Merkle Trie is designed specifically for the purposes of the Ethereum
// state trie. Empty values are not allowed in the state trie, so we can safely
// say that if the value is empty, the key should not exist and the proof is
// invalid.
value_ = RLPReader.readBytes(currentNode.decoded[1]);
require(value_.length > 0, "MerkleTrie: value length must be greater than zero (leaf)");
// Extra proof elements are not allowed.
require(i == proof.length - 1, "MerkleTrie: value node must be last node in proof (leaf)");
return value_;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
// Prefix of 0 or 1 means this is an extension node. We move onto the next node
// in the proof and increment the key index by the length of the path remainder
// which is equal to the shared nibble length.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIndex += sharedNibbleLength;
} else {
revert("MerkleTrie: received a node with an unknown prefix");
}
} else {
revert("MerkleTrie: received an unparseable node");
}
}
revert("MerkleTrie: ran out of proof elements");
}
/// @notice Parses an array of proof elements into a new array that contains both the original
/// encoded element and the RLP-decoded element.
/// @param _proof Array of proof elements to parse.
/// @return proof_ Proof parsed into easily accessible structs.
function _parseProof(bytes[] memory _proof) private pure returns (TrieNode[] memory proof_) {
uint256 length = _proof.length;
proof_ = new TrieNode[](length);
for (uint256 i = 0; i < length;) {
proof_[i] = TrieNode({ encoded: _proof[i], decoded: RLPReader.readList(_proof[i]) });
unchecked {
++i;
}
}
}
/// @notice Picks out the ID for a node. Node ID is referred to as the "hash" within the
/// specification, but nodes < 32 bytes are not actually hashed.
/// @param _node Node to pull an ID for.
/// @return id_ ID for the node, depending on the size of its contents.
function _getNodeID(RLPReader.RLPItem memory _node) private pure returns (bytes memory id_) {
id_ = _node.length < 32 ? RLPReader.readRawBytes(_node) : RLPReader.readBytes(_node);
}
/// @notice Gets the path for a leaf or extension node.
/// @param _node Node to get a path for.
/// @return nibbles_ Node path, converted to an array of nibbles.
function _getNodePath(TrieNode memory _node) private pure returns (bytes memory nibbles_) {
nibbles_ = Bytes.toNibbles(RLPReader.readBytes(_node.decoded[0]));
}
/// @notice Utility; determines the number of nibbles shared between two nibble arrays.
/// @param _a First nibble array.
/// @param _b Second nibble array.
/// @return shared_ Number of shared nibbles.
function _getSharedNibbleLength(bytes memory _a, bytes memory _b) private pure returns (uint256 shared_) {
uint256 max = (_a.length < _b.length) ? _a.length : _b.length;
for (; shared_ < max && _a[shared_] == _b[shared_];) {
unchecked {
++shared_;
}
}
}
}
src/hardened/ForkShape.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {SSZ} from "./SSZ.sol";
/// @title ForkShape
/// @notice The one rule that decides which fork versions the bridge accepts, on both chains. It looks at the shape of the
/// `BeaconState` tree, never at the name of a fork version.
/// @dev A shape is a plain tree depth (5, 6 or 7) or the progressive form of Gloas, marked by `PROGRESSIVE`. A shape is
/// allowed when it is in the list that `allowedShapes` returns. That list is the only place where the set is written.
/// Both paths of `BeaconForkGate` read it: the path with EIP-4788 evidence (`judge`) and the path with the registry
/// (`isAllowed`). A new allowed shape added here reaches both paths and `allowedShapes` at once, so they cannot drift.
///
/// The evidence of one shape has two branches under the same state root:
/// - The version branch proves `fork.current_version`. In a plain tree of depth d the leaf sits at
/// `((2**d + 3) * 4) + 1` and the branch has d + 2 entries. In the progressive form it sits at 169 with 7 entries.
/// - The genesis validators root branch proves `genesis_validators_root` (field 1) at its position for that shape: `2**d + 1` with d
/// entries, or node 40 with 5 entries. The leaf is the value that the gate holds as an immutable.
/// A version branch of 7 entries fits both plain depth 5 and the progressive form. `judge` tries each and takes the
/// first for which both branches verify.
///
/// Trade-off: the rule judges the shape, not the meaning of the fields. A future fork that reorders fields at the same
/// depth passes the gate. The light client then fails closed, because its own proofs check fixed positions.
library ForkShape {
/// @notice The marker of the progressive `BeaconState` (Gloas on).
uint8 internal constant PROGRESSIVE = 255;
/// @notice The smallest depth for which a seal proof is looked at. Lower depths land above the fields.
uint8 internal constant MIN_SEAL_DEPTH = 5;
/// @notice The largest depth for which a seal proof is looked at.
uint8 internal constant MAX_SEAL_DEPTH = 31;
/// @notice The depth of the three field `Fork` container.
uint256 internal constant FORK_DEPTH = 2;
/// @dev The generalized index of `fork.current_version` in the progressive state: node 42 times 4, plus 1.
uint256 private constant PROGRESSIVE_VERSION_GINDEX = 169;
/// @dev The generalized index of `genesis_validators_root` (chunk 1) in the progressive state.
uint256 private constant PROGRESSIVE_GENESIS_VALIDATORS_ROOT_GINDEX = 40;
/// @dev Branch length of the version leaf in the progressive state: 5 state levels and the `Fork` container.
uint256 private constant PROGRESSIVE_VERSION_LENGTH = 7;
/// @dev Branch length of the genesis validators root leaf in the progressive state.
uint256 private constant PROGRESSIVE_GENESIS_VALIDATORS_ROOT_LENGTH = 5;
/// @dev The position of `fork` among the `BeaconState` fields.
uint256 private constant FORK_FIELD_INDEX = 3;
/// @dev The position of `genesis_validators_root` among the `BeaconState` fields.
uint256 private constant GENESIS_VALIDATORS_ROOT_FIELD_INDEX = 1;
/// @notice The result of judging evidence.
enum Verdict {
/// @dev A shape in the allowed set, with both branches valid.
Allowed,
/// @dev No candidate shape has a valid version branch.
VersionProofInvalid,
/// @dev The version branch is valid for a candidate shape, but its genesis validators root branch is not.
GenesisValidatorsRootProofInvalid,
/// @dev The version branch length fits no allowed shape.
ShapeNotAllowed
}
/// @notice The allowed shapes, in the order in which `judge` tries them.
function allowedShapes() internal pure returns (uint8[] memory shapes) {
shapes = new uint8[](4);
shapes[0] = 5;
shapes[1] = 6;
shapes[2] = 7;
shapes[3] = PROGRESSIVE;
}
/// @notice Whether a shape is in the allowed set. The registry path uses this check.
/// @param shape A plain depth, or `PROGRESSIVE`.
function isAllowed(uint8 shape) internal pure returns (bool) {
uint8[] memory shapes = allowedShapes();
for (uint256 i = 0; i < shapes.length; i++) {
if (shapes[i] == shape) return true;
}
return false;
}
/// @notice The generalized index of `fork.current_version` for an allowed shape.
function versionGindex(uint8 shape) internal pure returns (uint256) {
if (shape == PROGRESSIVE) return PROGRESSIVE_VERSION_GINDEX;
return plainVersionGindex(shape);
}
/// @notice The generalized index of `fork.current_version` in a plain tree of any depth.
function plainVersionGindex(uint256 depth) internal pure returns (uint256) {
return (((uint256(1) << depth) + FORK_FIELD_INDEX) * 4) + 1;
}
/// @notice The generalized index of `genesis_validators_root` for an allowed shape.
function genesisValidatorsRootGindex(uint8 shape) internal pure returns (uint256) {
if (shape == PROGRESSIVE) return PROGRESSIVE_GENESIS_VALIDATORS_ROOT_GINDEX;
return (uint256(1) << shape) + GENESIS_VALIDATORS_ROOT_FIELD_INDEX;
}
/// @notice The number of entries in the version branch of an allowed shape.
function versionBranchLength(uint8 shape) internal pure returns (uint256) {
if (shape == PROGRESSIVE) return PROGRESSIVE_VERSION_LENGTH;
return uint256(shape) + FORK_DEPTH;
}
/// @notice The number of entries in the genesis validators root branch of an allowed shape.
function genesisValidatorsRootBranchLength(uint8 shape) internal pure returns (uint256) {
if (shape == PROGRESSIVE) return PROGRESSIVE_GENESIS_VALIDATORS_ROOT_LENGTH;
return shape;
}
/// @notice The tree depth that a version branch length implies, or zero when the length is below the `Fork` depth.
function depthOfVersionBranch(uint256 length) internal pure returns (uint256) {
if (length < FORK_DEPTH) return 0;
return length - FORK_DEPTH;
}
/// @notice Judges the evidence of the EIP-4788 path.
/// @param stateRoot The state root of the header that the beacon roots contract vouches for.
/// @param version The claimed `fork.current_version`.
/// @param versionBranch The branch of the version leaf, deepest first.
/// @param genesisValidatorsRootBranch The branch of `genesis_validators_root`, deepest first.
/// @param genesisValidatorsRoot The value that the genesis validators root leaf must hold.
/// @return verdict The result.
/// @return shape The shape that was proven. Zero unless the verdict is `Allowed`.
function judge(
bytes32 stateRoot,
bytes4 version,
bytes32[] memory versionBranch,
bytes32[] memory genesisValidatorsRootBranch,
bytes32 genesisValidatorsRoot
) internal pure returns (Verdict verdict, uint8 shape) {
uint8[] memory shapes = allowedShapes();
bool anyCandidate;
bool versionProven;
for (uint256 i = 0; i < shapes.length; i++) {
uint8 candidate = shapes[i];
if (versionBranch.length != versionBranchLength(candidate)) continue;
anyCandidate = true;
if (!SSZ.isValidBranchMemory(bytes32(version), versionBranch, versionGindex(candidate), stateRoot)) continue;
versionProven = true;
if (_genesisValidatorsRootHolds(candidate, genesisValidatorsRootBranch, genesisValidatorsRoot, stateRoot)) return (Verdict.Allowed, candidate);
}
if (!anyCandidate) return (Verdict.ShapeNotAllowed, 0);
if (versionProven) return (Verdict.GenesisValidatorsRootProofInvalid, 0);
return (Verdict.VersionProofInvalid, 0);
}
/// @notice Whether a version branch is valid at the plain position of `depth`. A seal uses it for a depth outside
/// the allowed set. The branch length must equal `depth + 2`.
/// @param stateRoot The state root.
/// @param version The claimed version.
/// @param versionBranch The branch of the version leaf.
/// @param depth The plain tree depth that the branch length implies.
function provesPlainVersion(bytes32 stateRoot, bytes4 version, bytes32[] memory versionBranch, uint256 depth)
internal
pure
returns (bool)
{
return SSZ.isValidBranchMemory(bytes32(version), versionBranch, plainVersionGindex(depth), stateRoot);
}
/// @dev Whether the genesis validators root branch has the length of the shape and proves the genesis validators root.
function _genesisValidatorsRootHolds(uint8 shape, bytes32[] memory genesisValidatorsRootBranch, bytes32 genesisValidatorsRoot, bytes32 stateRoot)
private
pure
returns (bool)
{
if (genesisValidatorsRootBranch.length != genesisValidatorsRootBranchLength(shape)) return false;
return SSZ.isValidBranchMemory(genesisValidatorsRoot, genesisValidatorsRootBranch, genesisValidatorsRootGindex(shape), stateRoot);
}
}
src/hardened/vendor/optimism/rlp/RLPReader.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
// Libraries
import {
EmptyItem,
UnexpectedString,
InvalidDataRemainder,
ContentLengthMismatch,
InvalidHeader,
UnexpectedList
} from "./RLPErrors.sol";
/// @custom:attribution https://github.com/hamdiallam/Solidity-RLP
/// @title RLPReader
/// @notice RLPReader is a library for parsing RLP-encoded byte arrays into Solidity types. Adapted
/// from Solidity-RLP (https://github.com/hamdiallam/Solidity-RLP) by Hamdi Allam with
/// various tweaks to improve readability.
library RLPReader {
/// @notice Custom pointer type to avoid confusion between pointers and uint256s.
type MemoryPointer is uint256;
/// @notice RLP item types.
/// @custom:value DATA_ITEM Represents an RLP data item (NOT a list).
/// @custom:value LIST_ITEM Represents an RLP list item.
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/// @notice Struct representing an RLP item.
/// @custom:field length Length of the RLP item.
/// @custom:field ptr Pointer to the RLP item in memory.
struct RLPItem {
uint256 length;
MemoryPointer ptr;
}
/// @notice Max list length that this library will accept.
uint256 internal constant MAX_LIST_LENGTH = 32;
/// @notice Converts bytes to a reference to memory position and length.
/// @param _in Input bytes to convert.
/// @return out_ Output memory reference.
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory out_) {
// Empty arrays are not RLP items.
if (_in.length == 0) revert EmptyItem();
MemoryPointer ptr;
assembly {
ptr := add(_in, 32)
}
out_ = RLPItem({ length: _in.length, ptr: ptr });
}
/// @notice Reads an RLP list value into a list of RLP items.
/// @param _in RLP list value.
/// @return out_ Decoded RLP list items.
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory out_) {
(uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);
if (itemType != RLPItemType.LIST_ITEM) revert UnexpectedString();
if (listOffset + listLength != _in.length) revert InvalidDataRemainder();
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
out_ = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
(uint256 itemOffset, uint256 itemLength,) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset) })
);
// We don't need to check itemCount < out.length explicitly because Solidity already
// handles this check on our behalf, we'd just be wasting gas.
out_[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out_, itemCount)
}
}
/// @notice Reads an RLP list value into a list of RLP items.
/// @param _in RLP list value.
/// @return out_ Decoded RLP list items.
function readList(bytes memory _in) internal pure returns (RLPItem[] memory out_) {
out_ = readList(toRLPItem(_in));
}
/// @notice Reads an RLP bytes value into bytes.
/// @param _in RLP bytes value.
/// @return out_ Decoded bytes.
function readBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
if (itemType != RLPItemType.DATA_ITEM) revert UnexpectedList();
if (_in.length != itemOffset + itemLength) revert InvalidDataRemainder();
out_ = _copy(_in.ptr, itemOffset, itemLength);
}
/// @notice Reads an RLP bytes value into bytes.
/// @param _in RLP bytes value.
/// @return out_ Decoded bytes.
function readBytes(bytes memory _in) internal pure returns (bytes memory out_) {
out_ = readBytes(toRLPItem(_in));
}
/// @notice Reads the raw bytes of an RLP item.
/// @param _in RLP item to read.
/// @return out_ Raw RLP bytes.
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
out_ = _copy(_in.ptr, 0, _in.length);
}
/// @notice Decodes the length of an RLP item.
/// @param _in RLP item to decode.
/// @return offset_ Offset of the encoded data.
/// @return length_ Length of the encoded data.
/// @return type_ RLP item type (LIST_ITEM or DATA_ITEM).
function _decodeLength(RLPItem memory _in)
private
pure
returns (uint256 offset_, uint256 length_, RLPItemType type_)
{
// Short-circuit if there's nothing to decode, note that we perform this check when
// the user creates an RLP item via toRLPItem, but it's always possible for them to bypass
// that function and create an RLP item directly. So we need to check this anyway.
if (_in.length == 0) revert EmptyItem();
MemoryPointer ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
// slither-disable-next-line variable-scope
uint256 strLen = prefix - 0x80;
if (_in.length <= strLen) revert ContentLengthMismatch();
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
if (strLen == 1 && firstByteOfContent < 0x80) revert InvalidHeader();
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
if (_in.length <= lenOfStrLen) revert ContentLengthMismatch();
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
if (firstByteOfContent == 0x00) revert InvalidHeader();
uint256 strLen;
assembly {
strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))
}
if (strLen <= 55) revert InvalidHeader();
if (_in.length <= lenOfStrLen + strLen) revert ContentLengthMismatch();
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
// slither-disable-next-line variable-scope
uint256 listLen = prefix - 0xc0;
if (_in.length <= listLen) revert ContentLengthMismatch();
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
if (_in.length <= lenOfListLen) revert ContentLengthMismatch();
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
if (firstByteOfContent == 0x00) revert InvalidHeader();
uint256 listLen;
assembly {
listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))
}
if (listLen <= 55) revert InvalidHeader();
if (_in.length <= lenOfListLen + listLen) revert ContentLengthMismatch();
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/// @notice Copies the bytes from a memory location.
/// @param _src Pointer to the location to read from.
/// @param _offset Offset to start reading from.
/// @param _length Number of bytes to read.
/// @return out_ Copied bytes.
function _copy(MemoryPointer _src, uint256 _offset, uint256 _length) private pure returns (bytes memory out_) {
out_ = new bytes(_length);
if (_length == 0) {
return out_;
}
// Mostly based on Solidity's copy_memory_to_memory:
// https://github.com/ethereum/solidity/blob/34dd30d71b4da730488be72ff6af7083cf2a91f6/libsolidity/codegen/YulUtilFunctions.cpp#L102-L114
uint256 src = MemoryPointer.unwrap(_src) + _offset;
assembly {
let dest := add(out_, 32)
let i := 0
for { } lt(i, _length) { i := add(i, 32) } { mstore(add(dest, i), mload(add(src, i))) }
if gt(i, _length) { mstore(add(dest, _length), 0) }
}
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to approve
* @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
src/hardened/mediator/IWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IWETH
/// @notice A token that wraps the native coin one to one (WETH on Ethereum, WPLS on PulseChain).
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
Compiler Settings
{"viaIR":false,"remappings":["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/","forge-std/=lib/forge-std/src/","erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/","halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/","openzeppelin-contracts/=lib/openzeppelin-contracts/"],"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}},"optimizer":{"runs":200,"enabled":true},"metadata":{"useLiteralContent":false,"bytecodeHash":"none","appendCBOR":false},"libraries":{},"evmVersion":"shanghai"}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"bridge_","internalType":"contract ITokenMediator"},{"type":"address","name":"wNative_","internalType":"contract IWETH"},{"type":"address","name":"rewardAddress_","internalType":"address"},{"type":"address","name":"failedDeliveryAddress_","internalType":"address"}]},{"type":"error","name":"CallOutOfGas","inputs":[{"type":"uint256","name":"gasAmount","internalType":"uint256"}]},{"type":"error","name":"DeliveryInProgress","inputs":[]},{"type":"error","name":"EmptyData","inputs":[]},{"type":"error","name":"InsufficientGas","inputs":[{"type":"uint256","name":"available","internalType":"uint256"},{"type":"uint256","name":"required","internalType":"uint256"}]},{"type":"error","name":"InvalidReceiver","inputs":[{"type":"address","name":"receiver","internalType":"address"}]},{"type":"error","name":"NotMediator","inputs":[{"type":"address","name":"caller","internalType":"address"}]},{"type":"error","name":"NotWrappedTokenSender","inputs":[{"type":"address","name":"sender","internalType":"address"}]},{"type":"error","name":"NothingToSweep","inputs":[{"type":"address","name":"token","internalType":"address"}]},{"type":"error","name":"ReentrancyGuardReentrantCall","inputs":[]},{"type":"error","name":"ZeroFailedDeliveryAddress","inputs":[]},{"type":"error","name":"ZeroRewardAddress","inputs":[]},{"type":"event","name":"CallFailed","inputs":[{"type":"address","name":"target","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"uint256","name":"gasGiven","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Delivered","inputs":[{"type":"address","name":"token","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"address","name":"feeTo","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false},{"type":"uint256","name":"fee","internalType":"uint256","indexed":false},{"type":"uint256","name":"paidOut","internalType":"uint256","indexed":false},{"type":"uint8","name":"paidAs","internalType":"enum DeliveryRouter.PaidAs","indexed":false},{"type":"address","name":"callTarget","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"DeliveryFailed","inputs":[{"type":"address","name":"token","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false},{"type":"uint8","name":"reason","internalType":"enum DeliveryRouter.Reason","indexed":false}],"anonymous":false},{"type":"event","name":"HandOffRefused","inputs":[{"type":"address","name":"token","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Swept","inputs":[{"type":"address","name":"token","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"CALL_GAS_RESERVE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DELIVERY_SLOT","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"EXCLUDE_PRIORITY","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"FIXED_FEE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"MULTIPLIER_OF_TOTAL","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"NATIVE_GAS_OVERHEAD","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"NATIVE_SEND_GAS","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"TOKEN_GAS_OVERHEAD","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"UNWRAP","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"baseFee","inputs":[{"type":"bool","name":"excludePriority","internalType":"bool"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract ITokenMediator"}],"name":"bridge","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeMessage","inputs":[{"type":"tuple","name":"proof","internalType":"struct MessageBridge.MessageProof","components":[{"type":"tuple","name":"anchorHeader","internalType":"struct BeaconBlockHeader","components":[{"type":"uint64","name":"slot","internalType":"uint64"},{"type":"uint64","name":"proposerIndex","internalType":"uint64"},{"type":"bytes32","name":"parentRoot","internalType":"bytes32"},{"type":"bytes32","name":"stateRoot","internalType":"bytes32"},{"type":"bytes32","name":"bodyRoot","internalType":"bytes32"}]},{"type":"tuple","name":"sourceHeader","internalType":"struct BeaconBlockHeader","components":[{"type":"uint64","name":"slot","internalType":"uint64"},{"type":"uint64","name":"proposerIndex","internalType":"uint64"},{"type":"bytes32","name":"parentRoot","internalType":"bytes32"},{"type":"bytes32","name":"stateRoot","internalType":"bytes32"},{"type":"bytes32","name":"bodyRoot","internalType":"bytes32"}]},{"type":"bytes32[]","name":"ancestryBranch","internalType":"bytes32[]"},{"type":"bytes32[]","name":"blockHashBranch","internalType":"bytes32[]"},{"type":"tuple","name":"sourceFork","internalType":"struct BeaconProofVerifier.ForkProof","components":[{"type":"bytes4","name":"version","internalType":"bytes4"},{"type":"bytes32[]","name":"versionBranch","internalType":"bytes32[]"},{"type":"bytes32[]","name":"genesisValidatorsRootBranch","internalType":"bytes32[]"}]},{"type":"bytes","name":"executionHeaderRlp","internalType":"bytes"},{"type":"bytes[]","name":"receiptProof","internalType":"bytes[]"},{"type":"uint256","name":"receiptIndex","internalType":"uint256"},{"type":"bytes[]","name":"transactionProof","internalType":"bytes[]"},{"type":"uint256","name":"transactionIndex","internalType":"uint256"},{"type":"uint256","name":"logIndex","internalType":"uint256"}]}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"failedDeliveryAddress","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"fee","internalType":"uint256"},{"type":"uint256","name":"toRecipient","internalType":"uint256"}],"name":"feeInfo","inputs":[{"type":"address","name":"token","internalType":"address"},{"type":"uint256","name":"value","internalType":"uint256"},{"type":"uint256","name":"gasUsed","internalType":"uint256"},{"type":"tuple","name":"director","internalType":"struct DeliveryRouter.FeeDirector","components":[{"type":"address","name":"recipient","internalType":"address"},{"type":"uint256","name":"settings","internalType":"uint256"},{"type":"uint256","name":"limit","internalType":"uint256"},{"type":"uint256","name":"multiplier","internalType":"uint256"},{"type":"uint256","name":"callGas","internalType":"uint256"}]}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"onTokenBridged","inputs":[{"type":"address","name":"token","internalType":"address"},{"type":"uint256","name":"value","internalType":"uint256"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"relayTokensAndCall","inputs":[{"type":"address","name":"receiver","internalType":"address"},{"type":"bytes","name":"data","internalType":"bytes"},{"type":"uint256","name":"callbackGas","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"rewardAddress","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"sweep","inputs":[{"type":"address","name":"token","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IWETH"}],"name":"wNative","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"wrapAndRelayTokens","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"wrapAndRelayTokens","inputs":[{"type":"address","name":"receiver","internalType":"address"}]},{"type":"receive","stateMutability":"payable"}]
Contract Creation Code
0x610100604052348015610010575f5ffd5b506040516123c83803806123c883398101604081905261002f916100da565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556001600160a01b03821661007a5760405163111164f760e21b815260040160405180910390fd5b6001600160a01b0381166100a15760405163426aa08360e11b815260040160405180910390fd5b6001600160a01b0393841660805291831660a052821660c0521660e052610136565b6001600160a01b03811681146100d7575f5ffd5b50565b5f5f5f5f608085870312156100ed575f5ffd5b84516100f8816100c3565b6020860151909450610109816100c3565b604086015190935061011a816100c3565b606086015190925061012b816100c3565b939692955090935050565b60805160a05160c05160e0516121be61020a5f395f81816103ab015261086701525f81816102a8015281816111aa015261130d01525f8181610139015281816101f7015281816106f40152818161092d015281816109dd01528181610a6b01528181610b4201528181610e5301528181610ec5015281816111fe0152818161126a015281816115c80152818161163b0152818161169401528181611802015261187c01525f81816103de01528181610596015281816107a0015281816109af01528181610aa10152610b1501526121be5ff3fe608060405260043610610129575f3560e01c80638d5aafb4116100a8578063cd0433741161006d578063cd04337414610351578063d1dc0fbe14610365578063db7af8541461037b578063e1ae2aa41461039a578063e78cea92146103cd578063f52cbf0e14610400575f5ffd5b80638d5aafb4146102ca578063a7685478146102e0578063b2e25341146102f3578063b7e7249014610327578063c42a5c8c1461033c575f5ffd5b806334f89905116100ee57806334f8990514610231578063351bb5491461024557806363f08d5e14610264578063888d60e3146102835780638cf57cb914610297575f5ffd5b806301681a621461018457806301a754ff146101a357806304a46f7a146101ab57806323d1b06c146101d25780632d68efc9146101e6575f5ffd5b3661018057336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461017e57604051636a2149f760e01b81523360048201526024015b60405180910390fd5b005b5f5ffd5b34801561018f575f5ffd5b5061017e61019e3660046118cf565b610413565b61017e610522565b3480156101b6575f5ffd5b506101bf600281565b6040519081526020015b60405180910390f35b3480156101dd575f5ffd5b506101bf600181565b3480156101f1575f5ffd5b506102197f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016101c9565b34801561023c575f5ffd5b506101bf600481565b348015610250575f5ffd5b506101bf61025f3660046118f7565b61053d565b34801561026f575f5ffd5b5061017e61027e366004611912565b610559565b34801561028e575f5ffd5b506101bf600881565b3480156102a2575f5ffd5b506102197f000000000000000000000000000000000000000000000000000000000000000081565b3480156102d5575f5ffd5b506101bf62019a2881565b61017e6102ee36600461194a565b610676565b3480156102fe575f5ffd5b5061031261030d3660046119d1565b6106de565b604080519283526020830191909152016101c9565b348015610332575f5ffd5b506101bf61c35081565b348015610347575f5ffd5b506101bf61271081565b34801561035c575f5ffd5b506101bf61076d565b348015610370575f5ffd5b506101bf620186a081565b348015610386575f5ffd5b5061017e610395366004611a8e565b610795565b3480156103a5575f5ffd5b506102197f000000000000000000000000000000000000000000000000000000000000000081565b3480156103d8575f5ffd5b506102197f000000000000000000000000000000000000000000000000000000000000000081565b61017e61040e3660046118cf565b610823565b61041b61083c565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa15801561045f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104839190611b3d565b9050805f036104b057604051630180603d60e01b81526001600160a01b0383166004820152602401610175565b6104ba8282610857565b6104c45750610509565b816001600160a01b03167fc36b5179cb9c303b200074996eab2b3473eac370fdd7eba3bec636fe35109696826040516104ff91815260200190565b60405180910390a2505b61051f60015f51602061219e5f395f51905f5255565b50565b61053b3360405180602001604052805f8152505f6108e4565b565b5f6105538261054c575f610b72565b6001610b72565b92915050565b6001610563610b99565b111561058257604051630bf85a6360e11b815260040160405180910390fd5b6105945a6001600160601b0316610bc9565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663cd5965836040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105f0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106149190611b54565b6001600160a01b03166363f08d5e826040518263ffffffff1660e01b815260040161063f9190611d9f565b5f604051808303815f87803b158015610656575f5ffd5b505af1158015610668573d5f5f3e3d5ffd5b5050505061051f6001610bc9565b5f829003610697576040516399d8fec960e01b815260040160405180910390fd5b6106d88484848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152508692506108e4915050565b50505050565b5f808060208401356002161580159061072857507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316876001600160a01b0316145b9050610755868661073e36889003880188611eee565b8461074c57620186a0610bf8565b62019a28610bf8565b92506107618387611f5a565b91505094509492505050565b60405160200161077c90611f6d565b6040516020818303038152906040528051906020012081565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146107e05760405163460f964960e11b8152336004820152602401610175565b5f51602061219e5f395f51905f525460020361080f5761080a836108048585610ccd565b83610d4d565b505050565b61080a8361081d8585610ccd565b83610de1565b61051f8160405180602001604052805f8152505f6108e4565b61084461106e565b60025f51602061219e5f395f51905f5255565b5f61088c6001600160a01b0384167f00000000000000000000000000000000000000000000000000000000000000008461109d565b1561089957506001610553565b826001600160a01b03167fa9111a00103a8ad954ec785e35eb1ff973d78877885958c2b0c7b12369a45ff3836040516108d491815260200190565b60405180910390a2505f92915050565b6001600160a01b038316158061090257506001600160a01b03831630145b1561092b57604051639cfea58360e01b81526001600160a01b0384166004820152602401610175565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b158015610984575f5ffd5b505af1158015610996573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301523460248301527f000000000000000000000000000000000000000000000000000000000000000016935063095ea7b3925060440190506020604051808303815f875af1158015610a27573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a4b9190611fa4565b5081515f03610afe5760405163ad58bdd160e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015284811660248301523460448301527f0000000000000000000000000000000000000000000000000000000000000000169063ad58bdd1906064015b5f604051808303815f87803b158015610ae3575f5ffd5b505af1158015610af5573d5f5f3e3d5ffd5b50505050505050565b604051632488d04d60e21b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690639223413490610acc907f0000000000000000000000000000000000000000000000000000000000000000908790349088908890600401611fbf565b5f6001826001811115610b8757610b87612035565b14610b92573a610553565b4892915050565b5f5f604051602001610baa90611f6d565b60408051601f1981840301815291905280516020909101205492915050565b5f604051602001610bd990611f6d565b6040516020818303038152906040528051906020012090508181555050565b5f60018360200151165f14610c1257506040820151610cba565b602083015160081615610c4957670de0b6b3a7640000836060015186610c389190612049565b610c429190612060565b9050610cba565b5f60048460200151165f03610c5e575f610c61565b60015b9050670de0b6b3a7640000610c7582610b72565b6060860151610c84868961207f565b610c8e9190612049565b610c989190612049565b610ca29190612060565b91508360400151821115610cb857836040015191505b505b84811115610cc55750835b949350505050565b6040516370a0823160e01b81523060048201525f9081906001600160a01b038516906370a0823190602401602060405180830381865afa158015610d13573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d379190611b3d565b9050828110610d465782610cc5565b9392505050565b8051601403610d6e5761080a83610d6383612092565b60601c8460026110aa565b610d778161110e565b610d885761080a835f8460026110aa565b5f81806020019051810190610d9d91906120db565b90505f610da8610b99565b90505f60018211610db95784610dc7565b610dc7865f8786865f611128565b9050610dd986845f01518360026110aa565b505050505050565b610de961083c565b8051601403610e0d57610e0883610dff83612092565b60601c846111fb565b611058565b610e168161110e565b610e2757610e08835f8460016110aa565b5f81806020019051810190610e3c91906120db565b90505f60028260200151165f14158015610e8757507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316856001600160a01b0316145b610e91575f610e94565b60015b90506001816001811115610eaa57610eaa612035565b03610f2557604051632e1a7d4d60e01b8152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015610f0e575f5ffd5b505af1158015610f20573d5f5f3e3d5ffd5b505050505b5f610f32601460a061207f565b84511015610f40575f610f43565b60015b90505f610f4e610b99565b90505f60018211610f5f5786610f6d565b610f6d888589888688611128565b9050805f03610fb3578451610fa9908990895f6001896001811115610f9457610f94612035565b14610fa0576001610fa3565b60025b5f6112f8565b5050505050611058565b5f610fc38986885f015185611398565b90505f816003811115610fd857610fd8612035565b03610fe857505050505050611058565b5f6001856001811115610ffd57610ffd612035565b14611008575f611011565b611011886113e4565b90506110248a885f01518b8686866112f8565b600185600181111561103857611038612035565b036110505761105081885f01518a8a60800151611400565b505050505050505b61080a60015f51602061219e5f395f51905f5255565b5f51602061219e5f395f51905f525460020361053b57604051633ee5aeb560e01b815260040160405180910390fd5b5f610cc58484845f611471565b81156106d857826001600160a01b0316846001600160a01b03167f7e0353da0a9b2b35992db1a601368da9ea3c927089e2849bcb442bc1f96d3ade84846040516110f5929190612133565b60405180910390a36111078483610857565b5050505050565b5f60a08251101580156105535750506020015160a01c1590565b5f80600187600181111561113e5761113e612035565b1461114c57620186a0611151565b62019a285b90505f5a61115f9086611f5a565b9050600184600181111561117557611175612035565b0361118c576080860151611189908261207f565b90505b5f61119988838986610bf8565b90508015806111d157506111cf8a8a7f0000000000000000000000000000000000000000000000000000000000000000846114d3565b155b156111e1578793505050506111f1565b6111eb8189611f5a565b93505050505b9695505050505050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316846001600160a01b03161461125457611240848484611560565b61124a575f61124d565b60015b90506112d6565b604051632e1a7d4d60e01b8152600481018390527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b1580156112b3575f5ffd5b505af11580156112c5573d5f5f3e3d5ffd5b505050506112d383836115b8565b90505b5f8160038111156112e9576112e9612035565b146106d8576106d884848485855f5b5f6113038486611f5a565b90508015611331577f0000000000000000000000000000000000000000000000000000000000000000611333565b5f5b6001600160a01b0316866001600160a01b0316886001600160a01b03167f33f5f01cea30866e647c396d74ec19be8b9123c2f92b21640dd6b8465fb8497e8885898989604051611387959493929190612157565b60405180910390a450505050505050565b5f60018460018111156113ad576113ad612035565b036113c3576113bc83836115b8565b9050610cc5565b6113ce858484611560565b6113d8575f6113db565b60015b95945050505050565b5f806113f260a0602061207f565b929092015160601c92915050565b61141a848261271085611415601460a061207f565b6116bb565b6106d857826001600160a01b0316846001600160a01b03167f8562988fbe66147bc95ef01db9f013592f7058191e59fa6b2b9c1d9625fba7138360405161146391815260200190565b60405180910390a350505050565b60405163a9059cbb60e01b5f8181526001600160a01b038616600452602485905291602083604481808b5af1925060015f511483166114c75783831516156114bb573d5f823e3d81fd5b5f873b113d1516831692505b60405250949350505050565b5f808460018111156114e7576114e7612035565b03611500576113bc6001600160a01b038616848461109d565b5f836001600160a01b03168361c350906040515f60405180830381858888f193505050503d805f811461154e576040519150601f19603f3d011682016040523d82523d5f602084013e611553565b606091505b5090979650505050505050565b5f61156a83611771565b6115825761157b84848460016110aa565b505f610d46565b6115966001600160a01b038516848461109d565b156115a357506001610d46565b6115af8484845f6110aa565b505f9392505050565b5f6115c283611771565b61166a577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0836040518263ffffffff1660e01b81526004015f604051808303818588803b15801561161f575f5ffd5b505af1158015611631573d5f5f3e3d5ffd5b50505050506116637f0000000000000000000000000000000000000000000000000000000000000000848460016110aa565b505f610553565b5f6116758484611798565b90505f81600381111561168a5761168a612035565b03610d4657610d467f000000000000000000000000000000000000000000000000000000000000000085855f6110aa565b5f80846116c9603f88612060565b6116d3908861207f565b6116dd919061207f565b90505f5a90508181101561170e576040516323e228cb60e01b81526004810182905260248101839052604401610175565b5f84865161171c9190611f5a565b90505f5f828760208a01015f8d8df19350831580156117445750611741603f89612060565b5a105b1561176557604051634de8e2d960e01b815260048101899052602401610175565b50505095945050505050565b5f6001600160a01b0382161580159061055357506001600160a01b03821630141592915050565b5f5f836001600160a01b03168361c350906040515f60405180830381858888f193505050503d805f81146117e7576040519150601f19603f3d011682016040523d82523d5f602084013e6117ec565b606091505b505090508015611800576002915050610553565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004015f604051808303818588803b158015611859575f5ffd5b505af115801561186b573d5f5f3e3d5ffd5b506118a79350506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691508690508561109d565b6118b1575f610cc5565b5060039392505050565b6001600160a01b038116811461051f575f5ffd5b5f602082840312156118df575f5ffd5b8135610d46816118bb565b801515811461051f575f5ffd5b5f60208284031215611907575f5ffd5b8135610d46816118ea565b5f60208284031215611922575f5ffd5b813567ffffffffffffffff811115611938575f5ffd5b82016102608185031215610d46575f5ffd5b5f5f5f5f6060858703121561195d575f5ffd5b8435611968816118bb565b9350602085013567ffffffffffffffff811115611983575f5ffd5b8501601f81018713611993575f5ffd5b803567ffffffffffffffff8111156119a9575f5ffd5b8760208284010111156119ba575f5ffd5b949760209190910196509394604001359392505050565b5f5f5f5f8486036101008112156119e6575f5ffd5b85356119f1816118bb565b9450602086013593506040860135925060a0605f1982011215611a12575f5ffd5b509295919450926060019150565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715611a5757611a57611a20565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715611a8657611a86611a20565b604052919050565b5f5f5f60608486031215611aa0575f5ffd5b8335611aab816118bb565b925060208401359150604084013567ffffffffffffffff811115611acd575f5ffd5b8401601f81018613611add575f5ffd5b803567ffffffffffffffff811115611af757611af7611a20565b611b0a601f8201601f1916602001611a5d565b818152876020838501011115611b1e575f5ffd5b816020840160208301375f602083830101528093505050509250925092565b5f60208284031215611b4d575f5ffd5b5051919050565b5f60208284031215611b64575f5ffd5b8151610d46816118bb565b803567ffffffffffffffff81168114611b86575f5ffd5b919050565b67ffffffffffffffff611b9d82611b6f565b16825267ffffffffffffffff611bb560208301611b6f565b1660208301526040818101359083015260608082013590830152608090810135910152565b5f5f8335601e19843603018112611bef575f5ffd5b830160208101925035905067ffffffffffffffff811115611c0e575f5ffd5b8060051b3603821315611c1f575f5ffd5b9250929050565b8183525f6001600160fb1b03831115611c3d575f5ffd5b8260051b80836020870137939093016020019392505050565b5f8235605e19833603018112611c6a575f5ffd5b90910192915050565b5f81356001600160e01b03198116808214611c8c575f5ffd5b845250611c9c6020830183611bda565b60606020860152611cb1606086018284611c26565b915050611cc16040840184611bda565b85830360408701526111f1838284611c26565b5f5f8335601e19843603018112611ce9575f5ffd5b830160208101925035905067ffffffffffffffff811115611d08575f5ffd5b803603821315611c1f575f5ffd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b5f8383855260208501945060208460051b820101835f5b86811015611d9357838303601f19018852611d708287611cd4565b611d7b858284611d16565b60209a8b019a90955093909301925050600101611d55565b50909695505050505050565b60208152611db06020820183611b8b565b611dc060c0820160a08401611b8b565b5f611dcf610140840184611bda565b610260610160850152611de761028085018284611c26565b915050611df8610160850185611bda565b848303601f1901610180860152611e10838284611c26565b92505050611e22610180850185611c56565b838203601f19016101a0850152611e398282611c73565b915050611e4a6101a0850185611cd4565b848303601f19016101c0860152611e62838284611d16565b92505050611e746101c0850185611bda565b848303601f19016101e0860152611e8c838284611d3e565b925050505f6101e085013590508061020085015250611eaf610200850185611bda565b848303601f1901610220860152611ec7838284611d3e565b61022087013561024087810191909152909601356102609095019490945250929392505050565b5f60a0828403128015611eff575f5ffd5b50611f08611a34565b8235611f13816118bb565b81526020838101359082015260408084013590820152606080840135908201526080928301359281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561055357610553611f46565b60208082526017908201527f64656c6976657279726f757465722e64656c6976657279000000000000000000604082015260600190565b5f60208284031215611fb4575f5ffd5b8151610d46816118ea565b6001600160a01b038681168252851660208201526040810184905260a06060820181905283519082018190525f90815b8181101561200c57602081870181015160c0868401015201611fef565b505f60c0828501015260c0601f19601f8301168401019150508260808301529695505050505050565b634e487b7160e01b5f52602160045260245ffd5b808202811582820484141761055357610553611f46565b5f8261207a57634e487b7160e01b5f52601260045260245ffd5b500490565b8082018082111561055357610553611f46565b805160208201516bffffffffffffffffffffffff198116919060148210156120d4576001600160601b03196001600160601b03198360140360031b1b82161692505b5050919050565b5f60a08284031280156120ec575f5ffd5b506120f5611a34565b8251612100816118bb565b81526020838101519082015260408084015190820152606080840151908201526080928301519281019290925250919050565b828152604081016003831061214a5761214a612035565b8260208301529392505050565b858152602081018590526040810184905260a081016004841061217c5761217c612035565b60608201939093526001600160a01b0391909116608090910152939250505056fe9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f700000000000000000000000070499adebb11efd915e3b69e700c331778628707000000000000000000000000e73c08fcda3aba51009b5804d2c464229cd22db4000000000000000000000000f71cbaa5a165fad2ffff6b0d68e84d67b1f75eac
Deployed ByteCode
0x608060405260043610610129575f3560e01c80638d5aafb4116100a8578063cd0433741161006d578063cd04337414610351578063d1dc0fbe14610365578063db7af8541461037b578063e1ae2aa41461039a578063e78cea92146103cd578063f52cbf0e14610400575f5ffd5b80638d5aafb4146102ca578063a7685478146102e0578063b2e25341146102f3578063b7e7249014610327578063c42a5c8c1461033c575f5ffd5b806334f89905116100ee57806334f8990514610231578063351bb5491461024557806363f08d5e14610264578063888d60e3146102835780638cf57cb914610297575f5ffd5b806301681a621461018457806301a754ff146101a357806304a46f7a146101ab57806323d1b06c146101d25780632d68efc9146101e6575f5ffd5b3661018057336001600160a01b037f00000000000000000000000070499adebb11efd915e3b69e700c331778628707161461017e57604051636a2149f760e01b81523360048201526024015b60405180910390fd5b005b5f5ffd5b34801561018f575f5ffd5b5061017e61019e3660046118cf565b610413565b61017e610522565b3480156101b6575f5ffd5b506101bf600281565b6040519081526020015b60405180910390f35b3480156101dd575f5ffd5b506101bf600181565b3480156101f1575f5ffd5b506102197f00000000000000000000000070499adebb11efd915e3b69e700c33177862870781565b6040516001600160a01b0390911681526020016101c9565b34801561023c575f5ffd5b506101bf600481565b348015610250575f5ffd5b506101bf61025f3660046118f7565b61053d565b34801561026f575f5ffd5b5061017e61027e366004611912565b610559565b34801561028e575f5ffd5b506101bf600881565b3480156102a2575f5ffd5b506102197f000000000000000000000000e73c08fcda3aba51009b5804d2c464229cd22db481565b3480156102d5575f5ffd5b506101bf62019a2881565b61017e6102ee36600461194a565b610676565b3480156102fe575f5ffd5b5061031261030d3660046119d1565b6106de565b604080519283526020830191909152016101c9565b348015610332575f5ffd5b506101bf61c35081565b348015610347575f5ffd5b506101bf61271081565b34801561035c575f5ffd5b506101bf61076d565b348015610370575f5ffd5b506101bf620186a081565b348015610386575f5ffd5b5061017e610395366004611a8e565b610795565b3480156103a5575f5ffd5b506102197f000000000000000000000000f71cbaa5a165fad2ffff6b0d68e84d67b1f75eac81565b3480156103d8575f5ffd5b506102197f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f781565b61017e61040e3660046118cf565b610823565b61041b61083c565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa15801561045f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104839190611b3d565b9050805f036104b057604051630180603d60e01b81526001600160a01b0383166004820152602401610175565b6104ba8282610857565b6104c45750610509565b816001600160a01b03167fc36b5179cb9c303b200074996eab2b3473eac370fdd7eba3bec636fe35109696826040516104ff91815260200190565b60405180910390a2505b61051f60015f51602061219e5f395f51905f5255565b50565b61053b3360405180602001604052805f8152505f6108e4565b565b5f6105538261054c575f610b72565b6001610b72565b92915050565b6001610563610b99565b111561058257604051630bf85a6360e11b815260040160405180910390fd5b6105945a6001600160601b0316610bc9565b7f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f76001600160a01b031663cd5965836040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105f0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106149190611b54565b6001600160a01b03166363f08d5e826040518263ffffffff1660e01b815260040161063f9190611d9f565b5f604051808303815f87803b158015610656575f5ffd5b505af1158015610668573d5f5f3e3d5ffd5b5050505061051f6001610bc9565b5f829003610697576040516399d8fec960e01b815260040160405180910390fd5b6106d88484848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152508692506108e4915050565b50505050565b5f808060208401356002161580159061072857507f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b0316876001600160a01b0316145b9050610755868661073e36889003880188611eee565b8461074c57620186a0610bf8565b62019a28610bf8565b92506107618387611f5a565b91505094509492505050565b60405160200161077c90611f6d565b6040516020818303038152906040528051906020012081565b336001600160a01b037f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f716146107e05760405163460f964960e11b8152336004820152602401610175565b5f51602061219e5f395f51905f525460020361080f5761080a836108048585610ccd565b83610d4d565b505050565b61080a8361081d8585610ccd565b83610de1565b61051f8160405180602001604052805f8152505f6108e4565b61084461106e565b60025f51602061219e5f395f51905f5255565b5f61088c6001600160a01b0384167f000000000000000000000000f71cbaa5a165fad2ffff6b0d68e84d67b1f75eac8461109d565b1561089957506001610553565b826001600160a01b03167fa9111a00103a8ad954ec785e35eb1ff973d78877885958c2b0c7b12369a45ff3836040516108d491815260200190565b60405180910390a2505f92915050565b6001600160a01b038316158061090257506001600160a01b03831630145b1561092b57604051639cfea58360e01b81526001600160a01b0384166004820152602401610175565b7f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b158015610984575f5ffd5b505af1158015610996573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b037f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f7811660048301523460248301527f00000000000000000000000070499adebb11efd915e3b69e700c33177862870716935063095ea7b3925060440190506020604051808303815f875af1158015610a27573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a4b9190611fa4565b5081515f03610afe5760405163ad58bdd160e01b81526001600160a01b037f00000000000000000000000070499adebb11efd915e3b69e700c3317786287078116600483015284811660248301523460448301527f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f7169063ad58bdd1906064015b5f604051808303815f87803b158015610ae3575f5ffd5b505af1158015610af5573d5f5f3e3d5ffd5b50505050505050565b604051632488d04d60e21b81526001600160a01b037f000000000000000000000000571f96605921f76a24cf1388c2caf126b15b09f71690639223413490610acc907f00000000000000000000000070499adebb11efd915e3b69e700c331778628707908790349088908890600401611fbf565b5f6001826001811115610b8757610b87612035565b14610b92573a610553565b4892915050565b5f5f604051602001610baa90611f6d565b60408051601f1981840301815291905280516020909101205492915050565b5f604051602001610bd990611f6d565b6040516020818303038152906040528051906020012090508181555050565b5f60018360200151165f14610c1257506040820151610cba565b602083015160081615610c4957670de0b6b3a7640000836060015186610c389190612049565b610c429190612060565b9050610cba565b5f60048460200151165f03610c5e575f610c61565b60015b9050670de0b6b3a7640000610c7582610b72565b6060860151610c84868961207f565b610c8e9190612049565b610c989190612049565b610ca29190612060565b91508360400151821115610cb857836040015191505b505b84811115610cc55750835b949350505050565b6040516370a0823160e01b81523060048201525f9081906001600160a01b038516906370a0823190602401602060405180830381865afa158015610d13573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d379190611b3d565b9050828110610d465782610cc5565b9392505050565b8051601403610d6e5761080a83610d6383612092565b60601c8460026110aa565b610d778161110e565b610d885761080a835f8460026110aa565b5f81806020019051810190610d9d91906120db565b90505f610da8610b99565b90505f60018211610db95784610dc7565b610dc7865f8786865f611128565b9050610dd986845f01518360026110aa565b505050505050565b610de961083c565b8051601403610e0d57610e0883610dff83612092565b60601c846111fb565b611058565b610e168161110e565b610e2757610e08835f8460016110aa565b5f81806020019051810190610e3c91906120db565b90505f60028260200151165f14158015610e8757507f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b0316856001600160a01b0316145b610e91575f610e94565b60015b90506001816001811115610eaa57610eaa612035565b03610f2557604051632e1a7d4d60e01b8152600481018590527f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015610f0e575f5ffd5b505af1158015610f20573d5f5f3e3d5ffd5b505050505b5f610f32601460a061207f565b84511015610f40575f610f43565b60015b90505f610f4e610b99565b90505f60018211610f5f5786610f6d565b610f6d888589888688611128565b9050805f03610fb3578451610fa9908990895f6001896001811115610f9457610f94612035565b14610fa0576001610fa3565b60025b5f6112f8565b5050505050611058565b5f610fc38986885f015185611398565b90505f816003811115610fd857610fd8612035565b03610fe857505050505050611058565b5f6001856001811115610ffd57610ffd612035565b14611008575f611011565b611011886113e4565b90506110248a885f01518b8686866112f8565b600185600181111561103857611038612035565b036110505761105081885f01518a8a60800151611400565b505050505050505b61080a60015f51602061219e5f395f51905f5255565b5f51602061219e5f395f51905f525460020361053b57604051633ee5aeb560e01b815260040160405180910390fd5b5f610cc58484845f611471565b81156106d857826001600160a01b0316846001600160a01b03167f7e0353da0a9b2b35992db1a601368da9ea3c927089e2849bcb442bc1f96d3ade84846040516110f5929190612133565b60405180910390a36111078483610857565b5050505050565b5f60a08251101580156105535750506020015160a01c1590565b5f80600187600181111561113e5761113e612035565b1461114c57620186a0611151565b62019a285b90505f5a61115f9086611f5a565b9050600184600181111561117557611175612035565b0361118c576080860151611189908261207f565b90505b5f61119988838986610bf8565b90508015806111d157506111cf8a8a7f000000000000000000000000e73c08fcda3aba51009b5804d2c464229cd22db4846114d3565b155b156111e1578793505050506111f1565b6111eb8189611f5a565b93505050505b9695505050505050565b5f7f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b0316846001600160a01b03161461125457611240848484611560565b61124a575f61124d565b60015b90506112d6565b604051632e1a7d4d60e01b8152600481018390527f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b031690632e1a7d4d906024015f604051808303815f87803b1580156112b3575f5ffd5b505af11580156112c5573d5f5f3e3d5ffd5b505050506112d383836115b8565b90505b5f8160038111156112e9576112e9612035565b146106d8576106d884848485855f5b5f6113038486611f5a565b90508015611331577f000000000000000000000000e73c08fcda3aba51009b5804d2c464229cd22db4611333565b5f5b6001600160a01b0316866001600160a01b0316886001600160a01b03167f33f5f01cea30866e647c396d74ec19be8b9123c2f92b21640dd6b8465fb8497e8885898989604051611387959493929190612157565b60405180910390a450505050505050565b5f60018460018111156113ad576113ad612035565b036113c3576113bc83836115b8565b9050610cc5565b6113ce858484611560565b6113d8575f6113db565b60015b95945050505050565b5f806113f260a0602061207f565b929092015160601c92915050565b61141a848261271085611415601460a061207f565b6116bb565b6106d857826001600160a01b0316846001600160a01b03167f8562988fbe66147bc95ef01db9f013592f7058191e59fa6b2b9c1d9625fba7138360405161146391815260200190565b60405180910390a350505050565b60405163a9059cbb60e01b5f8181526001600160a01b038616600452602485905291602083604481808b5af1925060015f511483166114c75783831516156114bb573d5f823e3d81fd5b5f873b113d1516831692505b60405250949350505050565b5f808460018111156114e7576114e7612035565b03611500576113bc6001600160a01b038616848461109d565b5f836001600160a01b03168361c350906040515f60405180830381858888f193505050503d805f811461154e576040519150601f19603f3d011682016040523d82523d5f602084013e611553565b606091505b5090979650505050505050565b5f61156a83611771565b6115825761157b84848460016110aa565b505f610d46565b6115966001600160a01b038516848461109d565b156115a357506001610d46565b6115af8484845f6110aa565b505f9392505050565b5f6115c283611771565b61166a577f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b031663d0e30db0836040518263ffffffff1660e01b81526004015f604051808303818588803b15801561161f575f5ffd5b505af1158015611631573d5f5f3e3d5ffd5b50505050506116637f00000000000000000000000070499adebb11efd915e3b69e700c331778628707848460016110aa565b505f610553565b5f6116758484611798565b90505f81600381111561168a5761168a612035565b03610d4657610d467f00000000000000000000000070499adebb11efd915e3b69e700c33177862870785855f6110aa565b5f80846116c9603f88612060565b6116d3908861207f565b6116dd919061207f565b90505f5a90508181101561170e576040516323e228cb60e01b81526004810182905260248101839052604401610175565b5f84865161171c9190611f5a565b90505f5f828760208a01015f8d8df19350831580156117445750611741603f89612060565b5a105b1561176557604051634de8e2d960e01b815260048101899052602401610175565b50505095945050505050565b5f6001600160a01b0382161580159061055357506001600160a01b03821630141592915050565b5f5f836001600160a01b03168361c350906040515f60405180830381858888f193505050503d805f81146117e7576040519150601f19603f3d011682016040523d82523d5f602084013e6117ec565b606091505b505090508015611800576002915050610553565b7f00000000000000000000000070499adebb11efd915e3b69e700c3317786287076001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004015f604051808303818588803b158015611859575f5ffd5b505af115801561186b573d5f5f3e3d5ffd5b506118a79350506001600160a01b037f00000000000000000000000070499adebb11efd915e3b69e700c3317786287071691508690508561109d565b6118b1575f610cc5565b5060039392505050565b6001600160a01b038116811461051f575f5ffd5b5f602082840312156118df575f5ffd5b8135610d46816118bb565b801515811461051f575f5ffd5b5f60208284031215611907575f5ffd5b8135610d46816118ea565b5f60208284031215611922575f5ffd5b813567ffffffffffffffff811115611938575f5ffd5b82016102608185031215610d46575f5ffd5b5f5f5f5f6060858703121561195d575f5ffd5b8435611968816118bb565b9350602085013567ffffffffffffffff811115611983575f5ffd5b8501601f81018713611993575f5ffd5b803567ffffffffffffffff8111156119a9575f5ffd5b8760208284010111156119ba575f5ffd5b949760209190910196509394604001359392505050565b5f5f5f5f8486036101008112156119e6575f5ffd5b85356119f1816118bb565b9450602086013593506040860135925060a0605f1982011215611a12575f5ffd5b509295919450926060019150565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715611a5757611a57611a20565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715611a8657611a86611a20565b604052919050565b5f5f5f60608486031215611aa0575f5ffd5b8335611aab816118bb565b925060208401359150604084013567ffffffffffffffff811115611acd575f5ffd5b8401601f81018613611add575f5ffd5b803567ffffffffffffffff811115611af757611af7611a20565b611b0a601f8201601f1916602001611a5d565b818152876020838501011115611b1e575f5ffd5b816020840160208301375f602083830101528093505050509250925092565b5f60208284031215611b4d575f5ffd5b5051919050565b5f60208284031215611b64575f5ffd5b8151610d46816118bb565b803567ffffffffffffffff81168114611b86575f5ffd5b919050565b67ffffffffffffffff611b9d82611b6f565b16825267ffffffffffffffff611bb560208301611b6f565b1660208301526040818101359083015260608082013590830152608090810135910152565b5f5f8335601e19843603018112611bef575f5ffd5b830160208101925035905067ffffffffffffffff811115611c0e575f5ffd5b8060051b3603821315611c1f575f5ffd5b9250929050565b8183525f6001600160fb1b03831115611c3d575f5ffd5b8260051b80836020870137939093016020019392505050565b5f8235605e19833603018112611c6a575f5ffd5b90910192915050565b5f81356001600160e01b03198116808214611c8c575f5ffd5b845250611c9c6020830183611bda565b60606020860152611cb1606086018284611c26565b915050611cc16040840184611bda565b85830360408701526111f1838284611c26565b5f5f8335601e19843603018112611ce9575f5ffd5b830160208101925035905067ffffffffffffffff811115611d08575f5ffd5b803603821315611c1f575f5ffd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b5f8383855260208501945060208460051b820101835f5b86811015611d9357838303601f19018852611d708287611cd4565b611d7b858284611d16565b60209a8b019a90955093909301925050600101611d55565b50909695505050505050565b60208152611db06020820183611b8b565b611dc060c0820160a08401611b8b565b5f611dcf610140840184611bda565b610260610160850152611de761028085018284611c26565b915050611df8610160850185611bda565b848303601f1901610180860152611e10838284611c26565b92505050611e22610180850185611c56565b838203601f19016101a0850152611e398282611c73565b915050611e4a6101a0850185611cd4565b848303601f19016101c0860152611e62838284611d16565b92505050611e746101c0850185611bda565b848303601f19016101e0860152611e8c838284611d3e565b925050505f6101e085013590508061020085015250611eaf610200850185611bda565b848303601f1901610220860152611ec7838284611d3e565b61022087013561024087810191909152909601356102609095019490945250929392505050565b5f60a0828403128015611eff575f5ffd5b50611f08611a34565b8235611f13816118bb565b81526020838101359082015260408084013590820152606080840135908201526080928301359281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561055357610553611f46565b60208082526017908201527f64656c6976657279726f757465722e64656c6976657279000000000000000000604082015260600190565b5f60208284031215611fb4575f5ffd5b8151610d46816118ea565b6001600160a01b038681168252851660208201526040810184905260a06060820181905283519082018190525f90815b8181101561200c57602081870181015160c0868401015201611fef565b505f60c0828501015260c0601f19601f8301168401019150508260808301529695505050505050565b634e487b7160e01b5f52602160045260245ffd5b808202811582820484141761055357610553611f46565b5f8261207a57634e487b7160e01b5f52601260045260245ffd5b500490565b8082018082111561055357610553611f46565b805160208201516bffffffffffffffffffffffff198116919060148210156120d4576001600160601b03196001600160601b03198360140360031b1b82161692505b5050919050565b5f60a08284031280156120ec575f5ffd5b506120f5611a34565b8251612100816118bb565b81526020838101519082015260408084015190820152606080840151908201526080928301519281019290925250919050565b828152604081016003831061214a5761214a612035565b8260208301529392505050565b858152602081018590526040810184905260a081016004841061217c5761217c612035565b60608201939093526001600160a01b0391909116608090910152939250505056fe9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00