Verified contractPartialMIT
Bridger
Address0xf227f9340a4970d4ee2cdfd8ac48978ee3ab8b6f
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 800 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,221,631
- Creation transaction
- 0xe2351eee78…7742a62d31
- Main copy (most transactions)
- 0x02bc6bba…e573ed05
16 files
- src/v2/ethereum/Bridger.solmain8.67 KB
- node_modules/@openzeppelin/contracts/access/Ownable.sol3.1 KB
- node_modules/@openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC165.sol193 B
- node_modules/@openzeppelin/contracts/interfaces/IERC20.sol182 B
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol2.85 KB
- node_modules/@openzeppelin/contracts/utils/TransientSlot.sol5.08 KB
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- src/v2/interfaces/IArcStocksV2.sol520 B
- src/v2/libs/Arbitrum.sol2 KB
- src/v2/libs/CctpV2.sol6.01 KB
- src/v2/libs/Messages.sol4.65 KB
src/v2/ethereum/Bridger.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Messages} from "../libs/Messages.sol";
import {CctpV2, ITokenMessengerV2, IMessageTransmitterV2} from "../libs/CctpV2.sol";
import {IInbox, IBridge, IOutbox} from "../libs/Arbitrum.sol";
import {IReserveVaultDeliver, IBridgerCheckpoint} from "../interfaces/IArcStocksV2.sol";
/// @title Bridger — the canonical relay on Ethereum
/// @notice Two one-way pipes with no operator:
///
/// Arc (gate) ──CCTP──▶ relay() ──retryable ticket──▶ vault.deliver() on Robinhood Chain
/// Robinhood Chain ──outbox (7 days)──▶ acceptCheckpoint() ──CCTP hook──▶ gate on Arc
///
/// Anyone may call `relay` and `retry`; Circle's attestation and the rollup's outbox are the
/// only authorities. The bridger holds a little USDC (to pay the 1 USDC that carries a hook)
/// and nothing else of value.
contract Bridger is Ownable2Step, ReentrancyGuardTransient, IBridgerCheckpoint {
using SafeERC20 for IERC20;
IMessageTransmitterV2 public immutable messageTransmitter;
ITokenMessengerV2 public immutable tokenMessenger;
IERC20 public immutable usdc;
IInbox public immutable inbox;
IBridge public immutable bridge;
/// @notice CCTP domain of Arc and its TokenMessengerV2, the only sender `relay` accepts.
uint32 public immutable arcDomain;
bytes32 public immutable arcTokenMessenger;
/// @notice The canonical gate on Arc (the burn's `messageSender`, and where checkpoints are sent).
address public immutable gate;
address public immutable vault;
/// @notice Deliveries relayed from Arc, kept so a lapsed retryable can be re-created by anyone.
mapping(bytes32 ref => Messages.Deliver) private _deliveries;
mapping(bytes32 ref => bool) public relayed;
/// @notice Checkpoints received from the rollup, forwarded to Arc as soon as USDC is on hand.
Messages.Checkpoint[] private _checkpoints;
uint256 public forwardedThrough;
event Relayed(bytes32 indexed ref, address indexed underlying, uint128 shares, address to, uint256 ticket);
event Retried(bytes32 indexed ref, uint256 ticket);
event CheckpointAccepted(uint256 indexed index, bytes32 root, uint64 fromSeq, uint64 toSeq);
event CheckpointForwarded(uint256 indexed index, bytes32 root);
event Funded(uint256 amount);
error WrongSource(uint32 domain, bytes32 sender);
error NotFromGate(bytes32 messageSender);
error ReceiveFailed();
error UnknownRef(bytes32 ref);
error NotOutbox(address sender);
error NotFromVault(address l2Sender);
error NothingToForward();
error InsufficientUsdc(uint256 have, uint256 need);
constructor(
address messageTransmitter_,
address tokenMessenger_,
address usdc_,
address inbox_,
address bridge_,
uint32 arcDomain_,
address arcTokenMessenger_,
address gate_,
address vault_,
address owner_
) Ownable(owner_) {
messageTransmitter = IMessageTransmitterV2(messageTransmitter_);
tokenMessenger = ITokenMessengerV2(tokenMessenger_);
usdc = IERC20(usdc_);
inbox = IInbox(inbox_);
bridge = IBridge(bridge_);
arcDomain = arcDomain_;
arcTokenMessenger = CctpV2.toBytes32(arcTokenMessenger_);
gate = gate_;
vault = vault_;
}
// ------------------------------------------------------------------ Arc → Robinhood Chain
/// @notice Redeem an attested burn from the hub and turn its hook into a retryable ticket that
/// calls `vault.deliver`. `msg.value` pays the ticket (submission + L2 gas); the excess is
/// refunded on the rollup to `msg.sender`.
function relay(bytes calldata message, bytes calldata attestation, uint256 gasLimit, uint256 maxFeePerGas)
external
payable
nonReentrant
returns (uint256 ticket)
{
if (!messageTransmitter.receiveMessage(message, attestation)) revert ReceiveFailed();
CctpV2.Parsed memory p = CctpV2.parse(message);
if (p.sourceDomain != arcDomain || p.sender != arcTokenMessenger) revert WrongSource(p.sourceDomain, p.sender);
if (CctpV2.toAddress(p.messageSender) != gate) revert NotFromGate(p.messageSender);
Messages.Deliver memory d = Messages.decodeDeliver(p.hookData);
_deliveries[d.ref] = d;
relayed[d.ref] = true;
ticket = _ticket(d, gasLimit, maxFeePerGas);
emit Relayed(d.ref, d.underlying, d.shares, d.to, ticket);
}
/// @notice A retryable ticket lives seven days; if nobody redeemed it, anyone re-creates it here.
/// The vault ignores a ref it already settled, so retrying is always safe.
function retry(bytes32 ref, uint256 gasLimit, uint256 maxFeePerGas) external payable nonReentrant returns (uint256 ticket) {
if (!relayed[ref]) revert UnknownRef(ref);
ticket = _ticket(_deliveries[ref], gasLimit, maxFeePerGas);
emit Retried(ref, ticket);
}
function deliveryOf(bytes32 ref) external view returns (Messages.Deliver memory) {
return _deliveries[ref];
}
// ------------------------------------------------------------------ Robinhood Chain → Arc
/// @notice Called by the rollup's outbox when a vault checkpoint is executed on Ethereum.
function acceptCheckpoint(Messages.Checkpoint calldata c) external override nonReentrant {
if (msg.sender != address(bridge)) revert NotOutbox(msg.sender);
address l2Sender = IOutbox(bridge.activeOutbox()).l2ToL1Sender();
if (l2Sender != vault) revert NotFromVault(l2Sender);
_checkpoints.push(c);
emit CheckpointAccepted(_checkpoints.length - 1, c.root, c.fromSeq, c.toSeq);
if (usdc.balanceOf(address(this)) >= HOOK_AMOUNT) _forward();
}
/// @notice Sends every accepted-but-unforwarded checkpoint to the hub as a CCTP hook. Anyone.
function forward() external nonReentrant {
if (forwardedThrough == _checkpoints.length) revert NothingToForward();
_forward();
}
function checkpointCount() external view returns (uint256) {
return _checkpoints.length;
}
function checkpointAt(uint256 i) external view returns (Messages.Checkpoint memory) {
return _checkpoints[i];
}
// ------------------------------------------------------------------ funds
/// @notice USDC that rides along with hooks. 1 USDC per checkpoint; Standard Transfer, no fee.
uint256 public constant HOOK_AMOUNT = 1e6;
function fund(uint256 amount) external {
usdc.safeTransferFrom(msg.sender, address(this), amount);
emit Funded(amount);
}
function withdraw(address to, uint256 amount) external onlyOwner {
usdc.safeTransfer(to, amount);
}
receive() external payable {}
// ------------------------------------------------------------------ internals
function _ticket(Messages.Deliver memory d, uint256 gasLimit, uint256 maxFeePerGas) private returns (uint256) {
bytes memory data = abi.encodeCall(IReserveVaultDeliver.deliver, (d));
uint256 submission = inbox.calculateRetryableSubmissionFee(data.length, block.basefee);
return inbox.createRetryableTicket{value: msg.value}(
vault, 0, submission, msg.sender, msg.sender, gasLimit, maxFeePerGas, data
);
}
function _forward() private {
uint256 n = _checkpoints.length;
for (uint256 i = forwardedThrough; i < n; ++i) {
uint256 have = usdc.balanceOf(address(this));
if (have < HOOK_AMOUNT) revert InsufficientUsdc(have, HOOK_AMOUNT);
usdc.forceApprove(address(tokenMessenger), HOOK_AMOUNT);
tokenMessenger.depositForBurnWithHook(
HOOK_AMOUNT,
arcDomain,
CctpV2.toBytes32(gate),
address(usdc),
CctpV2.toBytes32(gate),
0,
CctpV2.FINALITY_FINALIZED,
Messages.encode(_checkpoints[i])
);
forwardedThrough = i + 1;
emit CheckpointForwarded(i, _checkpoints[i].root);
}
}
}
node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
node_modules/@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
node_modules/@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
node_modules/@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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._
*
* @custom:stateless
*/
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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
_reentrancyGuardStorageSlot().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 _reentrancyGuardStorageSlot().asBoolean().tload();
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
node_modules/@openzeppelin/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 represents a slot holding an 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 represents 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 represents 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 represents 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 represents 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)
}
}
}
node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/v2/interfaces/IArcStocksV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Messages} from "../libs/Messages.sol";
/// @notice What the canonical lane calls on the reserve vault: hand stock (or its proceeds) to a holder.
interface IReserveVaultDeliver {
function deliver(Messages.Deliver calldata d) external;
}
/// @notice What the reserve chain's outbox calls on the Ethereum bridger: a Merkle root of vault results.
interface IBridgerCheckpoint {
function acceptCheckpoint(Messages.Checkpoint calldata c) external;
}
src/v2/libs/Arbitrum.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title Arbitrum — the slice of the Nitro bridge that ArcStocks talks to
/// @notice Robinhood Chain is an Arbitrum Nitro rollup settling to Ethereum. Ethereum → Robinhood
/// goes through the Delayed Inbox as a retryable ticket; Robinhood → Ethereum goes through
/// ArbSys and, seven days later, the Outbox.
/// @notice Delayed Inbox on the parent chain.
interface IInbox {
function createRetryableTicket(
address to,
uint256 l2CallValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
bytes calldata data
) external payable returns (uint256);
function calculateRetryableSubmissionFee(uint256 dataLength, uint256 baseFee) external view returns (uint256);
}
/// @notice ArbSys precompile at 0x64 on the rollup.
interface IArbSys {
function sendTxToL1(address destination, bytes calldata data) external payable returns (uint256);
}
/// @notice Bridge on the parent chain: every executed outbox message is a call from here.
interface IBridge {
function activeOutbox() external view returns (address);
}
/// @notice Outbox on the parent chain: tells the callee which L2 account sent the message being executed.
interface IOutbox {
function l2ToL1Sender() external view returns (address);
}
library AddressAlias {
uint160 internal constant OFFSET = uint160(0x1111000000000000000000000000000000001111);
/// @notice What `msg.sender` looks like on the rollup when a parent-chain contract sends a retryable.
function applyL1ToL2Alias(address l1) internal pure returns (address) {
unchecked {
return address(uint160(l1) + OFFSET);
}
}
function undoL1ToL2Alias(address l2) internal pure returns (address) {
unchecked {
return address(uint160(l2) - OFFSET);
}
}
}
src/v2/libs/CctpV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title CctpV2 — the slice of Circle's CCTP v2 that ArcStocks talks to
/// @notice Hooks in CCTP v2 are opaque: Circle attests the burn, the destination caller executes
/// `receiveMessage` itself and then reads the hook data out of the message. This library
/// parses the MessageV2 header and BurnMessageV2 body exactly as Circle lays them out
/// (see evm-cctp-contracts `MessageV2.sol` / `BurnMessageV2.sol`).
library CctpV2 {
// MessageV2 header offsets
uint256 private constant VERSION_INDEX = 0; // uint32
uint256 private constant SOURCE_DOMAIN_INDEX = 4; // uint32
uint256 private constant DESTINATION_DOMAIN_INDEX = 8; // uint32
uint256 private constant NONCE_INDEX = 12; // bytes32
uint256 private constant SENDER_INDEX = 44; // bytes32
uint256 private constant RECIPIENT_INDEX = 76; // bytes32
uint256 private constant DESTINATION_CALLER_INDEX = 108; // bytes32
uint256 private constant MIN_FINALITY_THRESHOLD_INDEX = 140; // uint32
uint256 private constant FINALITY_THRESHOLD_EXECUTED_INDEX = 144; // uint32
uint256 private constant MESSAGE_BODY_INDEX = 148;
// BurnMessageV2 body offsets (relative to body start)
uint256 private constant BODY_VERSION_INDEX = 0; // uint32
uint256 private constant BURN_TOKEN_INDEX = 4; // bytes32
uint256 private constant MINT_RECIPIENT_INDEX = 36; // bytes32
uint256 private constant AMOUNT_INDEX = 68; // uint256
uint256 private constant MSG_SENDER_INDEX = 100; // bytes32
uint256 private constant MAX_FEE_INDEX = 132; // uint256
uint256 private constant FEE_EXECUTED_INDEX = 164; // uint256
uint256 private constant EXPIRATION_BLOCK_INDEX = 196; // uint256
uint256 private constant HOOK_DATA_INDEX = 228;
/// @notice Finality thresholds: Fast (confirmed) vs Standard (finalized).
uint32 internal constant FINALITY_CONFIRMED = 1000;
uint32 internal constant FINALITY_FINALIZED = 2000;
struct Parsed {
uint32 sourceDomain;
uint32 destinationDomain;
bytes32 nonce;
bytes32 sender; // the TokenMessengerV2 on the source chain
bytes32 recipient; // the TokenMessengerV2 on this chain
bytes32 destinationCaller;
uint32 finalityThresholdExecuted;
bytes32 burnToken;
bytes32 mintRecipient;
uint256 amount;
bytes32 messageSender; // who called depositForBurnWithHook on the source chain
bytes hookData;
}
error MessageTooShort(uint256 length);
function parse(bytes memory message) internal pure returns (Parsed memory p) {
if (message.length < MESSAGE_BODY_INDEX + HOOK_DATA_INDEX) revert MessageTooShort(message.length);
p.sourceDomain = uint32(_u(message, SOURCE_DOMAIN_INDEX, 4));
p.destinationDomain = uint32(_u(message, DESTINATION_DOMAIN_INDEX, 4));
p.nonce = bytes32(_u(message, NONCE_INDEX, 32));
p.sender = bytes32(_u(message, SENDER_INDEX, 32));
p.recipient = bytes32(_u(message, RECIPIENT_INDEX, 32));
p.destinationCaller = bytes32(_u(message, DESTINATION_CALLER_INDEX, 32));
p.finalityThresholdExecuted = uint32(_u(message, FINALITY_THRESHOLD_EXECUTED_INDEX, 4));
uint256 b = MESSAGE_BODY_INDEX;
p.burnToken = bytes32(_u(message, b + BURN_TOKEN_INDEX, 32));
p.mintRecipient = bytes32(_u(message, b + MINT_RECIPIENT_INDEX, 32));
p.amount = _u(message, b + AMOUNT_INDEX, 32);
p.messageSender = bytes32(_u(message, b + MSG_SENDER_INDEX, 32));
uint256 hookStart = b + HOOK_DATA_INDEX;
bytes memory hook = new bytes(message.length - hookStart);
for (uint256 i; i < hook.length; ++i) {
hook[i] = message[hookStart + i];
}
p.hookData = hook;
}
/// @notice Builds a message in Circle's layout. Used by tests and by tooling that wants to
/// preview what a burn will look like; production messages come from the attester.
function build(
uint32 sourceDomain,
uint32 destinationDomain,
bytes32 nonce,
bytes32 sender,
bytes32 recipient,
bytes32 destinationCaller,
uint32 minFinality,
uint32 finalityExecuted,
bytes32 burnToken,
bytes32 mintRecipient,
uint256 amount,
bytes32 messageSender,
bytes memory hookData
) internal pure returns (bytes memory) {
bytes memory body = abi.encodePacked(
uint32(1), burnToken, mintRecipient, amount, messageSender, uint256(0), uint256(0), uint256(0), hookData
);
return abi.encodePacked(
uint32(1),
sourceDomain,
destinationDomain,
nonce,
sender,
recipient,
destinationCaller,
minFinality,
finalityExecuted,
body
);
}
function toBytes32(address a) internal pure returns (bytes32) {
return bytes32(uint256(uint160(a)));
}
function toAddress(bytes32 b) internal pure returns (address) {
return address(uint160(uint256(b)));
}
function _u(bytes memory m, uint256 start, uint256 len) private pure returns (uint256 v) {
for (uint256 i; i < len; ++i) {
v = (v << 8) | uint8(m[start + i]);
}
}
}
/// @notice Circle's TokenMessengerV2, the entry point of a burn.
interface ITokenMessengerV2 {
function depositForBurnWithHook(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller,
uint256 maxFee,
uint32 minFinalityThreshold,
bytes calldata hookData
) external;
}
/// @notice Circle's MessageTransmitterV2, where an attested message is redeemed.
interface IMessageTransmitterV2 {
function receiveMessage(bytes calldata message, bytes calldata attestation) external returns (bool);
}
src/v2/libs/Messages.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title Messages — wire formats shared by the hub, the vault and the bridger
/// @notice Every cross-chain payload in ArcStocks v2 is one of these structs, abi-encoded with a
/// leading type byte. LayerZero carries Order and Result; the canonical lane carries Deliver
/// (Arc → Ethereum → Robinhood Chain as CCTP hook data, then retryable calldata) and
/// Checkpoint (Robinhood Chain → Ethereum → Arc as an outbox call, then CCTP hook data).
library Messages {
uint8 internal constant T_ORDER = 1;
uint8 internal constant T_RESULT = 2;
uint8 internal constant T_DELIVER = 3;
uint8 internal constant T_CHECKPOINT = 4;
enum Side {
Buy,
Sell
}
enum Outcome {
Bought,
Sold,
Failed
}
enum DeliverMode {
Stock,
Settlement
}
/// @dev Hub → vault. Buy: `amountIn` is settlement (6 dp), `minOut` is shares (18 dp).
/// Sell: `amountIn` is shares (18 dp), `minOut` is settlement (6 dp).
struct Order {
bytes32 ref;
address underlying;
Side side;
uint128 amountIn;
uint128 minOut;
}
/// @dev Vault → hub. Bought: `amountOut` shares. Sold: `amountOut` settlement (6 dp). Failed: 0.
struct Result {
bytes32 ref;
address underlying;
Outcome outcome;
uint128 amountIn;
uint128 amountOut;
uint64 seq;
}
/// @dev Canonical redemption: hand `shares` of `underlying` (or their sale proceeds) to `to` on the reserve chain.
struct Deliver {
bytes32 ref;
address underlying;
uint128 shares;
address to;
DeliverMode mode;
}
/// @dev Merkle root of vault results with sequence numbers `fromSeq..toSeq` (inclusive).
struct Checkpoint {
bytes32 root;
uint64 fromSeq;
uint64 toSeq;
}
error BadMessageType(uint8 got, uint8 want);
function encode(Order memory o) internal pure returns (bytes memory) {
return abi.encode(T_ORDER, o);
}
function encode(Result memory r) internal pure returns (bytes memory) {
return abi.encode(T_RESULT, r);
}
function encode(Deliver memory d) internal pure returns (bytes memory) {
return abi.encode(T_DELIVER, d);
}
function encode(Checkpoint memory c) internal pure returns (bytes memory) {
return abi.encode(T_CHECKPOINT, c);
}
function kind(bytes memory m) internal pure returns (uint8 t) {
(t) = abi.decode(m, (uint8));
}
function decodeOrder(bytes memory m) internal pure returns (Order memory o) {
uint8 t;
(t, o) = abi.decode(m, (uint8, Order));
if (t != T_ORDER) revert BadMessageType(t, T_ORDER);
}
function decodeResult(bytes memory m) internal pure returns (Result memory r) {
uint8 t;
(t, r) = abi.decode(m, (uint8, Result));
if (t != T_RESULT) revert BadMessageType(t, T_RESULT);
}
function decodeDeliver(bytes memory m) internal pure returns (Deliver memory d) {
uint8 t;
(t, d) = abi.decode(m, (uint8, Deliver));
if (t != T_DELIVER) revert BadMessageType(t, T_DELIVER);
}
function decodeCheckpoint(bytes memory m) internal pure returns (Checkpoint memory c) {
uint8 t;
(t, c) = abi.decode(m, (uint8, Checkpoint));
if (t != T_CHECKPOINT) revert BadMessageType(t, T_CHECKPOINT);
}
/// @dev Migration results carry no order: their ref has the top bit set (order refs are small ids),
/// then the underlying and a per-underlying nonce, so every batch has a distinct, decodable ref.
bytes32 internal constant MIGRATION_FLAG = bytes32(uint256(1) << 255);
function migrationRef(address underlying, uint64 nonce) internal pure returns (bytes32) {
return MIGRATION_FLAG | bytes32((uint256(uint160(underlying)) << 64) | uint256(nonce));
}
function isMigrationRef(bytes32 ref) internal pure returns (bool) {
return (ref & MIGRATION_FLAG) != 0;
}
function migrationUnderlying(bytes32 ref) internal pure returns (address) {
return address(uint160((uint256(ref) & ~uint256(MIGRATION_FLAG)) >> 64));
}
/// @notice Leaf of the reconciliation tree: one vault result. Double-hashed so a leaf can never be
/// confused with an internal node (OpenZeppelin MerkleProof convention).
function leaf(Result memory r) internal pure returns (bytes32) {
return keccak256(bytes.concat(keccak256(abi.encode(r))));
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 800,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@layerzerolabs/=node_modules/@layerzerolabs/",
":@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
":@pythnetwork/pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
":@uniswap/v4-core/=../../node_modules/@uniswap/v4-core/",
":@uniswap/v4-periphery/=../../node_modules/@uniswap/v4-periphery/",
":forge-std/=lib/forge-std/src/",
":solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
":solmate/=../../node_modules/@uniswap/v4-core/lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.