Verified contractPartialMIT
BaseRelay
Address0x6fcd669bda8f3336c94e89abfe14f4bcef6e5d42
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,408,584
- Creation transaction
- 0x05c4de822f…0500d2906b
22 files
- src/v2/base/BaseRelay.solmain3.49 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol653 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol2.34 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/cells/EthStateProof.sol3.44 KB
- src/cells/vendor/Bytes.sol6.72 KB
- src/cells/vendor/MerkleTrie.sol11.22 KB
- src/cells/vendor/RLPErrors.sol596 B
- src/cells/vendor/RLPReader.sol9.34 KB
- src/cells/vendor/SecureMerkleTrie.sol2.21 KB
- src/v2/CellCoreV2.sol28.99 KB
- src/v2/EthCellV2.sol1.66 KB
src/v2/base/BaseRelay.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IArbBridgeV2, IArbOutboxV2} from "../EthCellV2.sol";
/// @notice Base's L1CrossDomainMessenger on Ethereum (OP Stack): delivers a call to a contract on Base, where
/// Base's L2CrossDomainMessenger (0x4200…0007) executes it and reports `xDomainMessageSender()`.
interface IL1CrossDomainMessenger {
function sendMessage(address target, bytes calldata message, uint32 minGasLimit) external payable;
}
/// @title BaseRelay (lives on Ethereum) — passes a basket's messages from Robinhood Chain on to Base
/// @notice Robinhood Chain cannot talk to Base directly. A release for a coin held in a Base cell goes:
/// controller (RH) → ArbSys → rollup Outbox on Ethereum (anyone executes it after the challenge period)
/// → THIS relay → Base's own L1CrossDomainMessenger → the cell on Base (minutes later).
/// The relay accepts a call ONLY from the Robinhood Chain bridge while its active Outbox executes a message
/// of the one controller fixed here, and only forwards it. No owner, no settings, holds nothing.
/// @dev The controller decides the target (its Base cell); the cell accepts only messages whose
/// `xDomainMessageSender` is this relay. A message that runs out of gas on Base is stored by Base's
/// messenger as failed and can be replayed by anyone (`relayMessage`), so a release is never lost.
contract BaseRelay {
/// @notice gas the cell gets on Base for one message (a `record` costs ~150k; spare for safety)
uint32 public constant MIN_GAS = 500_000;
IArbBridgeV2 public immutable bridge; // Robinhood Chain's bridge on Ethereum
address public immutable controller; // BaseControllerV2 on Robinhood Chain
IL1CrossDomainMessenger public immutable messenger; // Base's L1CrossDomainMessenger on Ethereum
/// only the Robinhood Chain bridge calls `forward` (while its Outbox executes a message)
error NotBridge(address caller);
/// the bridge has no Outbox executing a message right now
error NoActiveOutbox();
/// the message being executed was sent on Robinhood Chain by `sender`, not by our controller
error NotController(address sender, address controller);
error ZeroAddress();
event Forwarded(address indexed target, bytes32 indexed dataHash);
constructor(IArbBridgeV2 bridge_, address controller_, IL1CrossDomainMessenger messenger_) {
if (address(bridge_) == address(0) || controller_ == address(0) || address(messenger_) == address(0)) {
revert ZeroAddress();
}
bridge = bridge_;
controller = controller_;
messenger = messenger_;
}
/// @notice called by the rollup bridge when the Outbox executes the controller's message
function forward(address target, bytes calldata data) external {
if (msg.sender != address(bridge)) revert NotBridge(msg.sender);
address outbox = bridge.activeOutbox();
if (outbox == address(0)) revert NoActiveOutbox();
address sender = IArbOutboxV2(outbox).l2ToL1Sender();
if (sender != controller) revert NotController(sender, controller);
// the keeper's address rides along (32 bytes after the call; the cell reads it for its reward, decision 13.11)
messenger.sendMessage(target, bytes.concat(data, abi.encode(tx.origin)), MIN_GAS); // solhint-disable-line
emit Forwarded(target, keccak256(data));
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
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);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.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 {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @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 {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @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 {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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 rely 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 rely 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}.
* Opposedly, 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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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 REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.20;
import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like
* Argent and Safe Wallet (previously Gnosis Safe).
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
if (signer.code.length == 0) {
(address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
return err == ECDSA.RecoverError.NoError && recovered == signer;
} else {
return isValidERC1271SignatureNow(signer, hash, signature);
}
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC-1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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/cells/EthStateProof.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {RLPReader} from "./vendor/RLPReader.sol";
import {SecureMerkleTrie} from "./vendor/SecureMerkleTrie.sol";
/// @title EthStateProof
/// @notice Reads Ethereum (L1) state inside another chain from a trusted L1 block hash:
/// block header → state root → account → storage slot, using standard Merkle-Patricia proofs
/// (the output of `eth_getProof`). No oracle, no relayer to trust: a wrong proof simply fails.
/// @dev Uses Optimism's audited MerkleTrie / RLPReader (MIT), vendored in ./vendor.
/// Inclusion proofs only: an account or slot that does not exist (or a slot that is zero) cannot be
/// proven and the call reverts. Callers must treat "cannot prove" as "no", never as zero.
library EthStateProof {
struct Header {
bytes32 stateRoot;
uint256 number;
uint256 timestamp;
}
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
error HeaderHashMismatch(bytes32 expected, bytes32 actual);
error BadHeader();
error BadAccount();
error ValueTooLong();
/// @notice Decode an RLP block header whose keccak256 must equal `blockHash`.
function header(bytes memory rlpHeader, bytes32 blockHash) internal pure returns (Header memory h) {
bytes32 actual = keccak256(rlpHeader);
if (actual != blockHash) revert HeaderHashMismatch(blockHash, actual);
RLPReader.RLPItem[] memory f = RLPReader.readList(rlpHeader);
// 0 parentHash, 1 ommersHash, 2 beneficiary, 3 stateRoot, 4 txRoot, 5 receiptsRoot, 6 logsBloom,
// 7 difficulty, 8 number, 9 gasLimit, 10 gasUsed, 11 timestamp, ...
if (f.length < 15) revert BadHeader();
bytes memory root = RLPReader.readBytes(f[3]);
if (root.length != 32) revert BadHeader();
h.stateRoot = bytes32(root);
h.number = toUint(RLPReader.readBytes(f[8]));
h.timestamp = toUint(RLPReader.readBytes(f[11]));
}
/// @notice Prove an account in a state root. Reverts if the account is not in the trie.
function account(bytes32 stateRoot, address who, bytes[] memory proof) internal pure returns (Account memory a) {
bytes memory rlpAcc = SecureMerkleTrie.get(abi.encodePacked(who), proof, stateRoot);
RLPReader.RLPItem[] memory f = RLPReader.readList(rlpAcc);
if (f.length != 4) revert BadAccount();
a.nonce = toUint(RLPReader.readBytes(f[0]));
a.balance = toUint(RLPReader.readBytes(f[1]));
bytes memory sr = RLPReader.readBytes(f[2]);
bytes memory ch = RLPReader.readBytes(f[3]);
if (sr.length != 32 || ch.length != 32) revert BadAccount();
a.storageRoot = bytes32(sr);
a.codeHash = bytes32(ch);
}
/// @notice Prove one storage slot in an account's storage root. Reverts for a zero / absent slot.
function slot(bytes32 storageRoot, bytes32 key, bytes[] memory proof) internal pure returns (uint256) {
bytes memory rlpVal = SecureMerkleTrie.get(abi.encodePacked(key), proof, storageRoot);
return toUint(RLPReader.readBytes(rlpVal));
}
function toUint(bytes memory b) internal pure returns (uint256 v) {
if (b.length > 32) revert ValueTooLong();
for (uint256 i; i < b.length; i++) {
v = (v << 8) | uint8(b[i]);
}
}
}
src/cells/vendor/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/cells/vendor/MerkleTrie.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { Bytes } from "./Bytes.sol";
import { RLPReader } from "./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/cells/vendor/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/cells/vendor/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) }
}
}
}
src/cells/vendor/SecureMerkleTrie.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { MerkleTrie } from "./MerkleTrie.sol";
/// @title SecureMerkleTrie
/// @notice SecureMerkleTrie is a thin wrapper around the MerkleTrie library that hashes the input
/// keys. Ethereum's state trie hashes input keys before storing them.
library SecureMerkleTrie {
/// @notice Verifies a proof that a given key/value pair is present in the Merkle 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_)
{
bytes memory key = _getSecureKey(_key);
valid_ = MerkleTrie.verifyInclusionProof(key, _value, _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_) {
bytes memory key = _getSecureKey(_key);
value_ = MerkleTrie.get(key, _proof, _root);
}
/// @notice Computes the hashed version of the input key.
/// @param _key Key to hash.
/// @return hash_ Hashed version of the key.
function _getSecureKey(bytes memory _key) private pure returns (bytes memory hash_) {
hash_ = abi.encodePacked(keccak256(_key));
}
}
src/v2/CellCoreV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {EthStateProof} from "../cells/EthStateProof.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
/// @title CellCoreV2 — everything a wishRWA cell does, except WHO may record releases
/// @notice Shared by EthCellV2 (Ethereum; releases arrive through the Robinhood Chain rollup Outbox) and
/// BaseCellV2 (Base; releases arrive through Base's own messenger from our relay on Ethereum). The payout
/// rules (delay, payout days, daily limit, slow mode, shortfall ratio) are the same code for both.
/// Extracted from EthCellV2 on 13.11.2026 without changing its behaviour, storage layout or ABI.
/// @dev Storage layout is part of the protocol (Robinhood Chain proves slots): `deposits` = slot 0,
/// `depositCount` = 1, `ledger` = 2, `fillRecipient` = 8. New state only after slot 9. Checked by a test.
abstract contract CellCoreV2 is ReentrancyGuardTransient {
using SafeERC20 for IERC20;
uint256 public constant BPS = 10_000;
uint256 public constant WAD = 1e18;
uint256 public constant DELAY = 3 days;
uint256 public constant DAILY_BPS = 2_500;
uint256 public constant SLOW_PERIOD = 30 days;
uint256 public constant SLOW_EXTRA_DELAY = 11 days; // 3 + 11 = 14 days in slow mode
uint256 public constant SLOW_DAILY_BPS = 500;
/// @notice after this many payout days missed (joined but never settled — e.g. a beneficiary the token refuses),
/// only the beneficiary or a helper it chose may put the release back into a day: a release that can
/// never be paid must not dilute everyone else's days forever. Normal releases (paid each day) never
/// hit it, so anyone may keep serving them. Any payment > 0 resets the count; past it, anyone may still
/// put the release back one day in RETRY_EVERY (its own day of the week), so a release to an address
/// that never acts itself (an exchange, a contract) keeps moving after a few days nobody served it
/// (review 09.11), while an unpayable one dilutes at most one day in RETRY_EVERY.
uint256 public constant FREE_MISSES = 3;
uint256 public constant RETRY_EVERY = 7;
address public constant HISTORY = 0x0000F90827F1C53a10cb7A02335B175320002935; // EIP-2935
/// @notice keepers' reward (decision 13.11), in basis points of what a release pays, in steps like a tax:
/// up to the coin's daily minimum (`minDaily`, ≈ $550 at deployment) a release pays REWARD_LOW_BPS to the
/// one who delivered it (executed the rollup message) and as much to the one who paid it out; above it
/// REWARD_HIGH_BPS each. Nothing goes to the beneficiary itself or its helper. Our fees are not touched.
uint256 public constant REWARD_LOW_BPS = 5; // 0.05% + 0.05% = 0.1% below the threshold
uint256 public constant REWARD_HIGH_BPS = 5; // in tenths of a basis point: 0.005% + 0.005% = 0.01% above
uint256 internal constant REWARD_DENOM = BPS * 10; // so LOW is 5 bps (50/100000), HIGH is 0.5 bps (5/100000)
/// @notice how far a release that has not arrived yet follows its owners' redirections (resales in flight)
uint256 public constant MAX_REDIRECTS = 8;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("ReleasePermit(uint256 releaseId,address owner,address operator,uint256 nonce,uint256 deadline)");
mapping(uint256 id => bytes32) public deposits; // slot 0
uint256 public depositCount; // slot 1
struct Ledger {
uint256 cumDeposited;
uint256 cumRecorded;
uint256 cumSettled;
uint256 cumPaid;
}
mapping(address token => Ledger) public ledger; // slot 2
struct Release {
address token;
address beneficiary;
uint128 remaining;
uint64 maturesAt;
uint64 round; // day it waits in (0 = none)
uint32 misses; // payout days it joined but that passed without being settled
}
mapping(uint256 releaseId => Release) public releases; // slot 3
mapping(uint256 releaseId => bool) public recorded; // slot 4
struct Round {
uint128 budget; // nominal this day's waiters may take (paid on the NEXT day only)
uint128 joined; // nominal waiting in this day
uint128 settled; // nominal already settled out of this day
bool slow; // the budget was set in slow mode
}
mapping(address token => mapping(uint256 day => Round)) public rounds; // slot 5
mapping(address token => uint256) public minDaily; // slot 6
address[] private _tokens; // slot 7
mapping(bytes32 orderHash => address) public fillRecipient; // slot 8
mapping(bytes32 orderHash => address) public filler; // slot 9
// ---------------------------------------------------------------- slow mode (state after slot 9)
struct Wire {
address target; // a contract whose upgrade could forge a release (rollup Bridge, Outbox, upgrade keys…)
bytes32 slot; // a slot that must not change silently (e.g. EIP-1967 implementation)
}
Wire[] private _wires; // fixed in the constructor
mapping(uint256 wire => uint256) public lastSeen; // value last proven (starts at the expected value)
mapping(uint256 wire => uint256) public lastBlock; // block of the last proof (proofs only move forward)
uint256 public slowUntil;
error InvalidConfig();
error NotController();
error NotToken(address token);
error ZeroAmount();
error AlreadyRecorded(uint256 releaseId);
error UnknownRelease(uint256 releaseId);
error NotBeneficiary();
error NotMature(uint256 maturesAt);
error Overflow();
error Expired(uint256 deadline);
error AlreadyFilled();
error Shortfall();
error Underpaid(uint256 received, uint256 payOut);
error NothingToPay();
error UnknownBlock(uint256 number);
error OldProof();
error Unchanged();
error NotAllowed();
event Deposited(uint256 indexed id, address indexed token, uint256 amount, address indexed l2Recipient);
event Recorded(uint256 indexed releaseId, address indexed token, uint256 amount, address indexed beneficiary);
event Joined(uint256 indexed releaseId, uint256 indexed day, uint256 remaining);
event Paid(uint256 indexed releaseId, address indexed to, uint256 nominal, uint256 amount);
event Filled(bytes32 indexed orderHash, uint256 indexed orderId, address indexed filler, address rhRecipient);
event TokenAdded(address indexed token, uint256 minDaily);
event SlowMode(uint256 indexed wire, uint256 oldValue, uint256 newValue, uint256 until);
event Rewarded(
uint256 indexed releaseId,
address indexed deliverer,
uint256 toDeliverer,
address indexed payer,
uint256 toPayer
);
event ReleaseTransferred(uint256 indexed releaseId, address indexed from, address indexed to);
event ReleaseRedirected(uint256 indexed releaseId, address indexed from, address indexed to);
event ReleaseOperator(uint256 indexed releaseId, address indexed owner, address indexed operator);
error BadSignature();
error SignatureExpired(uint256 deadline);
constructor(
address[] memory tokens_,
uint256[] memory minDaily_,
Wire[] memory wires_,
uint256[] memory expected_
) {
if (tokens_.length == 0 || tokens_.length != minDaily_.length) {
revert InvalidConfig();
}
if (wires_.length != expected_.length) revert InvalidConfig();
for (uint256 i; i < tokens_.length; i++) {
if (tokens_[i] == address(0) || minDaily_[i] == 0 || minDaily[tokens_[i]] != 0) revert InvalidConfig();
minDaily[tokens_[i]] = minDaily_[i];
_tokens.push(tokens_[i]);
}
for (uint256 i; i < wires_.length; i++) {
if (wires_[i].target == address(0) || expected_[i] == 0) revert InvalidConfig();
_wires.push(wires_[i]);
lastSeen[i] = expected_[i];
}
}
/// @dev reverts NotController unless the call is a message of this cell's basket (chain-specific)
function _onlyController() internal view virtual;
// ================================================================ in
function deposit(IERC20 token, uint256 amount, address l2Recipient) external nonReentrant returns (uint256 id) {
if (minDaily[address(token)] == 0) revert NotToken(address(token));
if (amount == 0 || l2Recipient == address(0)) revert ZeroAmount();
if (ratio(address(token)) < WAD) revert Shortfall();
uint256 before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 got = token.balanceOf(address(this)) - before;
if (got == 0) revert ZeroAmount();
id = ++depositCount;
deposits[id] = keccak256(abi.encode(address(token), got, l2Recipient));
ledger[address(token)].cumDeposited += got;
emit Deposited(id, address(token), got, l2Recipient);
}
// ================================================================ fast exit
function orderHash(uint256 orderId, address token, uint256 amount, uint256 payOut, address l1To, uint256 deadline)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(orderId, token, amount, payOut, l1To, deadline));
}
/// @notice Pay a fast-exit order: you send `gross` of `token` straight to the exiter `l1To`, who must RECEIVE
/// at least `payOut` (for a coin with a transfer fee send a little more). Prove the fill on Robinhood
/// Chain to get `amount` as credit for `rhRecipient`. CHECK THE ORDER ON ROBINHOOD CHAIN FIRST.
function fill(
uint256 orderId,
address token,
uint256 amount,
uint256 payOut,
address l1To,
uint256 deadline,
address rhRecipient,
uint256 gross
) external nonReentrant returns (bytes32 h) {
if (minDaily[token] == 0) revert NotToken(token);
if (block.timestamp > deadline) revert Expired(deadline);
if (payOut == 0 || payOut > amount || l1To == address(0) || rhRecipient == address(0)) revert ZeroAmount();
if (l1To == msg.sender || l1To == address(this)) revert ZeroAmount(); // receipt must be measurable
h = orderHash(orderId, token, amount, payOut, l1To, deadline);
if (fillRecipient[h] != address(0)) revert AlreadyFilled();
fillRecipient[h] = rhRecipient;
filler[h] = msg.sender;
uint256 before = IERC20(token).balanceOf(l1To);
IERC20(token).safeTransferFrom(msg.sender, l1To, gross);
uint256 got = IERC20(token).balanceOf(l1To) - before;
if (got < payOut) revert Underpaid(got, payOut);
emit Filled(h, orderId, msg.sender, rhRecipient);
}
// ================================================================ out: record (from Robinhood Chain)
function record(uint256 releaseId, address token, uint256 amount, address beneficiary, bytes32 order)
external
nonReentrant
{
_onlyController();
if (recorded[releaseId]) revert AlreadyRecorded(releaseId);
if (minDaily[token] == 0) revert NotToken(token);
if (amount > type(uint128).max) revert Overflow();
recorded[releaseId] = true;
ledger[token].cumRecorded += amount;
if (order != bytes32(0) && filler[order] != address(0)) beneficiary = filler[order];
// sold while in flight: follow the owners' redirections (each set by the owner of that moment)
for (uint256 i; i < MAX_REDIRECTS; i++) {
address next = redirect[releaseId][beneficiary];
if (next == address(0)) break;
beneficiary = next;
}
delivererOf[releaseId] = _deliverer();
releases[releaseId] = Release({
token: token,
beneficiary: beneficiary,
remaining: uint128(amount),
maturesAt: uint64(block.timestamp + DELAY),
round: 0,
misses: 0
});
emit Recorded(releaseId, token, amount, beneficiary);
}
/// @notice A new coin voted into the basket on Robinhood Chain (only as a message of the
/// controller). Coins already held keep their settings; nothing else changes.
function addToken(address token, uint256 minDaily_) external nonReentrant {
_onlyController();
if (token == address(0) || minDaily_ == 0) revert InvalidConfig();
if (minDaily[token] != 0) return; // already held
minDaily[token] = minDaily_;
_tokens.push(token);
emit TokenAdded(token, minDaily_);
}
/// @notice Share of each nominal unit the cell pays right now (WAD = in full). See EthCell for the reasoning.
function ratio(address token) public view returns (uint256) {
Ledger storage l = ledger[token];
if (l.cumSettled > l.cumDeposited) return 0;
uint256 outstanding = l.cumDeposited - l.cumSettled;
uint256 bal = IERC20(token).balanceOf(address(this));
if (bal >= outstanding) return WAD;
return bal * WAD / outstanding;
}
// ================================================================ out: pay (on Ethereum)
function isSlow() public view returns (bool) {
return block.timestamp < slowUntil;
}
/// @notice when a release may join a payout day (later while slow mode is on)
function joinableAt(uint256 releaseId) public view returns (uint256) {
uint256 t = releases[releaseId].maturesAt;
return isSlow() ? t + SLOW_EXTRA_DELAY : t;
}
/// @notice helpers a beneficiary allows to keep its releases in the payout queue after FREE_JOINS
mapping(address beneficiary => mapping(address helper => bool)) public isHelper;
event HelperSet(address indexed beneficiary, address indexed helper, bool allowed);
function setHelper(address helper, bool allowed) external {
isHelper[msg.sender][helper] = allowed;
emit HelperSet(msg.sender, helper, allowed);
}
// ---------------------------------------------------------------- keepers and transfers (state after isHelper)
/// @notice who delivered the release (sent the transaction that executed its rollup message)
mapping(uint256 releaseId => address) public delivererOf;
/// @notice what the release has paid so far (before rewards): the steps of the reward follow it
mapping(uint256 releaseId => uint256) public paidGross;
/// @notice a release not recorded yet: when it arrives for `owner`, it is recorded for `redirect` instead
mapping(uint256 releaseId => mapping(address owner => address)) public redirect;
/// @notice who may transfer `owner`'s release (a market contract), while `owner` owns it
mapping(uint256 releaseId => mapping(address owner => address)) public operatorOf;
/// @notice permits used by `owner`
mapping(address owner => uint256) public nonces;
/// @dev the one who delivered the release now being recorded; Ethereum: the sender of the transaction that
/// executes the rollup Outbox (only a reward goes there, nothing else depends on it)
function _deliverer() internal view virtual returns (address) {
return tx.origin; // solhint-disable-line avoid-tx-origin
}
/// @notice the reward a payment of `amount` makes, after `before` already paid, for one keeper (two keepers)
function rewardFor(address token, uint256 before, uint256 amount) public view returns (uint256) {
return (_steps(before + amount, minDaily[token]) - _steps(before, minDaily[token])) / REWARD_DENOM;
}
function _steps(uint256 x, uint256 threshold) private pure returns (uint256) {
return
x <= threshold
? x * REWARD_LOW_BPS * 10
: threshold * REWARD_LOW_BPS * 10 + (x - threshold) * REWARD_HIGH_BPS;
}
/// @dev pays the keepers of this payment of `paid`; returns what was taken from it. A keeper the token refuses
/// (a blocked address) simply gets nothing: a reward must never stop a payout.
function _reward(uint256 releaseId, Release storage r, uint256 paid) private returns (uint256 taken) {
uint256 each = rewardFor(r.token, paidGross[releaseId], paid);
paidGross[releaseId] += paid;
if (each == 0) return 0;
address b = r.beneficiary;
address d = delivererOf[releaseId];
uint256 toD = _stranger(b, d) && _trySend(r.token, d, each) ? each : 0;
uint256 toP = _stranger(b, msg.sender) && _trySend(r.token, msg.sender, each) ? each : 0;
taken = toD + toP;
if (taken != 0) emit Rewarded(releaseId, d, toD, msg.sender, toP);
}
function _stranger(address beneficiary, address a) private view returns (bool) {
return a != address(0) && a != beneficiary && !isHelper[beneficiary][a];
}
function _trySend(address token, address to, uint256 amount) private returns (bool) {
(bool ok, bytes memory ret) = token.call(abi.encodeCall(IERC20.transfer, (to, amount)));
return ok && (ret.length == 0 ? token.code.length != 0 : (ret.length == 32 && abi.decode(ret, (bool))));
}
/// @notice Give the release to `to` — now if it is recorded here, or, if it is still on its way, as soon as it
/// arrives. Only its owner (`from`) or the contract `from` allowed (`operatorOf`). A recorded release
/// keeps its place in the payout queue; `from`'s helpers no longer act for it.
function transferRelease(uint256 releaseId, address from, address to) external {
if (to == address(0) || to == address(this)) revert ZeroAmount();
if (msg.sender != from && msg.sender != operatorOf[releaseId][from]) revert NotAllowed();
delete operatorOf[releaseId][from];
Release storage r = releases[releaseId];
if (recorded[releaseId]) {
if (r.beneficiary != from) revert NotBeneficiary();
if (r.remaining == 0) revert NothingToPay();
r.beneficiary = to;
r.misses = 0; // a new owner: not the unpayable beneficiary FREE_MISSES protects against
emit ReleaseTransferred(releaseId, from, to);
} else {
redirect[releaseId][from] = to;
emit ReleaseRedirected(releaseId, from, to);
}
}
/// @notice allow `operator` (e.g. a market) to transfer your release `releaseId` (zero: take it back)
function approveRelease(uint256 releaseId, address operator) external {
operatorOf[releaseId][msg.sender] = operator;
emit ReleaseOperator(releaseId, msg.sender, operator);
}
/// @notice the same as `approveRelease`, by a signature of `owner` (free for the owner; anyone may send it).
/// Works for ordinary wallets and for contract wallets (ERC-1271, e.g. a Safe).
function permitRelease(uint256 releaseId, address owner, address operator, uint256 deadline, bytes calldata sig)
external
{
if (block.timestamp > deadline) revert SignatureExpired(deadline);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator(),
keccak256(abi.encode(PERMIT_TYPEHASH, releaseId, owner, operator, nonces[owner]++, deadline))
)
);
if (!SignatureChecker.isValidSignatureNow(owner, digest, sig)) revert BadSignature();
operatorOf[releaseId][owner] = operator;
emit ReleaseOperator(releaseId, owner, operator);
}
/// @notice EIP-712 domain of this cell (computed, so nothing is stored before `deposits`)
function domainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256("wishBASKET cell"),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/// @notice Put a matured release into today's payout. It is paid on the NEXT day (claim / claimFor); not
/// claimed then, it must join again. Anyone may do this, until the release missed FREE_MISSES days;
/// then only the beneficiary or its helper (or anyone on the release's retry day).
function join(uint256 releaseId) public {
_join(releaseId, msg.sender, true);
}
/// @dev strict = false (from a claim): a release that may not join now is left out, nothing reverts
function _join(uint256 releaseId, address caller, bool strict) private {
Release storage r = releases[releaseId];
if (r.token == address(0)) revert UnknownRelease(releaseId);
uint256 at = joinableAt(releaseId);
if (block.timestamp < at) revert NotMature(at);
uint256 day = block.timestamp / 1 days;
if (r.remaining == 0) return;
if (r.round != 0) {
if (r.round + 1 >= day) return; // already waiting (today) or payable (yesterday's round)
r.round = 0; // its payable day passed unclaimed: the budget expired, join again
r.misses += 1;
}
if (!_mayJoin(r, caller, releaseId, day)) {
if (strict) revert NotAllowed();
return;
}
Round storage rd = _round(r.token, day);
rd.joined += r.remaining;
r.round = uint64(day);
emit Joined(releaseId, day, r.remaining);
}
function claim(uint256 releaseId, address to) external nonReentrant returns (uint256 paid) {
Release storage r = releases[releaseId];
if (r.token == address(0)) revert UnknownRelease(releaseId);
if (msg.sender != r.beneficiary) revert NotBeneficiary();
if (to == address(0)) revert ZeroAmount();
paid = _settle(releaseId, r, to, false);
}
function claimFor(uint256 releaseId) external nonReentrant returns (uint256 paid) {
Release storage r = releases[releaseId];
if (r.token == address(0)) revert UnknownRelease(releaseId);
paid = _settle(releaseId, r, r.beneficiary, true);
}
function _settle(uint256 releaseId, Release storage r, address to, bool byAnyone) private returns (uint256 paid) {
uint256 day = block.timestamp / 1 days;
bool ripe = block.timestamp >= joinableAt(releaseId);
// not ripe (before maturity, or slow mode turned on after it joined): nothing is paid until it is
if (!ripe) revert NotMature(joinableAt(releaseId));
if (r.round != 0 && r.round + 1 == day) {
Round storage rd = rounds[r.token][r.round];
uint256 budget = rd.budget;
// slow mode turned on after this day's budget was set: the day pays at the slow rate too
if (isSlow() && !rd.slow) budget = budget * SLOW_DAILY_BPS / DAILY_BPS;
uint256 nominal = rd.joined <= budget ? r.remaining : uint256(r.remaining) * budget / rd.joined;
paid = nominal * ratio(r.token) / WAD;
if (byAnyone && paid == 0) revert NothingToPay(); // nobody but the beneficiary may write off dust
uint256 bal = IERC20(r.token).balanceOf(address(this));
if (paid > bal) paid = bal;
r.remaining -= uint128(nominal);
r.round = 0;
rd.settled += uint128(nominal);
Ledger storage l = ledger[r.token];
l.cumSettled += nominal;
if (paid != 0) {
r.misses = 0; // it can be paid: not the release FREE_MISSES protects against
l.cumPaid += paid;
paid -= _reward(releaseId, r, paid);
IERC20(r.token).safeTransfer(to, paid);
}
emit Paid(releaseId, to, nominal, paid);
}
if (ripe && r.remaining != 0 && (r.round == 0 || r.round + 1 < day)) _join(releaseId, msg.sender, false);
}
function _mayJoin(Release storage r, address caller, uint256 releaseId, uint256 day) private view returns (bool) {
return r.misses < FREE_MISSES || caller == r.beneficiary || isHelper[r.beneficiary][caller]
|| (day + releaseId) % RETRY_EVERY == 0;
}
/// @dev today's round; its budget is fixed at the first touch: a share of the balance MINUS what yesterday's
/// round may still pay today (so two days' budgets never stack)
function _round(address token, uint256 day) private returns (Round storage rd) {
rd = rounds[token][day];
if (rd.budget == 0) {
Round storage prev = rounds[token][day - 1];
uint256 prevOpen = prev.joined < prev.budget ? prev.joined : prev.budget;
prevOpen = prevOpen > prev.settled ? prevOpen - prev.settled : 0;
uint256 bal = IERC20(token).balanceOf(address(this));
uint256 base = bal > prevOpen ? bal - prevOpen : 0;
uint256 b = base * (isSlow() ? SLOW_DAILY_BPS : DAILY_BPS) / BPS;
uint256 m = isSlow() ? minDaily[token] * SLOW_DAILY_BPS / DAILY_BPS : minDaily[token];
if (b < m) b = m;
if (b > type(uint128).max) b = type(uint128).max;
if (b == 0) b = 1;
rd.budget = uint128(b);
rd.slow = isSlow();
}
}
// ================================================================ slow mode
/// @notice Prove that watched slot `wire` of a rollup contract now holds a different value than last proven.
/// The block must be one of the last 8191 (its hash is read on-chain, nothing to trust).
function trip(
uint256 wire,
bytes calldata rlpHeader,
uint256 number,
bytes[] calldata accountProof,
bytes[] calldata slotProof
) external {
if (number <= lastBlock[wire]) revert OldProof();
uint256 v = _proveWire(wire, rlpHeader, number, accountProof, slotProof);
lastBlock[wire] = number;
uint256 old = lastSeen[wire];
if (v == old) revert Unchanged();
lastSeen[wire] = v;
slowUntil = block.timestamp + SLOW_PERIOD;
emit SlowMode(wire, old, v, slowUntil);
}
function _proveWire(
uint256 wire,
bytes calldata rlpHeader,
uint256 number,
bytes[] calldata accountProof,
bytes[] calldata slotProof
) private view returns (uint256) {
Wire memory w = _wires[wire];
EthStateProof.Header memory hd = EthStateProof.header(rlpHeader, _wireBlockHash(wire, number));
EthStateProof.Account memory a = EthStateProof.account(hd.stateRoot, w.target, accountProof);
return EthStateProof.slot(a.storageRoot, w.slot, slotProof);
}
/// @dev the trusted hash of block `number` of the chain watched wire `wire` lives on: by default this chain
/// (BaseCellV2 also watches slots on Ethereum, through Ethereum hashes recorded on Base)
function _wireBlockHash(uint256 wire, uint256 number) internal view virtual returns (bytes32) {
wire; // the default does not depend on the wire
return _blockHash(number);
}
function _blockHash(uint256 number) private view returns (bytes32 h) {
if (number >= block.number) revert UnknownBlock(number);
h = blockhash(number);
if (h == bytes32(0) && HISTORY.code.length != 0) {
(bool ok, bytes memory out) = HISTORY.staticcall(abi.encode(number));
if (ok && out.length == 32) h = abi.decode(out, (bytes32));
}
if (h == bytes32(0)) revert UnknownBlock(number);
}
// ================================================================ views
function tokens() external view returns (address[] memory) {
return _tokens;
}
function wires() external view returns (Wire[] memory) {
return _wires;
}
/// @notice remaining nominal, the part payable from its round (estimate while the round is open), coins at
/// today's ratio, and when it may join
function pending(uint256 releaseId)
external
view
returns (uint256 remaining, uint256 thisRound, uint256 coins, uint256 joinAt)
{
Release storage r = releases[releaseId];
remaining = r.remaining;
joinAt = joinableAt(releaseId);
if (r.round != 0) {
Round storage rd = rounds[r.token][r.round];
thisRound = rd.joined <= rd.budget ? r.remaining : uint256(r.remaining) * rd.budget / rd.joined;
coins = thisRound * ratio(r.token) / WAD;
}
}
}
src/v2/EthCellV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {CellCoreV2} from "./CellCoreV2.sol";
/// @notice Arbitrum bridge on the parent chain: knows which outbox is executing an L2 → L1 message.
interface IArbBridgeV2 {
function activeOutbox() external view returns (address);
}
interface IArbOutboxV2 {
function l2ToL1Sender() external view returns (address);
}
/// @title EthCellV2 (lives on Ethereum) — the cell of wishRWA
/// @notice Holds the Ethereum coins of ONE basket on Robinhood Chain. No owner, no keys, no settings.
/// Releases are recorded only from the controller on Robinhood Chain, through the rollup's Outbox.
/// Payout rules, fast-exit `fill`, slow mode and the storage layout live in CellCoreV2 (shared with
/// BaseCellV2).
contract EthCellV2 is CellCoreV2 {
IArbBridgeV2 public immutable bridge;
address public immutable controller;
constructor(
IArbBridgeV2 bridge_,
address controller_,
address[] memory tokens_,
uint256[] memory minDaily_,
Wire[] memory wires_,
uint256[] memory expected_
) CellCoreV2(tokens_, minDaily_, wires_, expected_) {
if (address(bridge_) == address(0) || controller_ == address(0)) {
revert InvalidConfig();
}
bridge = bridge_;
controller = controller_;
}
function _onlyController() internal view override {
address outbox = bridge.activeOutbox();
if (msg.sender != address(bridge) || outbox == address(0)) revert NotController();
if (IArbOutboxV2(outbox).l2ToL1Sender() != controller) revert NotController();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.