Contract Details
Overview
COOK BALANCE
Loading…TOKEN NAME
EVM ContractTOTAL SUPPLY
Not availableMore Info
CONTRACT ADDRESS
0x5c2e5dec72280f2ad5bb7f9befc0ef877aedf62dCONTRACT CREATOR
Not availableTOKEN TRACKER
Checking ERC-20 metadata…Contract Info
SOURCE CODE
✓ Verified
TOKEN DECIMALS
Not availableMarket and multichain values require verified data feeds.
Latest Contract Transactions
Loading indexed transactions…
| Transaction Hash | Action | Block | Age | From | To | Amount | Txn Fee |
|---|
Token Transfers
ERC-20 Transfer events from the latest indexed transactions involving this contract.
Loading receipt events…
Contract Events
Event logs emitted by this contract in the latest indexed contract transactions.
Loading receipt events…
Internal Transactions
Execution traces are not currently indexed. Internal calls cannot be reconstructed from receipts alone.
Token & Contract Information
- Network
- Cookchain · Chain ID 20261001
- Contract
- 0x5c2e5dec72280f2ad5bb7f9befc0ef877aedf62d
- Verification
- Verified
Token metadata is read from the contract. Market valuations and multichain holdings are not currently indexed.
Verified Solidity Source
Compiler: 0.8.30+commit.73712a01.Emscripten.clang · Contract: @hyperlane-xyz/core/contracts/token/HypERC20.sol:HypERC20 · Creation bytecode: matched
@hyperlane-xyz/core/contracts/Mailbox.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {Versioned} from "./upgrade/Versioned.sol";
import {Indexed} from "./libs/Indexed.sol";
import {Message} from "./libs/Message.sol";
import {TypeCasts} from "./libs/TypeCasts.sol";
import {IInterchainSecurityModule, ISpecifiesInterchainSecurityModule} from "./interfaces/IInterchainSecurityModule.sol";
import {IPostDispatchHook} from "./interfaces/hooks/IPostDispatchHook.sol";
import {IMessageRecipient} from "./interfaces/IMessageRecipient.sol";
import {IMailbox} from "./interfaces/IMailbox.sol";
import {PackageVersioned} from "./PackageVersioned.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract Mailbox is
IMailbox,
Indexed,
Versioned,
OwnableUpgradeable,
PackageVersioned
{
// ============ Libraries ============
using Message for bytes;
using TypeCasts for bytes32;
using TypeCasts for address;
// ============ Constants ============
// Domain of chain on which the contract is deployed
uint32 public immutable localDomain;
// ============ Public Storage ============
// A monotonically increasing nonce for outbound unique message IDs.
uint32 public nonce;
// The latest dispatched message ID used for auth in post-dispatch hooks.
bytes32 public latestDispatchedId;
// The default ISM, used if the recipient fails to specify one.
IInterchainSecurityModule public defaultIsm;
// The default post dispatch hook, used for post processing of opting-in dispatches.
IPostDispatchHook public defaultHook;
// The required post dispatch hook, used for post processing of ALL dispatches.
IPostDispatchHook public requiredHook;
// Mapping of message ID to delivery context that processed the message.
struct Delivery {
address processor;
uint48 blockNumber;
}
mapping(bytes32 messageId => Delivery delivery) internal deliveries;
// ============ Events ============
/**
* @notice Emitted when the default ISM is updated
* @param module The new default ISM
*/
event DefaultIsmSet(address indexed module);
/**
* @notice Emitted when the default hook is updated
* @param hook The new default hook
*/
event DefaultHookSet(address indexed hook);
/**
* @notice Emitted when the required hook is updated
* @param hook The new required hook
*/
event RequiredHookSet(address indexed hook);
// ============ Constructor ============
constructor(uint32 _localDomain) {
localDomain = _localDomain;
}
// ============ Initializers ============
function initialize(
address _owner,
address _defaultIsm,
address _defaultHook,
address _requiredHook
) external initializer {
__Ownable_init();
setDefaultIsm(_defaultIsm);
setDefaultHook(_defaultHook);
setRequiredHook(_requiredHook);
transferOwnership(_owner);
}
// ============ External Functions ============
/**
* @notice Dispatches a message to the destination domain & recipient
* using the default hook and empty metadata.
* @param _destinationDomain Domain of destination chain
* @param _recipientAddress Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes content of message body
* @return The message ID inserted into the Mailbox's merkle tree
*/
function dispatch(
uint32 _destinationDomain,
bytes32 _recipientAddress,
bytes calldata _messageBody
) external payable override returns (bytes32) {
return
dispatch(
_destinationDomain,
_recipientAddress,
_messageBody,
_messageBody[0:0],
defaultHook
);
}
/**
* @notice Dispatches a message to the destination domain & recipient.
* @param destinationDomain Domain of destination chain
* @param recipientAddress Address of recipient on destination chain as bytes32
* @param messageBody Raw bytes content of message body
* @param hookMetadata Metadata used by the post dispatch hook
* @return The message ID inserted into the Mailbox's merkle tree
*/
function dispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata hookMetadata
) external payable override returns (bytes32) {
return
dispatch(
destinationDomain,
recipientAddress,
messageBody,
hookMetadata,
defaultHook
);
}
/**
* @notice Computes quote for dipatching a message to the destination domain & recipient
* using the default hook and empty metadata.
* @param destinationDomain Domain of destination chain
* @param recipientAddress Address of recipient on destination chain as bytes32
* @param messageBody Raw bytes content of message body
* @return fee The payment required to dispatch the message
*/
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody
) external view returns (uint256 fee) {
return
quoteDispatch(
destinationDomain,
recipientAddress,
messageBody,
messageBody[0:0],
defaultHook
);
}
/**
* @notice Computes quote for dispatching a message to the destination domain & recipient.
* @param destinationDomain Domain of destination chain
* @param recipientAddress Address of recipient on destination chain as bytes32
* @param messageBody Raw bytes content of message body
* @param defaultHookMetadata Metadata used by the default post dispatch hook
* @return fee The payment required to dispatch the message
*/
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata defaultHookMetadata
) external view returns (uint256 fee) {
return
quoteDispatch(
destinationDomain,
recipientAddress,
messageBody,
defaultHookMetadata,
defaultHook
);
}
/**
* @notice Attempts to deliver `_message` to its recipient. Verifies
* `_message` via the recipient's ISM using the provided `_metadata`.
* @param _metadata Metadata used by the ISM to verify `_message`.
* @param _message Formatted Hyperlane message (refer to Message.sol).
*/
function process(
bytes calldata _metadata,
bytes calldata _message
) external payable override {
/// CHECKS ///
// Check that the message was intended for this mailbox.
require(_message.version() == VERSION, "Mailbox: bad version");
require(
_message.destination() == localDomain,
"Mailbox: unexpected destination"
);
// Check that the message hasn't already been delivered.
bytes32 _id = _message.id();
require(delivered(_id) == false, "Mailbox: already delivered");
// Get the recipient's ISM.
address recipient = _message.recipientAddress();
IInterchainSecurityModule ism = recipientIsm(recipient);
/// EFFECTS ///
deliveries[_id] = Delivery({
processor: msg.sender,
blockNumber: uint48(block.number)
});
emit Process(_message.origin(), _message.sender(), recipient);
emit ProcessId(_id);
/// INTERACTIONS ///
// Verify the message via the interchain security module.
require(
ism.verify(_metadata, _message),
"Mailbox: ISM verification failed"
);
// Deliver the message to the recipient.
IMessageRecipient(recipient).handle{value: msg.value}(
_message.origin(),
_message.sender(),
_message.body()
);
}
/**
* @notice Returns the account that processed the message.
* @param _id The message ID to check.
* @return The account that processed the message.
*/
function processor(bytes32 _id) external view returns (address) {
return deliveries[_id].processor;
}
/**
* @notice Returns the account that processed the message.
* @param _id The message ID to check.
* @return The number of the block that the message was processed at.
*/
function processedAt(bytes32 _id) external view returns (uint48) {
return deliveries[_id].blockNumber;
}
// ============ Public Functions ============
/**
* @notice Dispatches a message to the destination domain & recipient.
* @param destinationDomain Domain of destination chain
* @param recipientAddress Address of recipient on destination chain as bytes32
* @param messageBody Raw bytes content of message body
* @param metadata Metadata used by the post dispatch hook
* @param hook Custom hook to use instead of the default
* @return The message ID inserted into the Mailbox's merkle tree
*/
function dispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata metadata,
IPostDispatchHook hook
) public payable virtual returns (bytes32) {
if (address(hook) == address(0)) {
hook = defaultHook;
}
/// CHECKS ///
// Format the message into packed bytes.
bytes memory message = _buildMessage(
destinationDomain,
recipientAddress,
messageBody
);
bytes32 id = message.id();
/// EFFECTS ///
latestDispatchedId = id;
nonce += 1;
emit Dispatch(msg.sender, destinationDomain, recipientAddress, message);
emit DispatchId(id);
/// INTERACTIONS ///
uint256 requiredValue = requiredHook.quoteDispatch(metadata, message);
// if underpaying, defer to required hook's reverting behavior
if (msg.value < requiredValue) {
requiredValue = msg.value;
}
requiredHook.postDispatch{value: requiredValue}(metadata, message);
hook.postDispatch{value: msg.value - requiredValue}(metadata, message);
return id;
}
/**
* @notice Computes quote for dispatching a message to the destination domain & recipient.
* @dev This function sums the quotes from requiredHook and hook, assuming both return
* values denominated in the same currency. When using ERC-20 fee tokens (via
* StandardHookMetadata.feeToken), this works because:
* - Native-only hooks reject non-zero feeToken metadata via supportsMetadata
* - The requiredHook (typically ProtocolFee) returns 0 when protocolFee is 0
*
* IMPORTANT: Mixing fee denominations (native + ERC-20) in a single dispatch is not
* supported. Callers must ensure all hooks in the chain use the same fee denomination.
*
* @param destinationDomain Domain of destination chain
* @param recipientAddress Address of recipient on destination chain as bytes32
* @param messageBody Raw bytes content of message body
* @param metadata Metadata used by the post dispatch hook
* @param hook Custom hook to use instead of the default
* @return fee The payment required to dispatch the message
*/
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata metadata,
IPostDispatchHook hook
) public view returns (uint256 fee) {
if (address(hook) == address(0)) {
hook = defaultHook;
}
bytes memory message = _buildMessage(
destinationDomain,
recipientAddress,
messageBody
);
return
requiredHook.quoteDispatch(metadata, message) +
hook.quoteDispatch(metadata, message);
}
/**
* @notice Returns true if the message has been processed.
* @param _id The message ID to check.
* @return True if the message has been delivered.
*/
function delivered(bytes32 _id) public view override returns (bool) {
return deliveries[_id].blockNumber > 0;
}
/**
* @notice Sets the default ISM for the Mailbox.
* @param _module The new default ISM. Must be a contract.
*/
function setDefaultIsm(address _module) public onlyOwner {
require(
Address.isContract(_module),
"Mailbox: default ISM not contract"
);
defaultIsm = IInterchainSecurityModule(_module);
emit DefaultIsmSet(_module);
}
/**
* @notice Sets the default post dispatch hook for the Mailbox.
* @param _hook The new default post dispatch hook. Must be a contract.
*/
function setDefaultHook(address _hook) public onlyOwner {
require(
Address.isContract(_hook),
"Mailbox: default hook not contract"
);
defaultHook = IPostDispatchHook(_hook);
emit DefaultHookSet(_hook);
}
/**
* @notice Sets the required post dispatch hook for the Mailbox.
* @param _hook The new default post dispatch hook. Must be a contract.
*/
function setRequiredHook(address _hook) public onlyOwner {
require(
Address.isContract(_hook),
"Mailbox: required hook not contract"
);
requiredHook = IPostDispatchHook(_hook);
emit RequiredHookSet(_hook);
}
/**
* @notice Returns the ISM to use for the recipient, defaulting to the
* default ISM if none is specified.
* @param _recipient The message recipient whose ISM should be returned.
* @return The ISM to use for `_recipient`.
*/
function recipientIsm(
address _recipient
) public view returns (IInterchainSecurityModule) {
// use low-level staticcall in case of revert or empty return data
(bool success, bytes memory returnData) = _recipient.staticcall(
abi.encodeCall(
ISpecifiesInterchainSecurityModule.interchainSecurityModule,
()
)
);
// check if call was successful and returned data
if (success && returnData.length != 0) {
// check if returnData is a valid address
address ism = abi.decode(returnData, (address));
// check if the ISM is a contract
if (ism != address(0)) {
return IInterchainSecurityModule(ism);
}
}
// Use the default if a valid one is not specified by the recipient.
return defaultIsm;
}
// ============ Internal Functions ============
function _buildMessage(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody
) internal view returns (bytes memory) {
return
Message.formatMessage(
VERSION,
nonce,
localDomain,
msg.sender.addressToBytes32(),
destinationDomain,
recipientAddress,
messageBody
);
}
}
@hyperlane-xyz/core/contracts/hooks/MerkleTreeHook.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {MailboxClient} from "../client/MailboxClient.sol";
import {Indexed} from "../libs/Indexed.sol";
import {IPostDispatchHook} from "../interfaces/hooks/IPostDispatchHook.sol";
import {AbstractPostDispatchHook} from "./libs/AbstractPostDispatchHook.sol";
import {StandardHookMetadata} from "./libs/StandardHookMetadata.sol";
contract MerkleTreeHook is AbstractPostDispatchHook, MailboxClient, Indexed {
using Message for bytes;
using MerkleLib for MerkleLib.Tree;
using StandardHookMetadata for bytes;
// An incremental merkle tree used to store outbound message IDs.
MerkleLib.Tree internal _tree;
event InsertedIntoTree(bytes32 messageId, uint32 index);
constructor(address _mailbox) MailboxClient(_mailbox) {}
// count cannot exceed 2**TREE_DEPTH, see MerkleLib.sol
function count() public view returns (uint32) {
return uint32(_tree.count);
}
function root() public view returns (bytes32) {
return _tree.root();
}
function tree() public view returns (MerkleLib.Tree memory) {
return _tree;
}
function latestCheckpoint() external view returns (bytes32, uint32) {
return (root(), count() - 1);
}
// ============ External Functions ============
/// @inheritdoc IPostDispatchHook
function hookType() external pure override returns (uint8) {
return uint8(IPostDispatchHook.HookTypes.MERKLE_TREE);
}
// ============ Internal Functions ============
/// @inheritdoc AbstractPostDispatchHook
function _postDispatch(
bytes calldata,
/*metadata*/
bytes calldata message
) internal override {
require(msg.value == 0, "MerkleTreeHook: no value expected");
// ensure messages which were not dispatched are not inserted into the tree
bytes32 id = message.id();
require(_isLatestDispatched(id), "message not dispatching");
uint32 index = count();
_tree.insert(id);
emit InsertedIntoTree(id, index);
}
/// @inheritdoc AbstractPostDispatchHook
function _quoteDispatch(
bytes calldata,
/*metadata*/
bytes calldata /*message*/
) internal pure override returns (uint256) {
return 0;
}
}
@hyperlane-xyz/core/contracts/hooks/ProtocolFee.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
// ============ Internal Imports ============
import {Message} from "../libs/Message.sol";
import {StandardHookMetadata} from "./libs/StandardHookMetadata.sol";
import {AbstractPostDispatchHook} from "./libs/AbstractPostDispatchHook.sol";
import {IPostDispatchHook} from "../interfaces/hooks/IPostDispatchHook.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title ProtocolFee
* @notice Collects a static protocol fee from the sender.
*/
contract ProtocolFee is AbstractPostDispatchHook, Ownable {
using StandardHookMetadata for bytes;
using Address for address payable;
using Message for bytes;
event ProtocolFeeSet(uint256 protocolFee);
event BeneficiarySet(address beneficiary);
event ProtocolFeePaid(address indexed sender, uint256 fee);
// ============ Constants ============
/// @notice The maximum protocol fee that can be set.
uint256 public immutable MAX_PROTOCOL_FEE;
// ============ Public Storage ============
/// @notice The current protocol fee.
uint256 public protocolFee;
/// @notice The beneficiary of protocol fees.
address public beneficiary;
// ============ Constructor ============
constructor(
uint256 _maxProtocolFee,
uint256 _protocolFee,
address _beneficiary,
address _owner
) {
MAX_PROTOCOL_FEE = _maxProtocolFee;
_setProtocolFee(_protocolFee);
_setBeneficiary(_beneficiary);
_transferOwnership(_owner);
}
// ============ External Functions ============
/// @inheritdoc AbstractPostDispatchHook
/// @dev Rejects metadata with a non-zero ERC20 fee token when the protocol fee
/// is non-zero, since this hook only accepts native token payment via msg.value.
/// When protocolFee is 0, fee token metadata is accepted because the hook contributes
/// nothing to the Mailbox.quoteDispatch sum, avoiding denomination mixing.
function supportsMetadata(
bytes calldata metadata
) public view override returns (bool) {
if (protocolFee > 0 && metadata.feeToken(address(0)) != address(0)) {
return false;
}
return super.supportsMetadata(metadata);
}
/// @inheritdoc IPostDispatchHook
function hookType() external pure override returns (uint8) {
return uint8(IPostDispatchHook.HookTypes.PROTOCOL_FEE);
}
/**
* @notice Sets the protocol fee.
* @param _protocolFee The new protocol fee.
*/
function setProtocolFee(uint256 _protocolFee) external onlyOwner {
_setProtocolFee(_protocolFee);
}
/**
* @notice Sets the beneficiary of protocol fees.
* @param _beneficiary The new beneficiary.
*/
function setBeneficiary(address _beneficiary) external onlyOwner {
_setBeneficiary(_beneficiary);
}
/**
* @notice Collects protocol fees from the contract.
*/
function collectProtocolFees() external {
payable(beneficiary).sendValue(address(this).balance);
}
// ============ Internal Functions ============
/// @inheritdoc AbstractPostDispatchHook
function _postDispatch(
bytes calldata metadata,
bytes calldata message
) internal override {
require(
msg.value >= protocolFee,
"ProtocolFee: insufficient protocol fee"
);
emit ProtocolFeePaid(message.senderAddress(), protocolFee);
_refund(metadata, message, msg.value - protocolFee);
}
/// @inheritdoc AbstractPostDispatchHook
function _quoteDispatch(
bytes calldata,
bytes calldata
) internal view override returns (uint256) {
return protocolFee;
}
/**
* @notice Sets the protocol fee.
* @param _protocolFee The new protocol fee.
*/
function _setProtocolFee(uint256 _protocolFee) internal {
require(
_protocolFee <= MAX_PROTOCOL_FEE,
"ProtocolFee: exceeds max protocol fee"
);
protocolFee = _protocolFee;
emit ProtocolFeeSet(_protocolFee);
}
/**
* @notice Sets the beneficiary of protocol fees.
* @param _beneficiary The new beneficiary.
*/
function _setBeneficiary(address _beneficiary) internal {
require(_beneficiary != address(0), "ProtocolFee: invalid beneficiary");
beneficiary = _beneficiary;
emit BeneficiarySet(_beneficiary);
}
}
@hyperlane-xyz/core/contracts/isms/PausableIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ External Imports ============
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
// ============ Internal Imports ============
import {IInterchainSecurityModule} from "../interfaces/IInterchainSecurityModule.sol";
import {PackageVersioned} from "../PackageVersioned.sol";
contract PausableIsm is
IInterchainSecurityModule,
Ownable,
Pausable,
PackageVersioned
{
uint8 public constant override moduleType = uint8(Types.NULL);
constructor(address owner) Ownable() Pausable() {
_transferOwnership(owner);
}
/**
* @inheritdoc IInterchainSecurityModule
* @dev Reverts when paused, otherwise returns `true`.
*/
function verify(
bytes calldata,
bytes calldata
) external view whenNotPaused returns (bool) {
return true;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
@hyperlane-xyz/core/contracts/isms/multisig/StaticMultisigIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {IInterchainSecurityModule} from "../../interfaces/IInterchainSecurityModule.sol";
import {AbstractMultisigIsm} from "./AbstractMultisigIsm.sol";
import {AbstractMerkleRootMultisigIsm} from "./AbstractMerkleRootMultisigIsm.sol";
import {AbstractMessageIdMultisigIsm} from "./AbstractMessageIdMultisigIsm.sol";
import {MetaProxy} from "../../libs/MetaProxy.sol";
import {StaticThresholdAddressSetFactory} from "../../libs/StaticAddressSetFactory.sol";
/**
* @title AbstractMetaProxyMultisigIsm
* @notice Manages per-domain m-of-n Validator set that is used
* to verify interchain messages.
*/
abstract contract AbstractMetaProxyMultisigIsm is AbstractMultisigIsm {
/**
* @inheritdoc AbstractMultisigIsm
*/
function validatorsAndThreshold(
bytes calldata
) public pure override returns (address[] memory, uint8) {
return abi.decode(MetaProxy.metadata(), (address[], uint8));
}
}
// solhint-disable no-empty-blocks
/**
* @title StaticMerkleRootMultisigIsm
* @notice Manages per-domain m-of-n validator set that is used
* to verify interchain messages using a merkle root signature quorum
* and merkle proof of inclusion.
*/
contract StaticMerkleRootMultisigIsm is
AbstractMerkleRootMultisigIsm,
AbstractMetaProxyMultisigIsm
{
uint8 public constant moduleType =
uint8(IInterchainSecurityModule.Types.MERKLE_ROOT_MULTISIG);
}
/**
* @title StaticMessageIdMultisigIsm
* @notice Manages per-domain m-of-n validator set that is used
* to verify interchain messages using a message ID signature quorum.
*/
contract StaticMessageIdMultisigIsm is
AbstractMessageIdMultisigIsm,
AbstractMetaProxyMultisigIsm
{
uint8 public constant moduleType =
uint8(IInterchainSecurityModule.Types.MESSAGE_ID_MULTISIG);
}
// solhint-enable no-empty-blocks
contract StaticMerkleRootMultisigIsmFactory is
StaticThresholdAddressSetFactory
{
function _deployImplementation() internal override returns (address) {
return address(new StaticMerkleRootMultisigIsm());
}
}
contract StaticMessageIdMultisigIsmFactory is StaticThresholdAddressSetFactory {
function _deployImplementation() internal override returns (address) {
return address(new StaticMessageIdMultisigIsm());
}
}
@hyperlane-xyz/core/contracts/isms/aggregation/StaticAggregationIsmFactory.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {StaticAggregationIsm} from "./StaticAggregationIsm.sol";
import {StaticThresholdAddressSetFactory} from "../../libs/StaticAddressSetFactory.sol";
contract StaticAggregationIsmFactory is StaticThresholdAddressSetFactory {
function _deployImplementation() internal override returns (address) {
return address(new StaticAggregationIsm());
}
}
@hyperlane-xyz/core/contracts/token/HypERC20Collateral.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
// ============ Internal Imports ============
import {TokenMessage} from "./libs/TokenMessage.sol";
import {TokenRouter} from "./libs/TokenRouter.sol";
import {MovableCollateralRouter} from "./libs/MovableCollateralRouter.sol";
import {LpCollateralRouter} from "./libs/LpCollateralRouter.sol";
import {ITokenBridge, Quote} from "../interfaces/ITokenBridge.sol";
import {ERC20Collateral} from "./libs/TokenCollateral.sol";
import {EnumerableMapExtended} from "../libs/EnumerableMapExtended.sol";
// ============ External Imports ============
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @title Hyperlane ERC20 Token Collateral that wraps an existing ERC20 with remote transfer functionality.
* @author Abacus Works
*/
contract HypERC20Collateral is LpCollateralRouter {
using SafeERC20 for IERC20;
using ERC20Collateral for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;
IERC20 public immutable wrappedToken;
/**
* @notice Constructor
* @param erc20 Address of the token to keep as collateral
*/
constructor(
address erc20,
uint256 _scaleNumerator,
uint256 _scaleDenominator,
address _mailbox
) TokenRouter(_scaleNumerator, _scaleDenominator, _mailbox) {
require(Address.isContract(erc20), "HypERC20Collateral: invalid token");
wrappedToken = IERC20(erc20);
}
function initialize(
address _hook,
address _interchainSecurityModule,
address _owner
) public initializer {
_MailboxClient_initialize(_hook, _interchainSecurityModule, _owner);
_LpCollateralRouter_initialize();
}
function token() public view override returns (address) {
return address(wrappedToken);
}
function _removeBridge(
uint32 domain,
ITokenBridge bridge
) internal override {
MovableCollateralRouter._removeBridge(domain, bridge);
uint32[] memory knownDomains = _routers.uint32Keys();
// Iteration is fine as number of enrolled domains is bounded
for (uint256 i = 0; i < knownDomains.length; i++) {
EnumerableSet.AddressSet storage bridges = allowed.bridges[
knownDomains[i]
];
if (bridges.contains(address(bridge))) {
return;
}
}
wrappedToken.forceApprove(address(bridge), 0);
}
/**
* @dev Transfers `_amount` of `wrappedToken` from `msg.sender` to this contract.
* @inheritdoc TokenRouter
*/
function _transferFromSender(uint256 _amount) internal override {
wrappedToken._transferFromSender(_amount);
}
/**
* @dev Transfers `_amount` of `wrappedToken` from this contract to `_recipient`.
* @inheritdoc TokenRouter
*/
function _transferTo(
address _recipient,
uint256 _amount
) internal override {
wrappedToken._transferTo(_recipient, _amount);
}
}
@hyperlane-xyz/core/contracts/token/HypERC20.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;
import {TokenRouter} from "./libs/TokenRouter.sol";
import {Quote} from "../interfaces/ITokenBridge.sol";
import {TokenRouter} from "./libs/TokenRouter.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
/**
* @title Hyperlane ERC20 Token Router that extends ERC20 with remote transfer functionality.
* @author Abacus Works
* @dev Supply on each chain is not constant but the aggregate supply across all chains is.
*/
contract HypERC20 is ERC20Upgradeable, TokenRouter {
uint8 private immutable _decimals;
constructor(
uint8 __decimals,
uint256 _scaleNumerator,
uint256 _scaleDenominator,
address _mailbox
) TokenRouter(_scaleNumerator, _scaleDenominator, _mailbox) {
_decimals = __decimals;
}
/**
* @notice Initializes the Hyperlane router, ERC20 metadata, and mints initial supply to deployer.
* @param _totalSupply The initial supply of the token.
* @param _name The name of the token.
* @param _symbol The symbol of the token.
*/
function initialize(
uint256 _totalSupply,
string memory _name,
string memory _symbol,
address _hook,
address _interchainSecurityModule,
address _owner
) public initializer {
// Initialize ERC20 metadata
__ERC20_init(_name, _symbol);
_mint(msg.sender, _totalSupply);
_MailboxClient_initialize(_hook, _interchainSecurityModule, _owner);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
// ============ TokenRouter overrides ============
/**
* @inheritdoc TokenRouter
*/
function token() public view override returns (address) {
return address(this);
}
/**
* @inheritdoc TokenRouter
* @dev Overrides to burn `_amount` of token from `msg.sender` balance.
* @dev Known overrides:
* - HypERC4626: Converts the amount to shares and burns from the User (via HypERC20 implementation)
*/
// solhint-disable-next-line hyperlane/no-virtual-override
function _transferFromSender(uint256 _amount) internal virtual override {
_burn(msg.sender, _amount);
}
/**
* @inheritdoc TokenRouter
* @dev Overrides to mint `_amount` of token to `_recipient` balance.
*/
function _transferTo(
address _recipient,
uint256 _amount
) internal override {
_mint(_recipient, _amount);
}
}
@hyperlane-xyz/core/contracts/upgrade/Versioned.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title Versioned
* @notice Version getter for contracts
**/
contract Versioned {
uint8 public constant VERSION = 3;
}
@hyperlane-xyz/core/contracts/libs/Indexed.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
contract Indexed {
uint256 public immutable deployedBlock;
constructor() {
deployedBlock = block.number;
}
}
@hyperlane-xyz/core/contracts/libs/Message.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
import {TypeCasts} from "./TypeCasts.sol";
/**
* @title Hyperlane Message Library
* @notice Library for formatted messages used by Mailbox
**/
library Message {
using TypeCasts for bytes32;
uint256 private constant VERSION_OFFSET = 0;
uint256 private constant NONCE_OFFSET = 1;
uint256 private constant ORIGIN_OFFSET = 5;
uint256 private constant SENDER_OFFSET = 9;
uint256 private constant DESTINATION_OFFSET = 41;
uint256 private constant RECIPIENT_OFFSET = 45;
uint256 private constant BODY_OFFSET = 77;
/**
* @notice Returns formatted (packed) Hyperlane message with provided fields
* @dev This function should only be used in memory message construction.
* @param _version The version of the origin and destination Mailboxes
* @param _nonce A nonce to uniquely identify the message on its origin chain
* @param _originDomain Domain of origin chain
* @param _sender Address of sender as bytes32
* @param _destinationDomain Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes of message body
* @return Formatted message
*/
function formatMessage(
uint8 _version,
uint32 _nonce,
uint32 _originDomain,
bytes32 _sender,
uint32 _destinationDomain,
bytes32 _recipient,
bytes calldata _messageBody
) internal pure returns (bytes memory) {
return
abi.encodePacked(
_version,
_nonce,
_originDomain,
_sender,
_destinationDomain,
_recipient,
_messageBody
);
}
/**
* @notice Returns the message ID.
* @param _message ABI encoded Hyperlane message.
* @return ID of `_message`
*/
function id(bytes memory _message) internal pure returns (bytes32) {
return keccak256(_message);
}
/**
* @notice Returns the message version.
* @param _message ABI encoded Hyperlane message.
* @return Version of `_message`
*/
function version(bytes calldata _message) internal pure returns (uint8) {
return uint8(bytes1(_message[VERSION_OFFSET:NONCE_OFFSET]));
}
/**
* @notice Returns the message nonce.
* @param _message ABI encoded Hyperlane message.
* @return Nonce of `_message`
*/
function nonce(bytes calldata _message) internal pure returns (uint32) {
return uint32(bytes4(_message[NONCE_OFFSET:ORIGIN_OFFSET]));
}
/**
* @notice Returns the message origin domain.
* @param _message ABI encoded Hyperlane message.
* @return Origin domain of `_message`
*/
function origin(bytes calldata _message) internal pure returns (uint32) {
return uint32(bytes4(_message[ORIGIN_OFFSET:SENDER_OFFSET]));
}
/**
* @notice Returns the message sender as bytes32.
* @param _message ABI encoded Hyperlane message.
* @return Sender of `_message` as bytes32
*/
function sender(bytes calldata _message) internal pure returns (bytes32) {
return bytes32(_message[SENDER_OFFSET:DESTINATION_OFFSET]);
}
/**
* @notice Returns the message sender as address.
* @param _message ABI encoded Hyperlane message.
* @return Sender of `_message` as address
*/
function senderAddress(
bytes calldata _message
) internal pure returns (address) {
return sender(_message).bytes32ToAddress();
}
/**
* @notice Returns the message destination domain.
* @param _message ABI encoded Hyperlane message.
* @return Destination domain of `_message`
*/
function destination(
bytes calldata _message
) internal pure returns (uint32) {
return uint32(bytes4(_message[DESTINATION_OFFSET:RECIPIENT_OFFSET]));
}
/**
* @notice Returns the message recipient as bytes32.
* @param _message ABI encoded Hyperlane message.
* @return Recipient of `_message` as bytes32
*/
function recipient(
bytes calldata _message
) internal pure returns (bytes32) {
return bytes32(_message[RECIPIENT_OFFSET:BODY_OFFSET]);
}
/**
* @notice Returns the message recipient as address.
* @param _message ABI encoded Hyperlane message.
* @return Recipient of `_message` as address
*/
function recipientAddress(
bytes calldata _message
) internal pure returns (address) {
return recipient(_message).bytes32ToAddress();
}
/**
* @notice Returns the message body.
* @param _message ABI encoded Hyperlane message.
* @return Body of `_message`
*/
function body(
bytes calldata _message
) internal pure returns (bytes calldata) {
return bytes(_message[BODY_OFFSET:]);
}
}
@hyperlane-xyz/core/contracts/libs/TypeCasts.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
library TypeCasts {
// alignment preserving cast
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
// alignment preserving cast
function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {
require(
uint256(_buf) <= uint256(type(uint160).max),
"TypeCasts: bytes32ToAddress overflow"
);
return address(uint160(uint256(_buf)));
}
}
@hyperlane-xyz/core/contracts/interfaces/IInterchainSecurityModule.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IInterchainSecurityModule {
enum Types {
UNUSED,
ROUTING,
AGGREGATION,
LEGACY_MULTISIG,
MERKLE_ROOT_MULTISIG,
MESSAGE_ID_MULTISIG,
NULL, // used with relayer carrying no metadata
CCIP_READ,
ARB_L2_TO_L1,
WEIGHTED_MERKLE_ROOT_MULTISIG,
WEIGHTED_MESSAGE_ID_MULTISIG,
OP_L2_TO_L1,
POLYMER
}
/**
* @notice Returns an enum that represents the type of security model
* encoded by this ISM.
* @dev Relayers infer how to fetch and format metadata.
*/
function moduleType() external view returns (uint8);
/**
* @notice Defines a security model responsible for verifying interchain
* messages based on the provided metadata.
* @param _metadata Off-chain metadata provided by a relayer, specific to
* the security model encoded by the module (e.g. validator signatures)
* @param _message Hyperlane encoded interchain message
* @return True if the message was verified
*/
function verify(
bytes calldata _metadata,
bytes calldata _message
) external returns (bool);
}
interface ISpecifiesInterchainSecurityModule {
function interchainSecurityModule()
external
view
returns (IInterchainSecurityModule);
}
@hyperlane-xyz/core/contracts/interfaces/hooks/IPostDispatchHook.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
interface IPostDispatchHook {
enum HookTypes {
UNUSED,
ROUTING,
AGGREGATION,
MERKLE_TREE,
INTERCHAIN_GAS_PAYMASTER,
FALLBACK_ROUTING,
ID_AUTH_ISM,
PAUSABLE,
PROTOCOL_FEE,
DEPRECATED,
RATE_LIMITED,
ARB_L2_TO_L1,
OP_L2_TO_L1,
MAILBOX_DEFAULT_HOOK,
AMOUNT_ROUTING,
CCTP,
TIMELOCK_ROUTING,
PREDICATE_ROUTER_WRAPPER
}
/**
* @notice Returns an enum that represents the type of hook
*/
function hookType() external view returns (uint8);
/**
* @notice Returns whether the hook supports metadata
* @param metadata metadata
* @return Whether the hook supports metadata
*/
function supportsMetadata(
bytes calldata metadata
) external view returns (bool);
/**
* @notice Post action after a message is dispatched via the Mailbox
* @param metadata The metadata required for the hook
* @param message The message passed from the Mailbox.dispatch() call
*/
function postDispatch(
bytes calldata metadata,
bytes calldata message
) external payable;
/**
* @notice Compute the payment required by the postDispatch call
* @dev The returned quote is denominated in a single currency - either native ETH
* (when metadata.feeToken is address(0) or unspecified) or an ERC-20 token
* (when metadata.feeToken is set). Mixing fee denominations within a single
* dispatch is not supported.
*
* When feeToken is set, hooks that only support native fees should return 0 or
* revert via supportsMetadata. The Mailbox.quoteDispatch sums quotes from
* requiredHook and hook, which assumes both use the same denomination.
*
* @param metadata The metadata required for the hook
* @param message The message passed from the Mailbox.dispatch() call
* @return Quoted payment for the postDispatch call
*/
function quoteDispatch(
bytes calldata metadata,
bytes calldata message
) external view returns (uint256);
}
@hyperlane-xyz/core/contracts/interfaces/IMessageRecipient.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IMessageRecipient {
function handle(
uint32 _origin,
bytes32 _sender,
bytes calldata _message
) external payable;
}
@hyperlane-xyz/core/contracts/interfaces/IMailbox.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
import {IInterchainSecurityModule} from "./IInterchainSecurityModule.sol";
import {IPostDispatchHook} from "./hooks/IPostDispatchHook.sol";
interface IMailbox {
// ============ Events ============
/**
* @notice Emitted when a new message is dispatched via Hyperlane
* @param sender The address that dispatched the message
* @param destination The destination domain of the message
* @param recipient The message recipient address on `destination`
* @param message Raw bytes of message
*/
event Dispatch(
address indexed sender,
uint32 indexed destination,
bytes32 indexed recipient,
bytes message
);
/**
* @notice Emitted when a new message is dispatched via Hyperlane
* @param messageId The unique message identifier
*/
event DispatchId(bytes32 indexed messageId);
/**
* @notice Emitted when a Hyperlane message is processed
* @param messageId The unique message identifier
*/
event ProcessId(bytes32 indexed messageId);
/**
* @notice Emitted when a Hyperlane message is delivered
* @param origin The origin domain of the message
* @param sender The message sender address on `origin`
* @param recipient The address that handled the message
*/
event Process(
uint32 indexed origin,
bytes32 indexed sender,
address indexed recipient
);
function localDomain() external view returns (uint32);
function delivered(bytes32 messageId) external view returns (bool);
/// @notice Returns the block number at which `messageId` was processed,
/// or 0 if it has not been processed.
/// @dev Implementation in `Mailbox.sol::processedAt`. The block number is
/// written to `deliveries[id].blockNumber` inside `process(...)` *before*
/// the ISM verify call, so within a single `process(...)` transaction,
/// `processedAt(id) == block.number` is true while the ISM is running.
function processedAt(bytes32 messageId) external view returns (uint48);
function defaultIsm() external view returns (IInterchainSecurityModule);
function defaultHook() external view returns (IPostDispatchHook);
function requiredHook() external view returns (IPostDispatchHook);
function latestDispatchedId() external view returns (bytes32);
function nonce() external view returns (uint32);
function dispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody
) external payable returns (bytes32 messageId);
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody
) external view returns (uint256 fee);
function dispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata body,
bytes calldata defaultHookMetadata
) external payable returns (bytes32 messageId);
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata defaultHookMetadata
) external view returns (uint256 fee);
function dispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata body,
bytes calldata customHookMetadata,
IPostDispatchHook customHook
) external payable returns (bytes32 messageId);
function quoteDispatch(
uint32 destinationDomain,
bytes32 recipientAddress,
bytes calldata messageBody,
bytes calldata customHookMetadata,
IPostDispatchHook customHook
) external view returns (uint256 fee);
function process(
bytes calldata metadata,
bytes calldata message
) external payable;
function recipientIsm(
address recipient
) external view returns (IInterchainSecurityModule module);
}
@hyperlane-xyz/core/contracts/PackageVersioned.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title PackageVersioned
* @notice Package version getter for contracts
**/
abstract contract PackageVersioned {
// GENERATED CODE - DO NOT EDIT
string public constant PACKAGE_VERSION = "12.1.0";
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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.
*
* By default, the owner account will be the one that deploys the contract. 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@hyperlane-xyz/core/contracts/libs/Merkle.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// work based on eth2 deposit contract, which is used under CC0-1.0
uint256 constant TREE_DEPTH = 32;
uint256 constant MAX_LEAVES = 2 ** TREE_DEPTH - 1;
/**
* @title MerkleLib
* @author Celo Labs Inc.
* @notice An incremental merkle tree modeled on the eth2 deposit contract.
**/
library MerkleLib {
/**
* @notice Struct representing incremental merkle tree. Contains current
* branch and the number of inserted leaves in the tree.
**/
struct Tree {
bytes32[TREE_DEPTH] branch;
uint256 count;
}
/**
* @notice Inserts `_node` into merkle tree
* @dev Reverts if tree is full
* @param _node Element to insert into tree
**/
function insert(Tree storage _tree, bytes32 _node) internal {
require(_tree.count < MAX_LEAVES, "merkle tree full");
_tree.count += 1;
uint256 size = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
if ((size & 1) == 1) {
_tree.branch[i] = _node;
return;
}
_node = keccak256(abi.encodePacked(_tree.branch[i], _node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}
/**
* @notice Calculates and returns`_tree`'s current root given array of zero
* hashes
* @param _zeroes Array of zero hashes
* @return _current Calculated root of `_tree`
**/
function rootWithCtx(
Tree storage _tree,
bytes32[TREE_DEPTH] memory _zeroes
) internal view returns (bytes32 _current) {
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
/// @notice Calculates and returns`_tree`'s current root
function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
/// @notice Returns array of TREE_DEPTH zero hashes
/// @return _zeroes Array of TREE_DEPTH zero hashes
function zeroHashes()
internal
pure
returns (bytes32[TREE_DEPTH] memory _zeroes)
{
_zeroes[0] = Z_0;
_zeroes[1] = Z_1;
_zeroes[2] = Z_2;
_zeroes[3] = Z_3;
_zeroes[4] = Z_4;
_zeroes[5] = Z_5;
_zeroes[6] = Z_6;
_zeroes[7] = Z_7;
_zeroes[8] = Z_8;
_zeroes[9] = Z_9;
_zeroes[10] = Z_10;
_zeroes[11] = Z_11;
_zeroes[12] = Z_12;
_zeroes[13] = Z_13;
_zeroes[14] = Z_14;
_zeroes[15] = Z_15;
_zeroes[16] = Z_16;
_zeroes[17] = Z_17;
_zeroes[18] = Z_18;
_zeroes[19] = Z_19;
_zeroes[20] = Z_20;
_zeroes[21] = Z_21;
_zeroes[22] = Z_22;
_zeroes[23] = Z_23;
_zeroes[24] = Z_24;
_zeroes[25] = Z_25;
_zeroes[26] = Z_26;
_zeroes[27] = Z_27;
_zeroes[28] = Z_28;
_zeroes[29] = Z_29;
_zeroes[30] = Z_30;
_zeroes[31] = Z_31;
}
/**
* @notice Calculates and returns the merkle root for the given leaf
* `_item`, a merkle branch, and the index of `_item` in the tree.
* @param _item Merkle leaf
* @param _branch Merkle proof
* @param _index Index of `_item` in tree
* @return _current Calculated merkle root
**/
function branchRoot(
bytes32 _item,
bytes32[TREE_DEPTH] memory _branch, // cheaper than calldata indexing
uint256 _index
) internal pure returns (bytes32 _current) {
_current = _item;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
// cheaper than calldata indexing _branch[i*32:(i+1)*32];
bytes32 _next = _branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _next));
}
}
}
/**
* @notice Calculates and returns the merkle root as if the index is
* the topmost leaf in the tree.
* @param _item Merkle leaf
* @param _branch Merkle proof
* @param _index Index of `_item` in tree
* @dev Replaces siblings greater than the index (right subtrees) with zeroes.
* @return _current Calculated merkle root
**/
function reconstructRoot(
bytes32 _item,
bytes32[TREE_DEPTH] memory _branch, // cheaper than calldata indexing
uint256 _index
) internal pure returns (bytes32 _current) {
_current = _item;
bytes32[TREE_DEPTH] memory _zeroes = zeroHashes();
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
// cheaper than calldata indexing _branch[i*32:(i+1)*32];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_branch[i], _current));
} else {
// remove right subtree from proof
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
// keccak256 zero hashes
bytes32 internal constant Z_0 =
hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes32 internal constant Z_1 =
hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5";
bytes32 internal constant Z_2 =
hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30";
bytes32 internal constant Z_3 =
hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85";
bytes32 internal constant Z_4 =
hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344";
bytes32 internal constant Z_5 =
hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d";
bytes32 internal constant Z_6 =
hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968";
bytes32 internal constant Z_7 =
hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83";
bytes32 internal constant Z_8 =
hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af";
bytes32 internal constant Z_9 =
hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0";
bytes32 internal constant Z_10 =
hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5";
bytes32 internal constant Z_11 =
hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892";
bytes32 internal constant Z_12 =
hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c";
bytes32 internal constant Z_13 =
hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb";
bytes32 internal constant Z_14 =
hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc";
bytes32 internal constant Z_15 =
hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2";
bytes32 internal constant Z_16 =
hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f";
bytes32 internal constant Z_17 =
hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a";
bytes32 internal constant Z_18 =
hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0";
bytes32 internal constant Z_19 =
hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0";
bytes32 internal constant Z_20 =
hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2";
bytes32 internal constant Z_21 =
hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9";
bytes32 internal constant Z_22 =
hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377";
bytes32 internal constant Z_23 =
hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652";
bytes32 internal constant Z_24 =
hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef";
bytes32 internal constant Z_25 =
hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d";
bytes32 internal constant Z_26 =
hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0";
bytes32 internal constant Z_27 =
hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e";
bytes32 internal constant Z_28 =
hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e";
bytes32 internal constant Z_29 =
hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322";
bytes32 internal constant Z_30 =
hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735";
bytes32 internal constant Z_31 =
hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9";
}
@hyperlane-xyz/core/contracts/client/MailboxClient.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
// ============ Internal Imports ============
import {IMailbox} from "../interfaces/IMailbox.sol";
import {IPostDispatchHook} from "../interfaces/hooks/IPostDispatchHook.sol";
import {IInterchainSecurityModule} from "../interfaces/IInterchainSecurityModule.sol";
import {Message} from "../libs/Message.sol";
import {PackageVersioned} from "../PackageVersioned.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract MailboxClient is OwnableUpgradeable, PackageVersioned {
using Message for bytes;
event HookSet(address _hook);
event IsmSet(address _ism);
IMailbox public immutable mailbox;
uint32 public immutable localDomain;
IPostDispatchHook public hook;
IInterchainSecurityModule internal _interchainSecurityModule;
uint256[48] private __GAP; // gap for upgrade safety
// ============ Modifiers ============
modifier onlyContract(address _contract) {
require(
Address.isContract(_contract),
"MailboxClient: invalid mailbox"
);
_;
}
modifier onlyContractOrNull(address _contract) {
require(
Address.isContract(_contract) || _contract == address(0),
"MailboxClient: invalid contract setting"
);
_;
}
/**
* @notice Only accept messages from a Hyperlane Mailbox contract
*/
modifier onlyMailbox() {
require(
msg.sender == address(mailbox),
"MailboxClient: sender not mailbox"
);
_;
}
constructor(address _mailbox) onlyContract(_mailbox) {
mailbox = IMailbox(_mailbox);
localDomain = mailbox.localDomain();
_transferOwnership(msg.sender);
}
function interchainSecurityModule()
external
view
virtual
returns (IInterchainSecurityModule)
{
return _interchainSecurityModule;
}
/**
* @notice Sets the address of the application's custom hook.
* @param _hook The address of the hook contract.
*/
function setHook(
address _hook
) public virtual onlyContractOrNull(_hook) onlyOwner {
hook = IPostDispatchHook(_hook);
emit HookSet(_hook);
}
/**
* @notice Sets the address of the application's custom interchain security module.
* @param _module The address of the interchain security module contract.
*/
function setInterchainSecurityModule(
address _module
) public onlyContractOrNull(_module) onlyOwner {
_interchainSecurityModule = IInterchainSecurityModule(_module);
emit IsmSet(_module);
}
// ======== Initializer =========
function _MailboxClient_initialize(
address _hook,
address __interchainSecurityModule,
address _owner
) internal onlyInitializing {
__Ownable_init();
setHook(_hook);
setInterchainSecurityModule(__interchainSecurityModule);
_transferOwnership(_owner);
}
function _isLatestDispatched(bytes32 id) internal view returns (bool) {
return mailbox.latestDispatchedId() == id;
}
function _isDelivered(bytes32 id) internal view returns (bool) {
return mailbox.delivered(id);
}
/// @dev True only while `mailbox.process()` is delivering `id` in the
/// current transaction. `process(...)` writes `deliveries[id].blockNumber`
/// before invoking the ISM, so this binds a check to the message being
/// processed *now* — stricter than `_isDelivered`, which stays true for any
/// previously-delivered message.
function _isProcessing(bytes32 id) internal view returns (bool) {
return mailbox.processedAt(id) == block.number;
}
}
@hyperlane-xyz/core/contracts/hooks/libs/AbstractPostDispatchHook.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// ============ Internal Imports ============
import {StandardHookMetadata} from "./StandardHookMetadata.sol";
import {IPostDispatchHook} from "../../interfaces/hooks/IPostDispatchHook.sol";
import {PackageVersioned} from "../../PackageVersioned.sol";
import {Message} from "../../libs/Message.sol";
/**
* @title AbstractPostDispatch
* @notice Abstract post dispatch hook supporting the current global hook metadata variant.
* @dev Hooks that charge fees denominated in native tokens should override
* `supportsMetadata` to reject metadata containing a non-zero fee token address.
* This prevents denomination mixing when `Mailbox.quoteDispatch` sums quotes from
* multiple hooks (e.g. `requiredHook` + `hook`), since the return type is a single
* `uint256` with no token denomination indicator.
*/
abstract contract AbstractPostDispatchHook is
IPostDispatchHook,
PackageVersioned
{
using StandardHookMetadata for bytes;
using Message for bytes;
using Address for address payable;
// ============ External functions ============
/// @inheritdoc IPostDispatchHook
/// @dev By default, accepts any valid variant-1 metadata including metadata
/// with a non-zero fee token. Hooks that charge non-zero native-token fees
/// should override this to return false when `metadata.feeToken() != address(0)`,
/// ensuring callers cannot mix native and ERC20 fee denominations.
function supportsMetadata(
bytes calldata metadata
) public view virtual returns (bool) {
return
metadata.length == 0 ||
metadata.variant() == StandardHookMetadata.VARIANT;
}
function _refund(
bytes calldata metadata,
bytes calldata message,
uint256 amount
) internal {
if (amount == 0) {
return;
}
address refundAddress = metadata.refundAddress(message.senderAddress());
require(
refundAddress != address(0),
"AbstractPostDispatchHook: no refund address"
);
payable(refundAddress).sendValue(amount);
}
/// @inheritdoc IPostDispatchHook
function postDispatch(
bytes calldata metadata,
bytes calldata message
) external payable override {
require(
supportsMetadata(metadata),
"AbstractPostDispatchHook: invalid metadata variant"
);
_postDispatch(metadata, message);
}
/// @inheritdoc IPostDispatchHook
function quoteDispatch(
bytes calldata metadata,
bytes calldata message
) public view override returns (uint256) {
require(
supportsMetadata(metadata),
"AbstractPostDispatchHook: invalid metadata variant"
);
return _quoteDispatch(metadata, message);
}
// ============ Internal functions ============
/**
* @notice Post dispatch hook implementation.
* @param metadata The metadata of the message being dispatched.
* @param message The message being dispatched.
*/
function _postDispatch(
bytes calldata metadata,
bytes calldata message
) internal virtual;
/**
* @notice Quote dispatch hook implementation.
* @param metadata The metadata of the message being dispatched.
* @param message The message being dispatched.
* @return The quote for the dispatch.
*/
function _quoteDispatch(
bytes calldata metadata,
bytes calldata message
) internal view virtual returns (uint256);
}
@hyperlane-xyz/core/contracts/hooks/libs/StandardHookMetadata.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
/**
* Format of metadata:
*
* [0:2] variant (uint16) = 1
* [2:34] msg.value (uint256)
* [34:66] Gas limit for message (uint256)
* [66:86] Refund address (address)
* [86:106] Fee token address (address) - OPTIONAL, read if length >= 106
*
* Fee Token Semantics:
* - When feeToken is address(0) or unspecified (metadata length < 106), fees are
* paid in native ETH via msg.value.
* - When feeToken is set to a non-zero address, fees are paid in that ERC-20 token.
* The caller must approve the hook to spend the fee token before calling dispatch.
*
* IMPORTANT: Mixing fee denominations within a single dispatch is NOT supported.
* All hooks in the call chain (requiredHook + hook, including any child hooks in
* aggregation) must use the same fee denomination. Hooks that only support native
* fees will reject metadata with a non-zero feeToken via supportsMetadata.
*
* The Mailbox.quoteDispatch function sums quotes from requiredHook and hook,
* assuming both return values in the same denomination. This works because:
* - Native-only hooks return 0 when feeToken is set (via supportsMetadata rejection)
* - The requiredHook (typically ProtocolFee) returns 0 when protocolFee is 0, allowing
* ERC-20 fee tokens to be used with the default hook even when requiredHook exists
*/
library StandardHookMetadata {
struct Metadata {
uint16 variant;
uint256 msgValue;
uint256 gasLimit;
address refundAddress;
}
uint8 private constant VARIANT_OFFSET = 0;
uint8 private constant MSG_VALUE_OFFSET = 2;
uint8 private constant GAS_LIMIT_OFFSET = 34;
uint8 private constant REFUND_ADDRESS_OFFSET = 66;
uint8 private constant FEE_TOKEN_OFFSET = 86;
uint16 public constant VARIANT = 1;
/**
* @notice Returns the variant of the metadata.
* @param _metadata ABI encoded standard hook metadata.
* @return variant of the metadata as uint16.
*/
function variant(bytes calldata _metadata) internal pure returns (uint16) {
if (_metadata.length < VARIANT_OFFSET + 2) return 0;
return uint16(bytes2(_metadata[VARIANT_OFFSET:VARIANT_OFFSET + 2]));
}
/**
* @notice Returns the specified value for the message.
* @param _metadata ABI encoded standard hook metadata.
* @param _default Default fallback value.
* @return Value for the message as uint256.
*/
function msgValue(
bytes calldata _metadata,
uint256 _default
) internal pure returns (uint256) {
if (_metadata.length < MSG_VALUE_OFFSET + 32) return _default;
return
uint256(bytes32(_metadata[MSG_VALUE_OFFSET:MSG_VALUE_OFFSET + 32]));
}
/**
* @notice Returns the specified gas limit for the message.
* @param _metadata ABI encoded standard hook metadata.
* @param _default Default fallback gas limit.
* @return Gas limit for the message as uint256.
*/
function gasLimit(
bytes calldata _metadata,
uint256 _default
) internal pure returns (uint256) {
if (_metadata.length < GAS_LIMIT_OFFSET + 32) return _default;
return
uint256(bytes32(_metadata[GAS_LIMIT_OFFSET:GAS_LIMIT_OFFSET + 32]));
}
function gasLimit(
bytes memory _metadata
) internal pure returns (uint256 _gasLimit) {
if (_metadata.length < GAS_LIMIT_OFFSET + 32) return 50_000;
assembly {
_gasLimit := mload(add(_metadata, add(0x20, GAS_LIMIT_OFFSET)))
}
}
/**
* @notice Returns the specified refund address for the message.
* @param _metadata ABI encoded standard hook metadata.
* @param _default Default fallback refund address.
* @return Refund address for the message as address.
*/
function refundAddress(
bytes calldata _metadata,
address _default
) internal pure returns (address) {
if (_metadata.length < REFUND_ADDRESS_OFFSET + 20) return _default;
return
address(
bytes20(
_metadata[REFUND_ADDRESS_OFFSET:REFUND_ADDRESS_OFFSET + 20]
)
);
}
/**
* @notice Returns the fee token address for token-based gas payments.
* @param _metadata ABI encoded standard hook metadata.
* @param _default Default fallback fee token (typically address(0) for native).
* @return Fee token address at [86:106], or _default if metadata too short.
*/
function feeToken(
bytes calldata _metadata,
address _default
) internal pure returns (address) {
if (_metadata.length < FEE_TOKEN_OFFSET + 20) return _default;
return
address(bytes20(_metadata[FEE_TOKEN_OFFSET:FEE_TOKEN_OFFSET + 20]));
}
/**
* @notice Returns the fee token address for token-based gas payments (memory version).
* @param _metadata ABI encoded standard hook metadata.
* @return _feeToken Fee token address at [86:106], or address(0) if metadata too short.
*/
function feeToken(
bytes memory _metadata
) internal pure returns (address _feeToken) {
if (_metadata.length < FEE_TOKEN_OFFSET + 20) return address(0);
assembly {
let data_start_ptr := add(_metadata, 32) // Skip length prefix
let mload_ptr := add(data_start_ptr, sub(FEE_TOKEN_OFFSET, 12))
_feeToken := mload(mload_ptr) // Loads 32 bytes; address takes lower 20 bytes
}
}
/**
* @notice Formats the specified gas limit and refund address into standard hook metadata.
* @param _msgValue msg.value for the message.
* @param _gasLimit Gas limit for the message.
* @param _refundAddress Refund address for the message.
* @return ABI encoded standard hook metadata.
*/
function format(
uint256 _msgValue,
uint256 _gasLimit,
address _refundAddress
) internal pure returns (bytes memory) {
return abi.encodePacked(VARIANT, _msgValue, _gasLimit, _refundAddress);
}
/**
* @notice Formats the specified gas limit and refund address into standard hook metadata.
* @param _msgValue msg.value for the message.
* @param _gasLimit Gas limit for the message.
* @param _refundAddress Refund address for the message.
* @param _customMetadata Additional metadata to include in the standard hook metadata.
* @return ABI encoded standard hook metadata.
*/
function formatMetadata(
uint256 _msgValue,
uint256 _gasLimit,
address _refundAddress,
bytes memory _customMetadata
) internal pure returns (bytes memory) {
return
abi.encodePacked(
VARIANT,
_msgValue,
_gasLimit,
_refundAddress,
_customMetadata
);
}
/**
* @notice Formats the specified gas limit and refund address into standard hook metadata.
* @param _msgValue msg.value for the message.
* @return ABI encoded standard hook metadata.
*/
function overrideMsgValue(
uint256 _msgValue
) internal view returns (bytes memory) {
return formatMetadata(_msgValue, uint256(0), msg.sender, "");
}
/**
* @notice Formats the specified gas limit and refund address into standard hook metadata.
* @param _gasLimit Gas limit for the message.
* @return ABI encoded standard hook metadata.
*/
function overrideGasLimit(
uint256 _gasLimit
) internal view returns (bytes memory) {
return formatMetadata(uint256(0), _gasLimit, msg.sender, "");
}
/**
* @notice Formats the specified refund address into standard hook metadata.
* @param _refundAddress Refund address for the message.
* @return ABI encoded standard hook metadata.
*/
function overrideRefundAddress(
address _refundAddress
) internal pure returns (bytes memory) {
return formatMetadata(uint256(0), uint256(0), _refundAddress, "");
}
/**
* @notice Formats metadata with fee token for token-based gas payments.
* @param _msgValue msg.value for the message.
* @param _gasLimit Gas limit for the message.
* @param _refundAddress Refund address for the message.
* @param _feeToken Fee token address for gas payment.
* @return ABI encoded hook metadata with fee token at [86:106].
*/
function formatWithFeeToken(
uint256 _msgValue,
uint256 _gasLimit,
address _refundAddress,
address _feeToken
) internal pure returns (bytes memory) {
return
abi.encodePacked(
VARIANT,
_msgValue,
_gasLimit,
_refundAddress,
_feeToken
);
}
function getRefundAddress(
bytes memory _metadata,
address _default
) internal pure returns (address) {
if (_metadata.length < REFUND_ADDRESS_OFFSET + 20) return _default;
address result;
assembly {
let data_start_ptr := add(_metadata, 32) // Skip length prefix of _metadata
let mload_ptr := add(data_start_ptr, sub(REFUND_ADDRESS_OFFSET, 12))
result := mload(mload_ptr) // Loads 32 bytes; address takes lower 20 bytes.
}
return result;
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../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.
*
* By default, the owner account will be the one that deploys the contract. 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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
}
@openzeppelin/contracts/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@hyperlane-xyz/core/contracts/isms/aggregation/StaticAggregationIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {AbstractAggregationIsm} from "./AbstractAggregationIsm.sol";
import {MetaProxy} from "../../libs/MetaProxy.sol";
/**
* @title StaticAggregationIsm
* @notice Manages per-domain m-of-n ISM sets that are used to verify
* interchain messages.
*/
contract StaticAggregationIsm is AbstractAggregationIsm {
// ============ Public Functions ============
/**
* @notice Returns the set of ISMs responsible for verifying _message
* and the number of ISMs that must verify
* @dev Can change based on the content of _message
* @return modules The array of ISM addresses
* @return threshold The number of ISMs needed to verify
*/
function modulesAndThreshold(
bytes calldata
) public view override returns (address[] memory, uint8) {
return abi.decode(MetaProxy.metadata(), (address[], uint8));
}
}
@hyperlane-xyz/core/contracts/libs/StaticAddressSetFactory.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Create2} from "@openzeppelin/contracts/utils/Create2.sol";
// ============ Internal Imports ============
import {MetaProxy} from "./MetaProxy.sol";
import {PackageVersioned} from "../PackageVersioned.sol";
import {IThresholdAddressFactory} from "../interfaces/IThresholdAddressFactory.sol";
abstract contract StaticThresholdAddressSetFactory is
PackageVersioned,
IThresholdAddressFactory
{
// ============ Immutables ============
address public immutable implementation;
// ============ Constructor ============
constructor() {
implementation = _deployImplementation();
}
function _deployImplementation() internal virtual returns (address);
/**
* @notice Deploys a StaticThresholdAddressSet contract address for the given
* values
* @dev Consider sorting addresses to ensure contract reuse
* @param _values An array of addresses
* @param _threshold The threshold value to use
* @return set The contract address representing this StaticThresholdAddressSet
*/
function deploy(
address[] calldata _values,
uint8 _threshold
) public returns (address) {
require(
0 < _threshold && _threshold <= _values.length,
"Invalid threshold"
);
(bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(
_values,
_threshold
);
address _set = _getAddress(_salt, _bytecode);
if (!Address.isContract(_set)) {
_set = Create2.deploy(0, _salt, _bytecode);
}
return _set;
}
/**
* @notice Returns the StaticThresholdAddressSet contract address for the given
* values
* @dev Consider sorting addresses to ensure contract reuse
* @param _values An array of addresses
* @param _threshold The threshold value to use
* @return set The contract address representing this StaticThresholdAddressSet
*/
function getAddress(
address[] calldata _values,
uint8 _threshold
) external view returns (address) {
(bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(
_values,
_threshold
);
return _getAddress(_salt, _bytecode);
}
/**
* @notice Returns the StaticThresholdAddressSet contract address for the given
* values
* @param _salt The salt used in Create2
* @param _bytecode The metaproxy bytecode used in Create2
* @return set The contract address representing this StaticThresholdAddressSet
*/
function _getAddress(
bytes32 _salt,
bytes memory _bytecode
) internal view returns (address) {
bytes32 _bytecodeHash = keccak256(_bytecode);
return Create2.computeAddress(_salt, _bytecodeHash);
}
/**
* @notice Returns the create2 salt and bytecode for the given values
* @param _values An array of addresses
* @param _threshold The threshold value to use
* @return _salt The salt used in Create2
* @return _bytecode The metaproxy bytecode used in Create2
*/
function _saltAndBytecode(
address[] calldata _values,
uint8 _threshold
) internal view returns (bytes32, bytes memory) {
bytes memory _metadata = abi.encode(_values, _threshold);
bytes memory _bytecode = MetaProxy.bytecode(implementation, _metadata);
bytes32 _salt = keccak256(_metadata);
return (_salt, _bytecode);
}
}
abstract contract StaticAddressSetFactory is StaticThresholdAddressSetFactory {
/**
* @notice Deploys a StaticAddressSet contract address for the given
* values
* @dev Consider sorting addresses to ensure contract reuse
* @param _values An array of addresses
* @return set The contract address representing this StaticAddressSet
*/
function deploy(address[] calldata _values) external returns (address) {
return super.deploy(_values, uint8(_values.length));
}
/**
* @notice Returns the StaticAddressSet contract address for the given
* values
* @dev Consider sorting addresses to ensure contract reuse
* @param _values An array of addresses
* @return set The contract address representing this StaticAddressSet
*/
function getAddress(
address[] calldata _values
) external view returns (address) {
(bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(
_values,
uint8(_values.length)
);
return super._getAddress(_salt, _bytecode);
}
}
@hyperlane-xyz/core/contracts/isms/multisig/AbstractMultisigIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// ============ Internal Imports ============
import {IMultisigIsm} from "../../interfaces/isms/IMultisigIsm.sol";
import {PackageVersioned} from "../../PackageVersioned.sol";
/**
* @title AbstractMultisig
* @notice Manages per-domain m-of-n Validator sets
* @dev See ./AbstractMerkleRootMultisigIsm.sol and ./AbstractMessageIdMultisigIsm.sol
* for concrete implementations of `digest` and `signatureAt`.
* @dev See ./StaticMultisigIsm.sol for concrete implementations.
*/
abstract contract AbstractMultisig is PackageVersioned {
/**
* @notice Returns the digest to be used for signature verification.
* @param _metadata ABI encoded module metadata
* @param _message Formatted Hyperlane message (see Message.sol).
* @return digest The digest to be signed by validators
*/
function digest(
bytes calldata _metadata,
bytes calldata _message
) internal view virtual returns (bytes32);
/**
* @notice Returns the signature at a given index from the metadata.
* @param _metadata ABI encoded module metadata
* @param _index The index of the signature to return
* @return signature Packed encoding of signature (65 bytes)
*/
function signatureAt(
bytes calldata _metadata,
uint256 _index
) internal pure virtual returns (bytes calldata);
/**
* @notice Returns the number of signatures in the metadata.
* @param _metadata ABI encoded module metadata
* @return count The number of signatures
*/
function signatureCount(
bytes calldata _metadata
) public pure virtual returns (uint256);
}
/**
* @title AbstractMultisigIsm
* @notice Manages per-domain m-of-n Validator sets of AbstractMultisig that are used to verify
* interchain messages.
*/
abstract contract AbstractMultisigIsm is AbstractMultisig, IMultisigIsm {
// ============ Virtual Functions ============
// ======= OVERRIDE THESE TO IMPLEMENT =======
/**
* @notice Returns the set of validators responsible for verifying _message
* and the number of signatures required
* @dev Can change based on the content of _message
* @dev Signatures provided to `verify` must be consistent with validator ordering
* @param _message Hyperlane formatted interchain message
* @return validators The array of validator addresses
* @return threshold The number of validator signatures needed
*/
function validatorsAndThreshold(
bytes calldata _message
) public view virtual returns (address[] memory, uint8);
// ============ Public Functions ============
/**
* @notice Requires that m-of-n validators verify a merkle root,
* and verifies a merkle proof of `_message` against that root.
* @dev Optimization relies on the caller sorting signatures in the same order as validators.
* @dev Employs https://www.geeksforgeeks.org/two-pointers-technique/ to minimize gas usage.
* @param _metadata ABI encoded module metadata
* @param _message Formatted Hyperlane message (see Message.sol).
*/
function verify(
bytes calldata _metadata,
bytes calldata _message
) public view returns (bool) {
bytes32 _digest = digest(_metadata, _message);
(
address[] memory _validators,
uint8 _threshold
) = validatorsAndThreshold(_message);
require(_threshold > 0, "No MultisigISM threshold present for message");
uint256 _validatorCount = _validators.length;
uint256 _validatorIndex = 0;
// Assumes that signatures are ordered by validator
for (uint256 i = 0; i < _threshold; ++i) {
address _signer = ECDSA.recover(_digest, signatureAt(_metadata, i));
// Loop through remaining validators until we find a match
while (
_validatorIndex < _validatorCount &&
_signer != _validators[_validatorIndex]
) {
++_validatorIndex;
}
// Fail if we never found a match
require(_validatorIndex < _validatorCount, "!threshold");
++_validatorIndex;
}
return true;
}
}
@hyperlane-xyz/core/contracts/isms/multisig/AbstractMerkleRootMultisigIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {AbstractMultisig} from "./AbstractMultisigIsm.sol";
import {MerkleRootMultisigIsmMetadata} from "../../isms/libs/MerkleRootMultisigIsmMetadata.sol";
import {Message} from "../../libs/Message.sol";
import {MerkleLib} from "../../libs/Merkle.sol";
import {CheckpointLib} from "../../libs/CheckpointLib.sol";
/**
* @title `AbstractMerkleRootMultisigIsm` — multi-sig ISM with the validators-censorship resistance guarantee.
* @notice This ISM allows using a newer signed checkpoint (say #33) to prove existence of an older message (#22) in the validators' MerkleTree.
* This guarantees censorship resistance as validators cannot hide a message
* by refusing to sign its checkpoint but later signing a checkpoint for a newer message.
* If validators decide to censor a message, they are left with only one option — to not produce checkpoints at all.
* Otherwise, the very next signed checkpoint (#33) can be used by any relayer to prove the previous message inclusion using this ISM.
* This is censorship resistance is missing in the sibling implementation `AbstractMessageIdMultisigIsm`,
* since it can only verify messages having the corresponding checkpoints.
* @dev Provides the default implementation of verifying signatures over a checkpoint and the message inclusion in that checkpoint.
* This abstract contract can be overridden for customizing the `validatorsAndThreshold()` (static or dynamic).
* @dev May be adapted in future to support batch message verification against a single root.
*/
abstract contract AbstractMerkleRootMultisigIsm is AbstractMultisig {
using MerkleRootMultisigIsmMetadata for bytes;
using Message for bytes;
// ============ Constants ============
/**
* @inheritdoc AbstractMultisig
*/
function digest(
bytes calldata _metadata,
bytes calldata _message
) internal pure override returns (bytes32) {
require(
_metadata.messageIndex() <= _metadata.signedIndex(),
"Invalid merkle index metadata"
);
// We verify a merkle proof of (messageId, index) I to compute root J
bytes32 _signedRoot = MerkleLib.branchRoot(
_message.id(),
_metadata.proof(),
_metadata.messageIndex()
);
// We provide (messageId, index) J in metadata for digest derivation
return
CheckpointLib.digest(
_message.origin(),
_metadata.originMerkleTreeHook(),
_signedRoot,
_metadata.signedIndex(),
_metadata.signedMessageId()
);
}
/**
* @inheritdoc AbstractMultisig
*/
function signatureAt(
bytes calldata _metadata,
uint256 _index
) internal pure override returns (bytes calldata) {
return _metadata.signatureAt(_index);
}
/**
* @inheritdoc AbstractMultisig
*/
function signatureCount(
bytes calldata _metadata
) public pure override returns (uint256) {
return _metadata.signatureCount();
}
}
@hyperlane-xyz/core/contracts/isms/multisig/AbstractMessageIdMultisigIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {AbstractMultisig} from "./AbstractMultisigIsm.sol";
import {MessageIdMultisigIsmMetadata} from "../libs/MessageIdMultisigIsmMetadata.sol";
import {Message} from "../../libs/Message.sol";
import {CheckpointLib} from "../../libs/CheckpointLib.sol";
/**
* @title `AbstractMessageIdMultisigIsm` — multi-sig ISM for the censorship-friendly validators.
* @notice This ISM minimizes gas/performance overhead of the checkpoints verification by compromising on the censorship resistance.
* For censorship resistance consider using `AbstractMerkleRootMultisigIsm`.
* If the validators (`validatorsAndThreshold`) skip messages by not sign checkpoints for them,
* the relayers will not be able to aggregate a quorum of signatures sufficient to deliver these messages via this ISM.
* Integrations are free to choose the trade-off between the censorship resistance and the gas/processing overhead.
* @dev Provides the default implementation of verifying signatures over a checkpoint related to a specific message ID.
* This abstract contract can be customized to change the `validatorsAndThreshold()` (static or dynamic).
*/
abstract contract AbstractMessageIdMultisigIsm is AbstractMultisig {
using Message for bytes;
using MessageIdMultisigIsmMetadata for bytes;
// ============ Constants ============
/**
* @inheritdoc AbstractMultisig
*/
function digest(
bytes calldata _metadata,
bytes calldata _message
) internal pure override returns (bytes32) {
return
CheckpointLib.digest(
_message.origin(),
_metadata.originMerkleTreeHook(),
_metadata.root(),
_metadata.index(),
_message.id()
);
}
/**
* @inheritdoc AbstractMultisig
*/
function signatureAt(
bytes calldata _metadata,
uint256 _index
) internal pure override returns (bytes calldata) {
return _metadata.signatureAt(_index);
}
/**
* @inheritdoc AbstractMultisig
*/
function signatureCount(
bytes calldata _metadata
) public pure override returns (uint256) {
return _metadata.signatureCount();
}
}
@hyperlane-xyz/core/contracts/libs/MetaProxy.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity >=0.7.6;
/// @dev Adapted from https://eips.ethereum.org/EIPS/eip-3448
library MetaProxy {
bytes32 private constant PREFIX =
hex"600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73";
bytes13 private constant SUFFIX = hex"5af43d3d93803e603457fd5bf3";
function bytecode(
address _implementation,
bytes memory _metadata
) internal pure returns (bytes memory) {
return
abi.encodePacked(
PREFIX,
bytes20(_implementation),
SUFFIX,
_metadata,
_metadata.length
);
}
function metadata() internal pure returns (bytes memory) {
bytes memory data;
assembly {
let posOfMetadataSize := sub(calldatasize(), 32)
let size := calldataload(posOfMetadataSize)
let dataPtr := sub(posOfMetadataSize, size)
data := mload(64)
// increment free memory pointer by metadata size + 32 bytes (length)
mstore(64, add(data, add(size, 32)))
mstore(data, size)
let memPtr := add(data, 32)
calldatacopy(memPtr, dataPtr, size)
}
return data;
}
}
@hyperlane-xyz/core/contracts/token/libs/TokenRouter.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {TypeCasts} from "../../libs/TypeCasts.sol";
import {GasRouter} from "../../client/GasRouter.sol";
import {TokenMessage} from "./TokenMessage.sol";
import {Quote, ITokenBridge, ITokenFee} from "../../interfaces/ITokenBridge.sol";
import {Quotes} from "./Quotes.sol";
import {StandardHookMetadata} from "../../hooks/libs/StandardHookMetadata.sol";
// ============ External Imports ============
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @title Hyperlane Token Router that extends Router with abstract token (ERC20/ERC721) remote transfer functionality.
* @dev Overridable functions:
* - token(): specify the managed token address
* - _transferFromSender(uint256): pull tokens/ETH from msg.sender
* - _transferTo(address,uint256): send tokens/ETH to the recipient
* - _externalFeeAmount(uint32,bytes32,uint256): compute external fees (default returns 0)
* @dev Override transferRemote only to implement custom logic that can't be accomplished with the above functions.
*
* @author Abacus Works
*/
abstract contract TokenRouter is GasRouter, ITokenBridge {
using TypeCasts for bytes32;
using TypeCasts for address;
using TokenMessage for bytes;
using StandardHookMetadata for bytes;
using StorageSlot for bytes32;
using Quotes for Quote[];
using Math for uint256;
using SafeERC20 for IERC20;
/**
* @dev Emitted on `transferRemote` when a transfer message is dispatched.
* @param destination The identifier of the destination chain.
* @param recipient The address of the recipient on the destination chain.
* @param amountOrId The amount or ID of tokens sent in to the remote recipient.
*/
event SentTransferRemote(
uint32 indexed destination,
bytes32 indexed recipient,
uint256 amountOrId
);
/**
* @dev Emitted on `_handle` when a transfer message is processed.
* @param origin The identifier of the origin chain.
* @param recipient The address of the recipient on the destination chain.
* @param amountOrId The amount or ID of tokens received from the remote sender.
*/
event ReceivedTransferRemote(
uint32 indexed origin,
bytes32 indexed recipient,
uint256 amountOrId
);
uint256 public immutable scaleNumerator;
uint256 public immutable scaleDenominator;
// cannot use compiler assigned slot without
// breaking backwards compatibility of storage layout
bytes32 private constant FEE_RECIPIENT_SLOT =
keccak256("FungibleTokenRouter.feeRecipient");
bytes32 private constant FEE_HOOK_SLOT = keccak256("TokenRouter.feeHook");
event FeeRecipientSet(address feeRecipient);
event FeeHookSet(address feeHook);
constructor(
uint256 _scaleNumerator,
uint256 _scaleDenominator,
address _mailbox
) GasRouter(_mailbox) {
require(
_scaleNumerator > 0 && _scaleDenominator > 0,
"TokenRouter: scale cannot be 0"
);
scaleNumerator = _scaleNumerator;
scaleDenominator = _scaleDenominator;
}
// ===========================
// ========== Main API ==========
// ===========================
/**
* @notice Returns the address of the token managed by this router. It can be one of three options:
* - ERC20 token address for fungible tokens that are being collateralized (HypERC20Collateral, HypERC4626, etc.)
* - 0x0 address for native tokens (ETH, MATIC, etc.) (HypNative, etc.)
* - address(this) for synthetic ERC20 tokens (HypERC20, etc.)
* It is being used for quotes and fees from the fee recipient and pulling/push the tokens from the sender/receipient.
* @dev This function must be implemented by derived contracts to specify the token address.
* @return The address of the token contract.
*/
function token() public view virtual returns (address);
/**
* @inheritdoc ITokenFee
* @notice Implements the standardized fee quoting interface for token transfers based on
* overridable internal functions of _quoteGasPayment, _feeRecipientAndAmount, and _externalFeeAmount.
* @param _destination The identifier of the destination chain.
* @param _recipient The address of the recipient on the destination chain.
* @param _amount The amount or identifier of tokens to be sent to the remote recipient
* @return quotes An array of Quote structs representing the fees in different tokens.
* @dev This function may return multiple quotes with the same denomination. Convention is to return:
* [index 0] native fees charged by the mailbox dispatch
* [index 1] then any internal warp route fees (amount bridged plus fee recipient)
* [index 2] then any external bridging fees (if any, else 0)
* These are surfaced as separate elements to enable clients to interpret/render fees independently.
* There is a Quotes library with an extract function for onchain quoting in a specific denomination,
* but we discourage onchain quoting in favor of offchain quoting and overpaying with refunds.
*/
function quoteTransferRemote(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) external view virtual override returns (Quote[] memory quotes) {
address _feeToken = feeToken();
quotes = new Quote[](3);
quotes[0] = Quote({
token: _feeToken, // address(0) for native, token() for ERC20 payments
amount: _quoteGasPayment(
_destination,
_recipient,
_amount,
_feeToken
)
});
(, uint256 feeAmount) = _feeRecipientAndAmount(
_destination,
_recipient,
_amount
);
quotes[1] = Quote({token: token(), amount: _amount + feeAmount});
quotes[2] = Quote({
token: token(),
amount: _externalFeeAmount(_destination, _recipient, _amount)
});
}
/**
* @notice Transfers `_amount` token to `_recipient` on the `_destination` domain.
* @dev Delegates transfer logic to `_transferFromSender` implementation.
* Emits `SentTransferRemote` event on the origin chain.
* Override with custom behavior for storing or forwarding tokens.
* Known overrides:
* - OPL2ToL1TokenBridgeNative: adds hook metadata for message dispatch.
* - EverclearTokenBridge: creates Everclear intent for cross-chain token transfer.
* - TokenBridgeCctpBase: adds CCTP-specific metadata for message dispatch.
* - HypERC4626Collateral: deposits into vault and handles shares.
* When overriding, mirror the general flow of this function for consistency:
* 1. Calculate fees and charge the sender.
* 2. Prepare the token message with recipient, amount, and any additional metadata.
* 3. Emit `SentTransferRemote` event.
* 4. Dispatch the message.
* @param _destination The identifier of the destination chain.
* @param _recipient The address of the recipient on the destination chain.
* @param _amount The amount or identifier of tokens to be sent to the remote recipient.
* @return messageId The identifier of the dispatched message.
*/
function transferRemote(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) public payable virtual returns (bytes32 messageId) {
return _transferRemote(_destination, _recipient, _amount);
}
/// @notice Internal transfer implementation.
function _transferRemote(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) internal virtual returns (bytes32 messageId) {
address _feeHook = feeHook();
address _feeToken = feeToken();
// 1. Calculate the fee amounts, charge the sender and distribute to feeRecipient if necessary
(, uint256 remainingNativeValue) = _calculateFeesAndCharge(
_destination,
_recipient,
_amount,
msg.value,
_feeHook
);
uint256 scaledAmount = _outboundAmount(_amount);
// 2. Prepare the token message with the recipient and amount
bytes memory _tokenMessage = TokenMessage.format(
_recipient,
scaledAmount
);
messageId = _emitAndDispatch(
_destination,
_recipient,
scaledAmount,
remainingNativeValue,
_tokenMessage,
_feeToken
);
}
// ===========================
// ========== Internal convenience functions for readability ==========
// ==========================
function _calculateFeesAndCharge(
uint32 _destination,
bytes32 _recipient,
uint256 _amount,
uint256 _msgValue,
address _feeHook
) internal returns (uint256 externalFee, uint256 remainingNativeValue) {
(address _feeRecipient, uint256 feeAmount) = _feeRecipientAndAmount(
_destination,
_recipient,
_amount
);
externalFee = _externalFeeAmount(_destination, _recipient, _amount);
uint256 charge = _amount + feeAmount + externalFee;
address _token = token();
// ERC20 fee hook: use token() for gas payments
if (_feeHook != address(0)) {
uint256 hookFee = _quoteGasPayment(
_destination,
_recipient,
_amount,
_token
);
// For collateral routers (token() != address(this)), we can add hook fee to charge
// because _transferFromSender pulls tokens TO the router.
// For synthetic routers (token() == address(this)), we must pull separately
// because _transferFromSender burns tokens, so router never receives them.
if (_token != address(this)) {
// Collateral router: add hook fee to charge
charge += hookFee;
} else {
// Synthetic router: pull hook fee tokens separately
IERC20(_token).safeTransferFrom(
msg.sender,
address(this),
hookFee
);
}
// Per-call approval only: standing approvals to fee hooks are unsafe
// because postDispatch is publicly callable with arbitrary message data,
// allowing a third party to spend the approval. Funds would go to the
// hook beneficiary (not the attacker), but the caller still loses tokens.
IERC20(_token).forceApprove(_feeHook, hookFee);
}
_transferFromSender(charge);
if (feeAmount > 0) {
// transfer atomically so we don't need to keep track of collateral
// and fee balances separately
_transferFee(_feeRecipient, feeAmount);
}
// Calculate remaining native value for other hooks
// When token() is ERC20 (non-native), all native value is available for other hooks
// When token() is native (address(0)), subtract the charge from msg.value
remainingNativeValue = _token != address(0)
? _msgValue
: _msgValue - charge;
}
// Convenience overload that computes feeHook() internally.
function _calculateFeesAndCharge(
uint32 _destination,
bytes32 _recipient,
uint256 _amount,
uint256 _msgValue
) internal returns (uint256 externalFee, uint256 remainingNativeValue) {
return
_calculateFeesAndCharge(
_destination,
_recipient,
_amount,
_msgValue,
feeHook()
);
}
// Emits the SentTransferRemote event and dispatches the message with explicit feeToken.
function _emitAndDispatch(
uint32 _destination,
bytes32 _recipient,
uint256 _amount,
uint256 _messageDispatchValue,
bytes memory _tokenMessage,
address _feeToken
) internal returns (bytes32 messageId) {
// effects
emit SentTransferRemote(_destination, _recipient, _amount);
// interactions
messageId = _Router_dispatch(
_destination,
_messageDispatchValue,
_tokenMessage,
_generateHookMetadata(_destination, _feeToken),
address(hook)
);
}
// Convenience overload that computes feeToken from feeHook().
function _emitAndDispatch(
uint32 _destination,
bytes32 _recipient,
uint256 _amount,
uint256 _messageDispatchValue,
bytes memory _tokenMessage
) internal returns (bytes32 messageId) {
address _feeToken = feeToken();
return
_emitAndDispatch(
_destination,
_recipient,
_amount,
_messageDispatchValue,
_tokenMessage,
_feeToken
);
}
// ===========================
// ========== Fees & Quoting ==========
// ===========================
/**
* @notice Sets the fee recipient for the router.
* @dev Allows for address(0) to be set, which disables fees.
* @param recipient The address that receives fees.
*/
function setFeeRecipient(address recipient) public onlyOwner {
require(recipient != address(this), "Fee recipient cannot be self");
FEE_RECIPIENT_SLOT.getAddressSlot().value = recipient;
emit FeeRecipientSet(recipient);
}
/**
* @notice Returns the address of the fee recipient.
* @dev Returns address(0) if no fee recipient is set.
* @dev Can be overridden with address(0) to disable fees entirely.
* @return address of the fee recipient.
*/
function feeRecipient() public view virtual returns (address) {
return FEE_RECIPIENT_SLOT.getAddressSlot().value;
}
/**
* @notice Initializes the TokenRouter with fee hook configuration.
* @param _feeHook The fee hook contract address.
*/
function _TokenRouter_initialize(address _feeHook) internal {
_setFeeHook(_feeHook);
}
/**
* @notice Sets the fee hook contract address.
* @param _feeHook The fee hook address.
*/
function setFeeHook(address _feeHook) external onlyOwner {
_setFeeHook(_feeHook);
}
/**
* @notice Internal function to set the fee hook address.
* @param _feeHook The fee hook address.
*/
function _setFeeHook(address _feeHook) internal {
if (_feeHook != address(0)) {
require(
token() != address(0),
"TokenRouter: fee hook requires ERC20 token"
);
}
FEE_HOOK_SLOT.getAddressSlot().value = _feeHook;
emit FeeHookSet(_feeHook);
}
/**
* @notice Returns the fee hook contract address.
* @return The fee hook address.
*/
function feeHook() public view returns (address) {
return FEE_HOOK_SLOT.getAddressSlot().value;
}
/**
* @notice Returns the fee token address for gas payments.
* @return The token address if a fee hook is configured, otherwise address(0) for native payments.
*/
function feeToken() public view returns (address) {
return feeHook() != address(0) ? token() : address(0);
}
// To be overridden by derived contracts if they have additional fees
/**
* @notice Returns the external fee amount for the given parameters.
* param _destination The identifier of the destination chain.
* param _recipient The address of the recipient on the destination chain.
* param _amount The amount or identifier of tokens to be sent to the remote recipient
* @return feeAmount The external fee amount.
* @dev This fee must be denominated in the `token()` defined by this router.
* @dev The default implementation returns 0, meaning no external fees are charged.
* This function is intended to be overridden by derived contracts that have additional fees.
* Known overrides:
* - TokenBridgeCctpBase: for CCTP-specific fees
* - EverclearTokenBridge: for Everclear-specific fees
*/
function _externalFeeAmount(
uint32, // _destination,
bytes32, // _recipient,
uint256 // _amount
) internal view virtual returns (uint256 feeAmount) {
return 0;
}
/**
* @notice Returns the fee recipient amount for the given parameters.
* @param _destination The identifier of the destination chain.
* @param _recipient The address of the recipient on the destination chain.
* @param _amount The amount or identifier of tokens to be sent to the remote recipient
* @return _feeRecipient The address of the fee recipient.
* @return feeAmount The fee recipient amount.
* @dev This function is is not intended to be overridden as storage and logic is contained in TokenRouter.
*/
function _feeRecipientAndAmount(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) internal view returns (address _feeRecipient, uint256 feeAmount) {
_feeRecipient = feeRecipient();
if (_feeRecipient == address(0)) {
return (_feeRecipient, 0);
}
Quote[] memory quotes = ITokenFee(_feeRecipient).quoteTransferRemote(
_destination,
_recipient,
_amount
);
if (quotes.length == 0) {
return (_feeRecipient, 0);
}
require(
quotes.length == 1 && quotes[0].token == token(),
"FungibleTokenRouter: fee must match token"
);
feeAmount = quotes[0].amount;
}
/**
* @notice Returns the gas payment required to dispatch a message to the given domain's router.
* @param _destination The identifier of the destination chain.
* @param _recipient The address of the recipient on the destination chain.
* @param _amount The amount or identifier of tokens to be sent to the remote recipient
* @return payment How much value to send in transferRemote call (native or feeToken based on config).
* @dev This function is intended to be overridden by derived contracts that trigger multiple messages.
* Known overrides:
* - OPL2ToL1TokenBridgeNative: Quote for two messages (prove and finalize).
*/
function _quoteGasPayment(
uint32 _destination,
bytes32 _recipient,
uint256 _amount,
address _feeToken
) internal view virtual returns (uint256) {
return
_Router_quoteDispatch(
_destination,
TokenMessage.format(_recipient, _outboundAmount(_amount)),
_generateHookMetadata(_destination, _feeToken),
address(hook)
);
}
/**
* @notice Generates hook metadata for dispatch, including feeToken if configured.
* @param _destination The destination chain.
* @param _feeToken The fee token address (address(0) for native).
* @return Hook metadata with the specified feeToken.
*/
function _generateHookMetadata(
uint32 _destination,
address _feeToken
) internal view returns (bytes memory) {
uint256 gasLimit = destinationGas[_destination];
return
StandardHookMetadata.formatWithFeeToken(
0,
gasLimit,
msg.sender,
_feeToken
);
}
// ===========================
// ========== Internal virtual functions for token handling ==========
// ===========================
/**
* @dev Should transfer `_amount` of tokens from `msg.sender` to this token router.
* Called by `transferRemote` before message dispatch.
* Known overrides:
* - HypERC20: Burns the tokens from the sender.
* - HypERC20Collateral: Pulls the tokens from the sender.
* - HypNative: Asserts msg.value >= _amount
* - TokenBridgeCctpBase: (like HypERC20Collateral) Pulls the tokens from the sender.
* - EverclearEthTokenBridge: Wraps the native token (ETH) to WETH
* - HypERC4626: Converts the amounts to shares and burns from the User (via HypERC20 implementation)
* - HypFiatToken: Pulls the tokens from the sender and burns them on the FiatToken contract.
* - HypXERC20: Burns the tokens from the sender.
* - HypXERC20Lockbox: Pulls the tokens from the sender, locks them in the XERC20Lockbox contract and burns the resulting xERC20 tokens.
*/
function _transferFromSender(uint256 _amountOrId) internal virtual;
/**
* @dev Should transfer `_amountOrId` of tokens from this token router to `_recipient`.
* @dev Called by `handle` after message decoding.
* Known overrides:
* - HypERC20: Mints the tokens to the recipient.
* - HypERC20Collateral: Releases the tokens to the recipient.
* - HypNative: Releases native tokens to the recipient.
* - TokenBridgeCctpBase: Do nothing (CCTP transfers tokens to the recipient directly).
* - EverclearEthTokenBridge: Unwraps WETH to ETH and sends to the recipient.
* - HypERC4626: Converts the amount to shares and mints to the User (via HypERC20 implementation)
* - HypFiatToken: Mints the tokens to the recipient on the FiatToken contract.
* - HypXERC20: Mints the tokens to the recipient.
* - HypXERC20Lockbox: Withdraws the underlying tokens from the Lockbox and sends to the recipient.
* - OpL1NativeTokenBridge: Do nothing (the L2 bridge transfers the native tokens to the recipient directly).
*/
function _transferTo(
address _recipient,
uint256 _amountOrId
) internal virtual;
/**
* @dev Should transfer `_amount` of tokens from this token router to the fee recipient.
* @dev Called by `_calculateFeesAndCharge` when fee recipient is set and feeAmount > 0.
* @dev The default implementation delegates to `_transferTo`, which works for most token routers
* where tokens are held by the router (e.g., collateral routers, synthetic token routers).
* @dev Override this function for bridges where tokens are NOT held by the router but fees still
* need to be paid (e.g., CCTP, Everclear). In those cases, use direct token transfers from the
* router's balance collected via `_transferFromSender`.
* Known overrides:
* - TokenBridgeCctpBase: Directly transfers tokens from router balance.
* - EverclearTokenBridge: Directly transfers tokens from router balance.
*/
function _transferFee(
address _recipient,
uint256 _amount
) internal virtual {
_transferTo(_recipient, _amount);
}
/**
* @dev Scales local amount to message amount by the scale fraction.
* Applies: messageAmount = (localAmount * scaleNumerator) / scaleDenominator
* - If scaleNumerator > scaleDenominator: scales up (e.g., 2/1)
* - If scaleNumerator < scaleDenominator: scales down (e.g., 1/2)
* - If scaleNumerator == scaleDenominator: no scaling (e.g., 1/1)
* Known overrides:
* - HypERC4626: Scales by exchange rate
*/
function _outboundAmount(
uint256 _localAmount
) internal view virtual returns (uint256 _messageAmount) {
_messageAmount = _localAmount.mulDiv(
scaleNumerator,
scaleDenominator,
Math.Rounding.Down
);
}
/**
* @dev Scales message amount to local amount by the inverse scale fraction.
* Applies: localAmount = (messageAmount * scaleDenominator) / scaleNumerator
* - If scaleNumerator > scaleDenominator: scales down (e.g., 1/2 for 2/1 outbound)
* - If scaleNumerator < scaleDenominator: scales up (e.g., 2/1 for 1/2 outbound)
* - If scaleNumerator == scaleDenominator: no scaling (e.g., 1/1)
* Known overrides:
* - HypERC4626: Scales by exchange rate
*/
function _inboundAmount(
uint256 _messageAmount
) internal view virtual returns (uint256 _localAmount) {
_localAmount = _messageAmount.mulDiv(
scaleDenominator,
scaleNumerator,
Math.Rounding.Down
);
}
/**
* @notice Handles the incoming transfer message.
* It decodes the message, emits the ReceivedTransferRemote event, and transfers tokens to the recipient.
* @param _origin The identifier of the origin chain.
* @dev param _sender The address of the sender router on the origin chain.
* @param _message The message data containing recipient and amount.
* @dev Override this function if custom logic is required for sending out the tokens.
* Known overrides:
* - EverclearTokenBridge: Receives the tokens and sends them to the recipient.
* - EverclearEthBridge: Receives WETH, unwraps it and sends native ETH to the recipient.
* - HypERC4626: Updates the exchange rate from the metadata
*/
// solhint-disable-next-line hyperlane/no-virtual-override
function _handle(
uint32 _origin,
bytes32,
bytes calldata _message
) internal virtual override {
bytes32 recipient = _message.recipient();
uint256 amount = _message.amount();
// effects
emit ReceivedTransferRemote(_origin, recipient, amount);
// interactions
_transferTo(recipient.bytes32ToAddress(), _inboundAmount(amount));
}
}
@hyperlane-xyz/core/contracts/interfaces/ITokenBridge.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
struct Quote {
address token; // address(0) for the native token, or ERC20 for token payments
uint256 amount;
}
interface ITokenFee {
/**
* @notice Provide the value transfer quote
* @param _destination The destination domain of the message
* @param _recipient The message recipient address on `destination`
* @param _amount The amount to send to the recipient
* @return quotes Indicate how much of each token to approve and/or send.
* @dev Good practice is to use the first entry of the quotes for the IGP fee (native or ERC20).
* @dev Good practice is to use the last entry of the quotes for the token to be transferred.
* @dev There should not be duplicate `token` addresses in the returned quotes.
*/
function quoteTransferRemote(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) external view returns (Quote[] memory quotes);
}
interface ITokenBridge is ITokenFee {
/**
* @notice Transfer value to another domain
* @param _destination The destination domain of the message
* @param _recipient The message recipient address on `destination`
* @param _amount The amount to send to the recipient
* @return messageId The identifier of the dispatched message.
*/
function transferRemote(
uint32 _destination,
bytes32 _recipient,
uint256 _amount
) external payable returns (bytes32);
}
@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
@hyperlane-xyz/core/contracts/token/libs/TokenMessage.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
library TokenMessage {
uint8 internal constant RECIPIENT_OFFSET = 0;
uint8 internal constant AMOUNT_OFFSET = 32;
uint8 internal constant METADATA_OFFSET = 64;
function format(
bytes32 _recipient,
uint256 _amount,
bytes memory _metadata
) internal pure returns (bytes memory) {
return abi.encodePacked(_recipient, _amount, _metadata);
}
function format(
bytes32 _recipient,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodePacked(_recipient, _amount);
}
function recipient(bytes calldata message) internal pure returns (bytes32) {
return bytes32(message[RECIPIENT_OFFSET:RECIPIENT_OFFSET + 32]);
}
function amount(bytes calldata message) internal pure returns (uint256) {
return uint256(bytes32(message[AMOUNT_OFFSET:AMOUNT_OFFSET + 32]));
}
// alias for ERC721
function tokenId(bytes calldata message) internal pure returns (uint256) {
return amount(message);
}
function metadata(
bytes calldata message
) internal pure returns (bytes calldata) {
return message[METADATA_OFFSET:];
}
}
@hyperlane-xyz/core/contracts/token/libs/MovableCollateralRouter.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;
import {ITokenBridge, Quote} from "../../interfaces/ITokenBridge.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {TokenRouter} from "./TokenRouter.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Router} from "../../client/Router.sol";
import {Quotes} from "./Quotes.sol";
struct MovableCollateralRouterStorage {
// TODO: replace the single recipient override with a per-domain recipient
// set when routes need multiple allowed same-chain rebalance recipients.
mapping(uint32 routerDomain => bytes32 recipient) recipient;
mapping(uint32 routerDomain => EnumerableSet.AddressSet bridges) bridges;
EnumerableSet.AddressSet rebalancers;
}
abstract contract MovableCollateralRouter is TokenRouter {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using Quotes for Quote[];
MovableCollateralRouterStorage internal allowed;
/// @dev For a move driven by `AtomicLocalRebalancingBridge`, `recipient` is
/// this router's configured recipient rather than the address the bridge
/// funds, and `amount` is the source outflow rather than the (decimal-
/// converted) amount delivered. Off-chain consumers should read the bridge's
/// `LocalRebalanceExecuted` event for that flow instead.
event CollateralMoved(
uint32 indexed domain,
bytes32 recipient,
uint256 amount,
address indexed rebalancer
);
modifier onlyRebalancer() {
require(isAllowedRebalancer(_msgSender()), "MCR: Only Rebalancer");
_;
}
modifier onlyAllowedBridge(uint32 domain, ITokenBridge bridge) {
EnumerableSet.AddressSet storage bridges = allowed.bridges[domain];
require(bridges.contains(address(bridge)), "MCR: Not allowed bridge");
_;
}
/// @notice Set of addresses that are allowed to rebalance.
function allowedRebalancers() external view returns (address[] memory) {
return allowed.rebalancers.values();
}
/// @notice Returns whether an address is allowed to rebalance.
function isAllowedRebalancer(
address rebalancer
) public view returns (bool) {
return allowed.rebalancers.contains(rebalancer);
}
/// @notice Mapping of domain to allowed rebalance recipient.
/// @dev Keys constrained to a subset of Router.domains()
function allowedRecipient(uint32 domain) external view returns (bytes32) {
return allowed.recipient[domain];
}
/// @notice Mapping of domain to allowed rebalance bridges.
/// @dev Keys constrained to a subset of Router.domains()
function allowedBridges(
uint32 domain
) external view returns (address[] memory) {
return allowed.bridges[domain].values();
}
function setRecipient(
uint32 domain,
bytes32 recipient
) external virtual onlyOwner {
// constrain to a subset of Router.domains()
_mustHaveRemoteRouter(domain);
allowed.recipient[domain] = recipient;
}
function removeRecipient(uint32 domain) external onlyOwner {
delete allowed.recipient[domain];
}
function addBridge(
uint32 domain,
ITokenBridge bridge
) external virtual onlyOwner {
// constrain to a subset of Router.domains()
_mustHaveRemoteRouter(domain);
_addBridge(domain, bridge);
}
function _addBridge(uint32 domain, ITokenBridge bridge) internal virtual {
allowed.bridges[domain].add(address(bridge));
}
function removeBridge(
uint32 domain,
ITokenBridge bridge
) external onlyOwner {
_removeBridge(domain, bridge);
}
function _removeBridge(
uint32 domain,
ITokenBridge bridge
) internal virtual {
allowed.bridges[domain].remove(address(bridge));
}
/**
* @notice Clears legacy standing token approval for a bridge.
* @custom:deprecated Despite the name this revokes rather than approves.
* `rebalance` grants exact per-call approval from the bridge quote;
* the selector is retained so existing upgrade / governance tooling
* stays compatible and can clear old max allowances.
*/
function approveTokenForBridge(
IERC20 token,
ITokenBridge bridge
) external onlyOwner {
// Revokes the allowance; it does not approve.
token.forceApprove(address(bridge), 0);
}
function addRebalancer(address rebalancer) external onlyOwner {
allowed.rebalancers.add(rebalancer);
}
function removeRebalancer(address rebalancer) external onlyOwner {
allowed.rebalancers.remove(rebalancer);
}
/**
* @notice Rebalances the collateral between router domains.
* @param domain The domain to rebalance to.
* @param collateralAmount The amount of collateral to rebalance.
* @param bridge The bridge to use for the rebalance.
* @dev The caller must be an allowed rebalancer and the bridge must be an allowed bridge for the domain.
* @dev The recipient is the enrolled router if no recipient is set for the domain.
*/
function rebalance(
uint32 domain,
uint256 collateralAmount,
ITokenBridge bridge
) external payable onlyRebalancer onlyAllowedBridge(domain, bridge) {
bytes32 recipient = _recipient(domain);
Quote[] memory quotes = bridge.quoteTransferRemote(
domain,
recipient,
collateralAmount
);
address collateralToken = token();
// charge the rebalancer any bridging fees denominated in the collateral
// token to avoid undercollateralization
uint256 collateralFees = quotes.extract(collateralToken);
if (collateralFees > collateralAmount) {
_transferFromSender(collateralFees - collateralAmount);
}
// need to handle native quote separately from collateral quote because
// token() may be address(0), in which case we need to use address(this).balance
// to move native collateral tokens across chains
uint256 nativeFees = quotes.extract(address(0));
if (nativeFees > address(this).balance) {
revert("Rebalance native fee exceeds balance");
}
// Grant only the route collateral amount for this transfer. Expected
// bridges consume the full quoted collateral allowance.
if (collateralToken != address(0)) {
IERC20(collateralToken).forceApprove(
address(bridge),
collateralFees
);
}
bridge.transferRemote{value: nativeFees}(
domain,
recipient,
collateralAmount
);
// Revoke any allowance the bridge did not consume.
if (collateralToken != address(0)) {
IERC20(collateralToken).forceApprove(address(bridge), 0);
}
emit CollateralMoved(domain, recipient, collateralAmount, msg.sender);
}
function _recipient(
uint32 domain
) internal view returns (bytes32 recipient) {
recipient = allowed.recipient[domain];
if (recipient == bytes32(0)) {
recipient = _mustHaveRemoteRouter(domain);
}
}
/// @dev This function in `EnumerableSet` was introduced in OpenZeppelin v5. We are using 4.9
/// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.3.0-rc.0/contracts/utils/structs/EnumerableSet.sol#L126
function _clear(EnumerableSet.Set storage set) private {
uint256 len = set._values.length;
for (uint256 i = 0; i < len; ++i) {
delete set._indexes[set._values[i]];
}
_unsafeSetLength(set._values, 0);
}
/// @dev A helper for `_clear`. See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/39f5a0284e7eb539354e44b76fcbb69033b22b56/contracts/utils/Arrays.sol#L466
function _unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/// @dev Constrains keys of rebalance mappings to Router.domains()
function _unenrollRemoteRouter(uint32 domain) internal override {
Router._unenrollRemoteRouter(domain);
if (!_MovableCollateralRouter_hasRebalanceRoutes(domain)) {
_clearRebalanceState(domain);
}
}
/// @dev Whether `domain` still has any route that can drive a rebalance.
/// Base tracks only classic remote routers; `CrossCollateralRouter` also
/// considers its cross-collateral routes.
function _MovableCollateralRouter_hasRebalanceRoutes(
uint32 domain
) internal view virtual returns (bool) {
return routers(domain) != bytes32(0);
}
/// @dev Clears the rebalance config (recipient + allowed bridges) for a
/// domain that no longer has any route, so a removed route cannot retain
/// rebalance authority.
function _clearRebalanceState(uint32 domain) internal {
delete allowed.recipient[domain];
_clear(allowed.bridges[domain]._inner);
}
}
@hyperlane-xyz/core/contracts/token/libs/LpCollateralRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {MovableCollateralRouter, MovableCollateralRouterStorage} from "./MovableCollateralRouter.sol";
// ============ External Imports ============
import {ERC4626Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
struct LpCollateralRouterStorage {
// MovableCollateralRouter layout
MovableCollateralRouterStorage __MOVABLE_COLLATERAL_GAP;
// ERC4626 layout
// - (ERC20 layout)
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
// @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:376
uint256[45] __ERC20_GAP;
// - (ERC4626 layout)
address _asset;
uint8 _underlyingDecimals;
// @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol:267
uint256[49] __ERC4626_GAP;
// user defined fields
uint256 lpAssets;
}
abstract contract LpCollateralRouter is
MovableCollateralRouter,
ERC4626Upgradeable
{
uint256 private lpAssets;
event Donation(address sender, uint256 amount);
function _LpCollateralRouter_initialize() internal onlyInitializing {
__ERC4626_init(IERC20Upgradeable(token()));
}
function totalAssets() public view override returns (uint256) {
return lpAssets;
}
function asset() public view override returns (address) {
return token();
}
// modeled after ERC4626Upgradeable._deposit
function _deposit(
address caller,
address receiver,
uint256 assets,
uint256 shares
) internal override {
// checks
_transferFromSender(assets);
// effects
lpAssets += assets;
// interactions
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
// modeled after ERC4626Upgradeable._withdraw
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal override {
// checks
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
_burn(owner, shares);
// effects
lpAssets -= assets;
// interactions
_transferTo(receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
// can be used to distribute rewards to LPs pro rata
function donate(uint256 amount) public payable {
// checks
_transferFromSender(amount);
// effects
lpAssets += amount;
emit Donation(msg.sender, amount);
}
}
@hyperlane-xyz/core/contracts/token/libs/TokenCollateral.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;
import {IWETH} from "../interfaces/IWETH.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @title Handles deposits and withdrawals of native token collateral.
*/
library NativeCollateral {
function _transferFromSender(uint256 _amount) internal {
require(msg.value >= _amount, "Native: amount exceeds msg.value");
}
function _transferTo(address _recipient, uint256 _amount) internal {
Address.sendValue(payable(_recipient), _amount);
}
}
/**
* @title Handles deposits and withdrawals of WETH collateral.
* @dev TokenRouters must have `token() == address(0)` to use this library.
*/
library WETHCollateral {
function _transferFromSender(IWETH token, uint256 _amount) internal {
NativeCollateral._transferFromSender(_amount);
token.deposit{value: _amount}();
}
function _transferTo(
IWETH token,
address _recipient,
uint256 _amount
) internal {
token.withdraw(_amount);
NativeCollateral._transferTo(_recipient, _amount);
}
}
/**
* @title Handles deposits and withdrawals of ERC20 collateral.
*/
library ERC20Collateral {
using SafeERC20 for IERC20;
function _transferFromSender(IERC20 token, uint256 _amount) internal {
token.safeTransferFrom(msg.sender, address(this), _amount);
}
function _transferTo(
IERC20 token,
address _recipient,
uint256 _amount
) internal {
token.safeTransfer(_recipient, _amount);
}
}
/**
* @title Handles deposits and withdrawals of ERC721 collateral.
*/
library ERC721Collateral {
function _transferFromSender(IERC721 token, uint256 _tokenId) internal {
// safeTransferFrom not used here because recipient is this contract
token.transferFrom(msg.sender, address(this), _tokenId);
}
function _transferTo(
IERC721 token,
address _recipient,
uint256 _tokenId
) internal {
token.safeTransferFrom(address(this), _recipient, _tokenId);
}
}
@hyperlane-xyz/core/contracts/libs/EnumerableMapExtended.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ External Imports ============
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
// extends EnumerableMap with uint256 => bytes32 type
// modelled after https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/utils/structs/EnumerableMap.sol
library EnumerableMapExtended {
using EnumerableMap for EnumerableMap.Bytes32ToBytes32Map;
using EnumerableSet for EnumerableSet.Bytes32Set;
struct UintToBytes32Map {
EnumerableMap.Bytes32ToBytes32Map _inner;
}
// ============ Library Functions ============
function keys(
UintToBytes32Map storage map
) internal view returns (uint256[] memory _keys) {
uint256 _length = map._inner.length();
_keys = new uint256[](_length);
for (uint256 i = 0; i < _length; i++) {
_keys[i] = uint256(map._inner._keys.at(i));
}
}
function uint32Keys(
UintToBytes32Map storage map
) internal view returns (uint32[] memory _keys) {
uint256[] memory uint256keys = keys(map);
_keys = new uint32[](uint256keys.length);
for (uint256 i = 0; i < uint256keys.length; i++) {
_keys[i] = uint32(uint256keys[i]);
}
}
function set(
UintToBytes32Map storage map,
uint256 key,
bytes32 value
) internal {
map._inner.set(bytes32(key), value);
}
function get(
UintToBytes32Map storage map,
uint256 key
) internal view returns (bytes32) {
return map._inner.get(bytes32(key));
}
function tryGet(
UintToBytes32Map storage map,
uint256 key
) internal view returns (bool, bytes32) {
return map._inner.tryGet(bytes32(key));
}
function remove(
UintToBytes32Map storage map,
uint256 key
) internal returns (bool) {
return map._inner.remove(bytes32(key));
}
function contains(
UintToBytes32Map storage map,
uint256 key
) internal view returns (bool) {
return map._inner.contains(bytes32(key));
}
function length(
UintToBytes32Map storage map
) internal view returns (uint256) {
return map._inner.length();
}
function at(
UintToBytes32Map storage map,
uint256 index
) internal view returns (uint256, bytes32) {
(bytes32 key, bytes32 value) = map._inner.at(index);
return (uint256(key), value);
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 {
using Address for address;
/**
* @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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 silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
@openzeppelin/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
@hyperlane-xyz/core/contracts/isms/aggregation/AbstractAggregationIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
// ============ Internal Imports ============
import {IInterchainSecurityModule} from "../../interfaces/IInterchainSecurityModule.sol";
import {IAggregationIsm} from "../../interfaces/isms/IAggregationIsm.sol";
import {AggregationIsmMetadata} from "../../isms/libs/AggregationIsmMetadata.sol";
import {PackageVersioned} from "../../PackageVersioned.sol";
/**
* @title AggregationIsm
* @notice Manages per-domain m-of-n ISM sets that are used to verify
* interchain messages.
*/
abstract contract AbstractAggregationIsm is IAggregationIsm, PackageVersioned {
// ============ Constants ============
// solhint-disable-next-line const-name-snakecase
uint8 public constant moduleType =
uint8(IInterchainSecurityModule.Types.AGGREGATION);
// ============ Virtual Functions ============
// ======= OVERRIDE THESE TO IMPLEMENT =======
/**
* @notice Returns the set of ISMs responsible for verifying _message
* and the number of ISMs that must verify
* @dev Can change based on the content of _message
* @param _message Hyperlane formatted interchain message
* @return modules The array of ISM addresses
* @return threshold The number of ISMs needed to verify
*/
function modulesAndThreshold(
bytes calldata _message
) public view virtual returns (address[] memory, uint8);
// ============ Public Functions ============
/**
* @notice Requires that m-of-n ISMs verify the provided interchain message.
* @param _metadata ABI encoded module metadata (see AggregationIsmMetadata.sol)
* @param _message Formatted Hyperlane message (see Message.sol).
*/
function verify(
bytes calldata _metadata,
bytes calldata _message
) public returns (bool) {
(address[] memory _isms, uint8 _threshold) = modulesAndThreshold(
_message
);
uint256 _count = _isms.length;
for (uint8 i = 0; i < _count; i++) {
if (!AggregationIsmMetadata.hasMetadata(_metadata, i)) continue;
IInterchainSecurityModule _ism = IInterchainSecurityModule(
_isms[i]
);
require(
_ism.verify(
AggregationIsmMetadata.metadataAt(_metadata, i),
_message
),
"!verify"
);
_threshold -= 1;
}
require(_threshold == 0, "!threshold");
return true;
}
}
@openzeppelin/contracts/utils/Create2.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)
pragma solidity ^0.8.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
/// @solidity memory-safe-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |-------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |-------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := keccak256(start, 85)
}
}
}
@hyperlane-xyz/core/contracts/interfaces/IThresholdAddressFactory.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
interface IThresholdAddressFactory {
function deploy(
address[] calldata _values,
uint8 _threshold
) external returns (address);
}
@hyperlane-xyz/core/contracts/isms/libs/MerkleRootMultisigIsmMetadata.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/**
* Format of metadata:
* [ 0: 32] Origin merkle tree address
* [ 32: 36] Index of message ID in merkle tree
* [ 36: 68] Signed checkpoint message ID
* [ 68:1092] Merkle proof
* [1092:1096] Signed checkpoint index (computed from proof and index)
* [1096:????] Validator signatures (length := threshold * 65)
*/
library MerkleRootMultisigIsmMetadata {
uint8 private constant ORIGIN_MERKLE_TREE_OFFSET = 0;
uint8 private constant MESSAGE_INDEX_OFFSET = 32;
uint8 private constant MESSAGE_ID_OFFSET = 36;
uint8 private constant MERKLE_PROOF_OFFSET = 68;
uint16 private constant MERKLE_PROOF_LENGTH = 32 * 32;
uint16 private constant SIGNED_INDEX_OFFSET = 1092;
uint16 private constant SIGNATURES_OFFSET = 1096;
uint8 private constant SIGNATURE_LENGTH = 65;
/**
* @notice Returns the origin merkle tree hook of the signed checkpoint as bytes32.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Origin merkle tree hook of the signed checkpoint as bytes32
*/
function originMerkleTreeHook(
bytes calldata _metadata
) internal pure returns (bytes32) {
return
bytes32(
_metadata[ORIGIN_MERKLE_TREE_OFFSET:ORIGIN_MERKLE_TREE_OFFSET +
32]
);
}
/**
* @notice Returns the index of the message being proven.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Index of the target message in the merkle tree.
*/
function messageIndex(
bytes calldata _metadata
) internal pure returns (uint32) {
return
uint32(
bytes4(_metadata[MESSAGE_INDEX_OFFSET:MESSAGE_INDEX_OFFSET + 4])
);
}
/**
* @notice Returns the index of the signed checkpoint.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Index of the signed checkpoint
*/
function signedIndex(
bytes calldata _metadata
) internal pure returns (uint32) {
return
uint32(
bytes4(_metadata[SIGNED_INDEX_OFFSET:SIGNED_INDEX_OFFSET + 4])
);
}
/**
* @notice Returns the message ID of the signed checkpoint.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Message ID of the signed checkpoint
*/
function signedMessageId(
bytes calldata _metadata
) internal pure returns (bytes32) {
return bytes32(_metadata[MESSAGE_ID_OFFSET:MESSAGE_ID_OFFSET + 32]);
}
/**
* @notice Returns the merkle proof branch of the message.
* @dev This appears to be more gas efficient than returning a calldata
* slice and using that.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Merkle proof branch of the message.
*/
function proof(
bytes calldata _metadata
) internal pure returns (bytes32[32] memory) {
return
abi.decode(
_metadata[MERKLE_PROOF_OFFSET:MERKLE_PROOF_OFFSET +
MERKLE_PROOF_LENGTH],
(bytes32[32])
);
}
/**
* @notice Returns the validator ECDSA signature at `_index`.
* @dev Assumes signatures are sorted by validator
* @dev Assumes `_metadata` encodes `threshold` signatures.
* @dev Assumes `_index` is less than `threshold`
* @param _metadata ABI encoded Multisig ISM metadata.
* @param _index The index of the signature to return.
* @return The validator ECDSA signature at `_index`.
*/
function signatureAt(
bytes calldata _metadata,
uint256 _index
) internal pure returns (bytes calldata) {
uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH);
uint256 _end = _start + SIGNATURE_LENGTH;
return _metadata[_start:_end];
}
/**
* @notice Returns the number of signatures in the metadata.
* @param _metadata ABI encoded Merkle Root Multisig ISM metadata.
* @return The number of signatures in the metadata.
*/
function signatureCount(
bytes calldata _metadata
) internal pure returns (uint256) {
uint256 signatures = _metadata.length - SIGNATURES_OFFSET;
require(
signatures % SIGNATURE_LENGTH == 0,
"Invalid signatures length"
);
return signatures / SIGNATURE_LENGTH;
}
}
@hyperlane-xyz/core/contracts/libs/CheckpointLib.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {TypeCasts} from "./TypeCasts.sol";
struct Checkpoint {
uint32 origin;
bytes32 merkleTree;
bytes32 root;
uint32 index;
bytes32 messageId;
}
library CheckpointLib {
using TypeCasts for bytes32;
/**
* @notice Returns the digest validators are expected to sign when signing checkpoints.
* @param _origin The origin domain of the checkpoint.
* @param _merkleTreeHook The address of the origin merkle tree hook as bytes32.
* @param _checkpointRoot The root of the checkpoint.
* @param _checkpointIndex The index of the checkpoint.
* @param _messageId The message ID of the checkpoint.
* @dev Message ID must match leaf content of checkpoint root at index.
* @return The digest of the checkpoint.
*/
function digest(
uint32 _origin,
bytes32 _merkleTreeHook,
bytes32 _checkpointRoot,
uint32 _checkpointIndex,
bytes32 _messageId
) internal pure returns (bytes32) {
bytes32 _domainHash = domainHash(_origin, _merkleTreeHook);
return
ECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(
_domainHash,
_checkpointRoot,
_checkpointIndex,
_messageId
)
)
);
}
/**
* @notice Returns the digest validators are expected to sign when signing checkpoints.
* @param checkpoint The checkpoint (struct) to hash.
* @return The digest of the checkpoint.
*/
function digest(
Checkpoint memory checkpoint
) internal pure returns (bytes32) {
return
digest(
checkpoint.origin,
checkpoint.merkleTree,
checkpoint.root,
checkpoint.index,
checkpoint.messageId
);
}
function merkleTreeAddress(
Checkpoint calldata checkpoint
) internal pure returns (address) {
return checkpoint.merkleTree.bytes32ToAddress();
}
/**
* @notice Returns the domain hash that validators are expected to use
* when signing checkpoints.
* @param _origin The origin domain of the checkpoint.
* @param _merkleTreeHook The address of the origin merkle tree as bytes32.
* @return The domain hash.
*/
function domainHash(
uint32 _origin,
bytes32 _merkleTreeHook
) internal pure returns (bytes32) {
// Including the origin merkle tree address in the signature allows the slashing
// protocol to enroll multiple trees. Otherwise, a valid signature for
// tree A would be indistinguishable from a fraudulent signature for tree B.
// The slashing protocol should slash if validators sign attestations for
// anything other than a whitelisted tree.
return
keccak256(abi.encodePacked(_origin, _merkleTreeHook, "HYPERLANE"));
}
}
@hyperlane-xyz/core/contracts/isms/libs/MessageIdMultisigIsmMetadata.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/**
* Format of metadata:
* [ 0: 32] Origin merkle tree address
* [ 32: 64] Signed checkpoint root
* [ 64: 68] Signed checkpoint index
* [ 68:????] Validator signatures (length := threshold * 65)
*/
library MessageIdMultisigIsmMetadata {
uint8 private constant ORIGIN_MERKLE_TREE_OFFSET = 0;
uint8 private constant MERKLE_ROOT_OFFSET = 32;
uint8 private constant MERKLE_INDEX_OFFSET = 64;
uint8 private constant SIGNATURES_OFFSET = 68;
uint8 private constant SIGNATURE_LENGTH = 65;
/**
* @notice Returns the origin merkle tree hook of the signed checkpoint as bytes32.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Origin merkle tree hook of the signed checkpoint as bytes32
*/
function originMerkleTreeHook(
bytes calldata _metadata
) internal pure returns (bytes32) {
return
bytes32(
_metadata[ORIGIN_MERKLE_TREE_OFFSET:ORIGIN_MERKLE_TREE_OFFSET +
32]
);
}
/**
* @notice Returns the merkle root of the signed checkpoint.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Merkle root of the signed checkpoint
*/
function root(bytes calldata _metadata) internal pure returns (bytes32) {
return bytes32(_metadata[MERKLE_ROOT_OFFSET:MERKLE_ROOT_OFFSET + 32]);
}
/**
* @notice Returns the merkle index of the signed checkpoint.
* @param _metadata ABI encoded Multisig ISM metadata.
* @return Merkle index of the signed checkpoint
*/
function index(bytes calldata _metadata) internal pure returns (uint32) {
return
uint32(
bytes4(_metadata[MERKLE_INDEX_OFFSET:MERKLE_INDEX_OFFSET + 4])
);
}
/**
* @notice Returns the validator ECDSA signature at `_index`.
* @dev Assumes signatures are sorted by validator
* @dev Assumes `_metadata` encodes `threshold` signatures.
* @dev Assumes `_index` is less than `threshold`
* @param _metadata ABI encoded Multisig ISM metadata.
* @param _index The index of the signature to return.
* @return The validator ECDSA signature at `_index`.
*/
function signatureAt(
bytes calldata _metadata,
uint256 _index
) internal pure returns (bytes calldata) {
uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH);
uint256 _end = _start + SIGNATURE_LENGTH;
return _metadata[_start:_end];
}
/**
* @notice Returns the number of signatures in the metadata.
* @param _metadata ABI encoded MessageId Multisig ISM metadata.
* @return The number of signatures in the metadata.
*/
function signatureCount(
bytes calldata _metadata
) internal pure returns (uint256) {
uint256 signatures = _metadata.length - SIGNATURES_OFFSET;
require(
signatures % SIGNATURE_LENGTH == 0,
"Invalid signatures length"
);
return signatures / SIGNATURE_LENGTH;
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
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.
/// @solidity memory-safe-assembly
assembly {
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);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
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[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
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.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// 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);
}
// 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);
}
return (signer, RecoverError.NoError);
}
/**
* @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) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
@hyperlane-xyz/core/contracts/interfaces/isms/IMultisigIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import {IInterchainSecurityModule} from "../IInterchainSecurityModule.sol";
interface IMultisigIsm is IInterchainSecurityModule {
/**
* @notice Returns the set of validators responsible for verifying _message
* and the number of signatures required
* @dev Can change based on the content of _message
* @dev Signatures provided to `verify` must be consistent with validator ordering
* @param _message Hyperlane formatted interchain message
* @return validators The array of validator addresses
* @return threshold The number of validator signatures needed
*/
function validatorsAndThreshold(
bytes calldata _message
) external view returns (address[] memory validators, uint8 threshold);
}
@hyperlane-xyz/core/contracts/client/GasRouter.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/*@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@ HYPERLANE @@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@ @@@@@@@@*/
// ============ Internal Imports ============
import {Router} from "./Router.sol";
import {EnumerableMapExtended} from "../libs/EnumerableMapExtended.sol";
import {StandardHookMetadata} from "../hooks/libs/StandardHookMetadata.sol";
abstract contract GasRouter is Router {
using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;
event GasSet(uint32 domain, uint256 gas);
// ============ Mutable Storage ============
mapping(uint32 destinationDomain => uint256 gasLimit) public destinationGas;
struct GasRouterConfig {
uint32 domain;
uint256 gas;
}
constructor(address _mailbox) Router(_mailbox) {}
/**
* @notice Sets the gas amount dispatched for each configured domain.
* @param gasConfigs The array of GasRouterConfig structs
*/
function setDestinationGas(
GasRouterConfig[] calldata gasConfigs
) external onlyOwner {
for (uint256 i = 0; i < gasConfigs.length; i += 1) {
_setDestinationGas(gasConfigs[i].domain, gasConfigs[i].gas);
}
}
/**
* @notice Sets the gas amount dispatched for each configured domain.
* @param domain The destination domain ID
* @param gas The gas limit
*/
function setDestinationGas(uint32 domain, uint256 gas) external onlyOwner {
_setDestinationGas(domain, gas);
}
/**
* @notice Returns the gas payment required to dispatch a message to the given domain's router.
* @param _destinationDomain The domain of the router.
* @return _gasPayment Payment computed by the registered InterchainGasPaymaster.
*/
function quoteGasPayment(
uint32 _destinationDomain
) public view virtual returns (uint256) {
return
_Router_quoteDispatch(
_destinationDomain,
"",
_GasRouter_hookMetadata(_destinationDomain),
address(hook)
);
}
function _GasRouter_hookMetadata(
uint32 _destination
) internal view returns (bytes memory) {
return
StandardHookMetadata.overrideGasLimit(destinationGas[_destination]);
}
function _setDestinationGas(uint32 domain, uint256 gas) internal virtual {
require(
_routers.contains(uint256(domain)),
_domainNotFoundError(domain)
);
destinationGas[domain] = gas;
emit GasSet(domain, gas);
}
}
@hyperlane-xyz/core/contracts/token/libs/Quotes.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;
import {Quote} from "../../interfaces/ITokenBridge.sol";
library Quotes {
function extract(
Quote[] memory quotes,
address token
) internal pure returns (uint256 sum) {
sum = 0;
for (uint256 i = 0; i < quotes.length; i++) {
if (quotes[i].token == token) {
sum += quotes[i].amount;
}
}
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/utils/structs/EnumerableMap.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableMap.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.
pragma solidity ^0.8.0;
import "./EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* The following map types are supported:
*
* - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
* - `address -> uint256` (`AddressToUintMap`) since v4.6.0
* - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
* - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
* - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableMap.
* ====
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Bytes32ToBytes32Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
Bytes32ToBytes32Map storage map,
bytes32 key,
string memory errorMessage
) internal view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || contains(map, key), errorMessage);
return value;
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {
return map._keys.values();
}
// UintToUintMap
struct UintToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {
return set(map._inner, bytes32(key), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(key)));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToUintMap storage map, uint256 key, string memory errorMessage) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(key), errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(UintToUintMap storage map) internal view returns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintToAddressMap
struct UintToAddressMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(get(map._inner, bytes32(key), errorMessage))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressToUintMap
struct AddressToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(AddressToUintMap storage map) internal view returns (address[] memory) {
bytes32[] memory store = keys(map._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// Bytes32ToUintMap
struct Bytes32ToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {
return set(map._inner, key, bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {
return remove(map._inner, key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {
return contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(Bytes32ToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (key, uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, key);
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {
return uint256(get(map._inner, key));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
Bytes32ToUintMap storage map,
bytes32 key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(get(map._inner, key, errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) {
bytes32[] memory store = keys(map._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../utils/SafeERC20Upgradeable.sol";
import "../../../interfaces/IERC4626Upgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
* corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
* decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
* determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
* (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
* donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
* expensive than it is profitable. More details about the underlying math can be found
* xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*
* _Available since v4.7._
*/
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {
using MathUpgradeable for uint256;
IERC20Upgradeable private _asset;
uint8 private _underlyingDecimals;
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
*/
function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {
__ERC4626_init_unchained(asset_);
}
function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
_underlyingDecimals = success ? assetDecimals : 18;
_asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20Upgradeable asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector)
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual override returns (address) {
return address(_asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual override returns (uint256) {
return _asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual override returns (uint256) {
return _convertToShares(assets, MathUpgradeable.Rounding.Down);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual override returns (uint256) {
return _convertToAssets(shares, MathUpgradeable.Rounding.Down);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual override returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual override returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual override returns (uint256) {
return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual override returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
return _convertToShares(assets, MathUpgradeable.Rounding.Down);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual override returns (uint256) {
return _convertToAssets(shares, MathUpgradeable.Rounding.Up);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
return _convertToShares(assets, MathUpgradeable.Rounding.Up);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
return _convertToAssets(shares, MathUpgradeable.Rounding.Down);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}.
*
* As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
* In this case, the shares will be minted without requiring any assets to be deposited.
*/
function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
require(shares <= maxMint(receiver), "ERC4626: mint more than max");
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) {
require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) {
require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@hyperlane-xyz/core/contracts/client/Router.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol";
import {IPostDispatchHook} from "../interfaces/hooks/IPostDispatchHook.sol";
import {MailboxClient} from "./MailboxClient.sol";
import {EnumerableMapExtended} from "../libs/EnumerableMapExtended.sol";
// ============ External Imports ============
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
abstract contract Router is MailboxClient, IMessageRecipient {
using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;
using Strings for uint32;
// ============ Mutable Storage ============
/// @dev Mapping of domain => router. For a given domain we have one router we send/receive messages from.
EnumerableMapExtended.UintToBytes32Map internal _routers;
uint256[48] private __GAP; // gap for upgrade safety
constructor(address _mailbox) MailboxClient(_mailbox) {}
// ============ External functions ============
function domains() external view returns (uint32[] memory) {
return _routers.uint32Keys();
}
/**
* @notice Returns the address of the Router contract for the given domain
* @param _domain The remote domain ID.
* @dev Returns 0 address if no router is enrolled for the given domain
* @return router The address of the Router contract for the given domain
*/
function routers(uint32 _domain) public view virtual returns (bytes32) {
(, bytes32 _router) = _routers.tryGet(_domain);
return _router;
}
/**
* @notice Unregister the domain
* @param _domain The domain of the remote Application Router
*/
function unenrollRemoteRouter(uint32 _domain) external virtual onlyOwner {
_unenrollRemoteRouter(_domain);
}
/**
* @notice Register the address of a Router contract for the same Application on a remote chain
* @param _domain The domain of the remote Application Router
* @param _router The address of the remote Application Router
*/
function enrollRemoteRouter(
uint32 _domain,
bytes32 _router
) external virtual onlyOwner {
_enrollRemoteRouter(_domain, _router);
}
/**
* @notice Batch version of `enrollRemoteRouter`
* @param _domains The domains of the remote Application Routers
* @param _addresses The addresses of the remote Application Routers
*/
function enrollRemoteRouters(
uint32[] calldata _domains,
bytes32[] calldata _addresses
) external virtual onlyOwner {
require(_domains.length == _addresses.length, "!length");
uint256 length = _domains.length;
for (uint256 i = 0; i < length; i += 1) {
_enrollRemoteRouter(_domains[i], _addresses[i]);
}
}
/**
* @notice Batch version of `unenrollRemoteRouter`
* @param _domains The domains of the remote Application Routers
*/
function unenrollRemoteRouters(
uint32[] calldata _domains
) external virtual onlyOwner {
uint256 length = _domains.length;
for (uint256 i = 0; i < length; i += 1) {
_unenrollRemoteRouter(_domains[i]);
}
}
/**
* @notice Handles an incoming message
* @param _origin The origin domain
* @param _sender The sender address
* @param _message The message
*/
// solhint-disable-next-line hyperlane/no-virtual-override
function handle(
uint32 _origin,
bytes32 _sender,
bytes calldata _message
) external payable virtual override onlyMailbox {
bytes32 _router = _mustHaveRemoteRouter(_origin);
require(_router == _sender, "Enrolled router does not match sender");
_handle(_origin, _sender, _message);
}
// ============ Virtual functions ============
function _handle(
uint32 _origin,
bytes32 _sender,
bytes calldata _message
) internal virtual;
// ============ Internal functions ============
/**
* @notice Set the router for a given domain
* @param _domain The domain
* @param _address The new router
*/
function _enrollRemoteRouter(
uint32 _domain,
bytes32 _address
) internal virtual {
_routers.set(_domain, _address);
}
/**
* @notice Remove the router for a given domain
* @param _domain The domain
*/
function _unenrollRemoteRouter(uint32 _domain) internal virtual {
require(_routers.remove(_domain), _domainNotFoundError(_domain));
}
/**
* @notice Return true if the given domain / router is the address of a remote Application Router
* @param _domain The domain of the potential remote Application Router
* @param _address The address of the potential remote Application Router
*/
function _isRemoteRouter(
uint32 _domain,
bytes32 _address
) internal view returns (bool) {
return routers(_domain) == _address;
}
/**
* @notice Assert that the given domain has an Application Router registered and return its address
* @param _domain The domain of the chain for which to get the Application Router
* @return _router The address of the remote Application Router on _domain
*/
function _mustHaveRemoteRouter(
uint32 _domain
) internal view returns (bytes32) {
(bool contained, bytes32 _router) = _routers.tryGet(_domain);
if (contained) {
return _router;
}
revert(_domainNotFoundError(_domain));
}
function _domainNotFoundError(
uint32 _domain
) internal pure returns (string memory) {
return
string.concat(
"No router enrolled for domain: ",
_domain.toString()
);
}
function _Router_dispatch(
uint32 _destinationDomain,
uint256 _value,
bytes memory _messageBody
) internal returns (bytes32) {
return
_Router_dispatch(
_destinationDomain,
_value,
_messageBody,
"",
address(hook)
);
}
function _Router_dispatch(
uint32 _destinationDomain,
uint256 _value,
bytes memory _messageBody,
bytes memory _hookMetadata,
address _hook
) internal returns (bytes32) {
bytes32 _router = _mustHaveRemoteRouter(_destinationDomain);
return
mailbox.dispatch{value: _value}(
_destinationDomain,
_router,
_messageBody,
_hookMetadata,
IPostDispatchHook(_hook)
);
}
function _Router_quoteDispatch(
uint32 _destinationDomain,
bytes memory _messageBody
) internal view returns (uint256) {
return
_Router_quoteDispatch(
_destinationDomain,
_messageBody,
"",
address(hook)
);
}
function _Router_quoteDispatch(
uint32 _destinationDomain,
bytes memory _messageBody,
bytes memory _hookMetadata,
address _hook
) internal view returns (uint256) {
bytes32 _router = _mustHaveRemoteRouter(_destinationDomain);
return
mailbox.quoteDispatch(
_destinationDomain,
_router,
_messageBody,
_hookMetadata,
IPostDispatchHook(_hook)
);
}
}
@hyperlane-xyz/core/contracts/token/interfaces/IWETH.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.22;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@hyperlane-xyz/core/contracts/interfaces/isms/IAggregationIsm.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import {IInterchainSecurityModule} from "../IInterchainSecurityModule.sol";
interface IAggregationIsm is IInterchainSecurityModule {
/**
* @notice Returns the set of modules responsible for verifying _message
* and the number of modules that must verify
* @dev Can change based on the content of _message
* @param _message Hyperlane formatted interchain message
* @return modules The array of ISM addresses
* @return threshold The number of modules needed to verify
*/
function modulesAndThreshold(
bytes calldata _message
) external view returns (address[] memory modules, uint8 threshold);
}
@hyperlane-xyz/core/contracts/isms/libs/AggregationIsmMetadata.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.0;
/**
* Format of metadata:
*
* [????:????] Metadata start/end uint32 ranges, packed as uint64
* [????:????] ISM metadata, packed encoding
*/
library AggregationIsmMetadata {
uint256 private constant RANGE_SIZE = 4;
/**
* @notice Returns whether or not metadata was provided for the ISM at
* `_index`
* @dev Callers must ensure _index is less than the number of metadatas
* provided
* @param _metadata Encoded Aggregation ISM metadata
* @param _index The index of the ISM to check for metadata for
* @return Whether or not metadata was provided for the ISM at `_index`
*/
function hasMetadata(
bytes calldata _metadata,
uint8 _index
) internal pure returns (bool) {
(uint32 _start, ) = _metadataRange(_metadata, _index);
return _start > 0;
}
/**
* @notice Returns the metadata provided for the ISM at `_index`
* @dev Callers must ensure _index is less than the number of metadatas
* provided
* @dev Callers must ensure `hasMetadata(_metadata, _index)`
* @param _metadata Encoded Aggregation ISM metadata
* @param _index The index of the ISM to return metadata for
* @return The metadata provided for the ISM at `_index`
*/
function metadataAt(
bytes calldata _metadata,
uint8 _index
) internal pure returns (bytes calldata) {
(uint32 _start, uint32 _end) = _metadataRange(_metadata, _index);
return _metadata[_start:_end];
}
/**
* @notice Returns the range of the metadata provided for the ISM at
* `_index`, or zeroes if not provided
* @dev Callers must ensure _index is less than the number of metadatas
* provided
* @param _metadata Encoded Aggregation ISM metadata
* @param _index The index of the ISM to return metadata range for
* @return The range of the metadata provided for the ISM at `_index`, or
* zeroes if not provided
*/
function _metadataRange(
bytes calldata _metadata,
uint8 _index
) private pure returns (uint32, uint32) {
uint256 _start = (uint32(_index) * RANGE_SIZE * 2);
uint256 _mid = _start + RANGE_SIZE;
uint256 _end = _mid + RANGE_SIZE;
return (
uint32(bytes4(_metadata[_start:_mid])),
uint32(bytes4(_metadata[_mid:_end]))
);
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @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(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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 silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
@openzeppelin/contracts-upgradeable/interfaces/IERC4626Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20Upgradeable.sol";
import "../token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* _Available since v4.7._
*/
interface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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[EIP 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);
}
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Contract ABI
[
{
"inputs": [
{
"internalType": "uint8",
"name": "__decimals",
"type": "uint8"
},
{
"internalType": "uint256",
"name": "_scaleNumerator",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_scaleDenominator",
"type": "uint256"
},
{
"internalType": "address",
"name": "_mailbox",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeHook",
"type": "address"
}
],
"name": "FeeHookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeRecipient",
"type": "address"
}
],
"name": "FeeRecipientSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "GasSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "HookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint8",
"name": "version",
"type": "uint8"
}
],
"name": "Initialized",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_ism",
"type": "address"
}
],
"name": "IsmSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "previousOwner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "origin",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "ReceivedTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "destination",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "SentTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [],
"name": "PACKAGE_VERSION",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "decimals",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "subtractedValue",
"type": "uint256"
}
],
"name": "decreaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "destinationDomain",
"type": "uint32"
}
],
"name": "destinationGas",
"outputs": [
{
"internalType": "uint256",
"name": "gasLimit",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "domains",
"outputs": [
{
"internalType": "uint32[]",
"name": "",
"type": "uint32[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_router",
"type": "bytes32"
}
],
"name": "enrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
},
{
"internalType": "bytes32[]",
"name": "_addresses",
"type": "bytes32[]"
}
],
"name": "enrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "feeHook",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeRecipient",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeToken",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_origin",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_sender",
"type": "bytes32"
},
{
"internalType": "bytes",
"name": "_message",
"type": "bytes"
}
],
"name": "handle",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [],
"name": "hook",
"outputs": [
{
"internalType": "contract IPostDispatchHook",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "addedValue",
"type": "uint256"
}
],
"name": "increaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_totalSupply",
"type": "uint256"
},
{
"internalType": "string",
"name": "_name",
"type": "string"
},
{
"internalType": "string",
"name": "_symbol",
"type": "string"
},
{
"internalType": "address",
"name": "_hook",
"type": "address"
},
{
"internalType": "address",
"name": "_interchainSecurityModule",
"type": "address"
},
{
"internalType": "address",
"name": "_owner",
"type": "address"
}
],
"name": "initialize",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "interchainSecurityModule",
"outputs": [
{
"internalType": "contract IInterchainSecurityModule",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "localDomain",
"outputs": [
{
"internalType": "uint32",
"name": "",
"type": "uint32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "mailbox",
"outputs": [
{
"internalType": "contract IMailbox",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destinationDomain",
"type": "uint32"
}
],
"name": "quoteGasPayment",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "quoteTransferRemote",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "token",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"internalType": "struct Quote[]",
"name": "quotes",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "renounceOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "routers",
"outputs": [
{
"internalType": "bytes32",
"name": "",
"type": "bytes32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleDenominator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleNumerator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"components": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"internalType": "struct GasRouter.GasRouterConfig[]",
"name": "gasConfigs",
"type": "tuple[]"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_feeHook",
"type": "address"
}
],
"name": "setFeeHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "recipient",
"type": "address"
}
],
"name": "setFeeRecipient",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "setHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_module",
"type": "address"
}
],
"name": "setInterchainSecurityModule",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "symbol",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "token",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "from",
"type": "address"
},
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "transferRemote",
"outputs": [
{
"internalType": "bytes32",
"name": "messageId",
"type": "bytes32"
}
],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "unenrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
}
],
"name": "unenrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]Raw Contract Data · JSON
{
"id": "0x5c2e5dec72280f2ad5bb7f9befc0ef877aedf62d",
"contract": "0x5c2e5dec72280f2ad5bb7f9befc0ef877aedf62d",
"name": "EVM Contract",
"type": "contract",
"bytecode": "0x608080604052600436101561001357600080fd5b600090813560e01c90816306fdde0314611e8757508063095ea7b314611e605780630e72cc0614611dcd57806318160ddd14611daf5780631c2eaac014611d7457806323b872dd14611cb55780632ead72f614611c81578063313ce56714611c435780633950935114611bf25780633dfd387314611b5f578063440df4f414611a0957806346904840146119d357806349d462ef146119a557806356d5d47514611757578063647846a51461172a57806370a08231146116f1578063715018a61461169457806371a15b381461161a578063775313a1146115e55780637f5a7c7b146115bc57806381b4e8b4146111b25780638bd90b821461104e5780638d3638f41461100d5780638da5cb5b14610fe457806392c1845414610efa57806393c4484714610eb257806395d89b4114610ddd5780639f0b765914610da2578063a457c2d714610cfd578063a9059cbb14610ccb578063b1bd643614610c19578063b49c53a714610beb578063d5438eae14610ba6578063dd62ed3e14610b51578063de523cf314610b28578063e74b981b14610a55578063e80a7c79146104b0578063e9198bf9146103c0578063efae508a14610396578063f11f446114610360578063f2ed8c53146102a8578063f2fde38b146102175763fc0c546a146101fa57600080fd5b346102145780600319360112610214576020604051308152f35b80fd5b503461021457602036600319011261021457610231611f5f565b610239612330565b6001600160a01b0381161561025457610251906125f1565b80f35b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b5034610214576020366003190112610214576103586102c5611f8b565b63ffffffff8116835260fc60205260408320546020936103376076604051936102ee8886612026565b838552604051948591600160f01b8a84015285602284015260428301523360601b6062830152610326815180928b8686019101611f17565b81010301601f198101845283612026565b60018060a01b036097541692604051916103518784612026565b8252612a35565b604051908152f35b503461021457806003193601126102145760008051602061313f833981519152546040516001600160a01b039091168152602090f35b5034610214576020366003190112610214576102516103b3611f8b565b6103bb612330565b61263a565b5034610214576040366003190112610214576004356001600160401b0381116104ac576103f1903690600401611f9e565b6024929192356001600160401b0381116104a857610413903690600401611f9e565b909161041d612330565b81810361047957835b818110610431578480f35b61045961044761044283858a612189565b6121af565b610452838688612189565b35906128c2565b600181018091111561042657634e487b7160e01b85526011600452602485fd5b60405162461bcd60e51b8152602060048201526007602482015266042d8cadccee8d60cb1b6044820152606490fd5b8280fd5b5080fd5b50346102145760c0366003190112610214576024356001600160401b0381116104ac576104e1903690600401612062565b6044356001600160401b0381116104a857610500903690600401612062565b6064356001600160a01b038116808203610a50576084356001600160a01b03811692909190838303610a505760a435946001600160a01b0386168603610a505787549660ff8860081c161597888099610a43575b8015610a2c575b156109d05760ff1981166001178a55886109bf575b5061058a60ff8a5460081c16610585816128e5565b6128e5565b8051906001600160401b0382116109ab5781906105a86036546120a9565b601f8111610935575b50602090601f83116001146108c4578b926108b9575b50508160011b916000199060031b1c1916176036555b8051906001600160401b0382116108a5576105f96037546120a9565b601f8111610839575b5060209089601f84116001146107795794610720989794847fc47cbcc588c67679e52261c45cc315e56562f8d0ccaba16facb9093ff949879998957f4eab7b127c764308788622363ad3e9532de3dfba7845bd4f84c125a22544255a95602099958a969261076e575b50508160011b916000199060031b1c1916176037555b61068d60043533612945565b6106aa60ff8d5460081c166106a1816128e5565b610585816128e5565b6106b3336125f1565b3b15801590610766575b6106c6906120e3565b6106ce612330565b609780546001600160a01b03191682179055604051908152a13b1580159061075e575b6106fa906120e3565b610702612330565b609880546001600160a01b03191682179055604051908152a16125f1565b6107275780f35b61ff001981541681557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b5080156106f1565b5080156106bd565b01519050388061066b565b5060378a5260008051602061315f8339815191529190601f1984168b5b8181106108215750946001857f4eab7b127c764308788622363ad3e9532de3dfba7845bd4f84c125a22544255a9560209994958a967fc47cbcc588c67679e52261c45cc315e56562f8d0ccaba16facb9093ff94987999c996107209f9e9b10610808575b505050811b01603755610681565b015160001960f88460031b161c191690553880806107fa565b92936020600181928786015181550195019301610796565b60378a52601f830160051c60008051602061315f83398151915201906020841061088f575b601f0160051c60008051602061315f83398151915201905b8181106108835750610602565b60008155600101610876565b60008051602061315f833981519152915061085e565b634e487b7160e01b89526041600452602489fd5b0151905038806105c7565b60368c5260008051602061311f8339815191529250601f1984168c5b81811061091d5750908460019594939210610904575b505050811b016036556105dd565b015160001960f88460031b161c191690553880806108f6565b929360206001819287860151815501950193016108e0565b90915060368b52601f830160051c60008051602061311f833981519152019060208410610995575b90601f8493920160051c60008051602061311f83398151915201905b81811061098657506105b1565b60008155849350600101610979565b60008051602061311f833981519152915061095d565b634e487b7160e01b8a52604160045260248afd5b61ffff191661010117895538610570565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b15801561055b5750600160ff82161461055b565b50600160ff821610610554565b600080fd5b503461021457602036600319011261021457610a6f611f5f565b610a77612330565b6001600160a01b0316308114610ae3576020817fbf9a9534339a9d6b81696e05dcfb614b7dc518a31d48be3cfb757988381fb323926001600160601b0360a01b60008051602061317f83398151915254161760008051602061317f83398151915255604051908152a180f35b60405162461bcd60e51b815260206004820152601c60248201527f46656520726563697069656e742063616e6e6f742062652073656c66000000006044820152606490fd5b50346102145780600319360112610214576098546040516001600160a01b039091168152602090f35b5034610214576040366003190112610214576040610b6d611f5f565b91610b76611f75565b9260018060a01b031681526034602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102145780600319360112610214576040517f0000000000000000000000008ecd10fd6d7822ef16418689f92e5e1d5f144bd96001600160a01b03168152602090f35b503461021457604036600319011261021457610251610c08611f8b565b610c10612330565b602435906128c2565b503461021457602036600319011261021457600435906001600160401b0382116102145736602383011215610214578160040135916001600160401b0383116104ac576024810190602436918560061b0101116104ac57610c78612330565b815b838110610c85578280f35b610cab610c96610442838786612218565b6020610ca3848887612218565b013590612537565b6001810180911115610c7a57634e487b7160e01b83526011600452602483fd5b503461021457604036600319011261021457610cf2610ce8611f5f565b6024359033612388565b602060405160018152f35b503461021457604036600319011261021457610d17611f5f565b60406024359233815260346020522060018060a01b03821660005260205260406000205491808310610d4f57610cf292039033612228565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608490fd5b503461021457806003193601126102145760206040517f00000000000000000000000000000000000000000000000000000000000000018152f35b5034610214578060031936011261021457604051908060375490610e00826120a9565b8085529160018116908115610e8b5750600114610e40575b610e3c84610e2881860382612026565b604051918291602083526020830190611f3a565b0390f35b6037815260008051602061315f833981519152939250905b808210610e7157509091508101602001610e2882610e18565b919260018160209254838588010152019101909291610e58565b60ff191660208087019190915292151560051b85019092019250610e289150839050610e18565b5034610214578060031936011261021457610e3c6040805190610ed58183612026565b6006825265031322e312e360d41b602083015251918291602083526020830190611f3a565b503461021457602036600319011261021457610f14611f5f565b610f1c612330565b6001600160a01b031680610f87575b6020817fd6e2f80c31feccfd7c896d69ad9963871021131ff84f2a9828b40bad60dd8cb4926001600160601b0360a01b60008051602061313f83398151915254161760008051602061313f83398151915255604051908152a180f35b30610f2b5760405162461bcd60e51b815260206004820152602a60248201527f546f6b656e526f757465723a2066656520686f6f6b207265717569726573204560448201526929219918103a37b5b2b760b11b6064820152608490fd5b50346102145780600319360112610214576065546040516001600160a01b039091168152602090f35b5034610214578060031936011261021457602060405163ffffffff7f0000000000000000000000000000000000000000000000000000000001352889168152f35b50346102145761105d36611fce565b611068939193612162565b9360405193611078608086612026565b60038552606095845b8781106111895750928282856110a06110de978580986110d69861266b565b604051916110ad83611ff5565b6001600160a01b0316825260208201526110c6896121d7565b526110d0886121d7565b506126e9565b91905061213f565b604051906110eb82611ff5565b30825260208201526110fc836121e4565b52611106826121e4565b5060405161111381611ff5565b308152816020820152611125836121f4565b5261112f826121f4565b50604051918291602083016020845282518091526020604085019301915b81811061115b575050500390f35b825180516001600160a01b03168552602090810151818601528695506040909401939092019160010161114d565b60209060409796975161119b81611ff5565b888152888382015282828901015201959495611081565b506111bc36611fce565b60008051602061313f833981519152546001600160a01b0316936111de612162565b946111ea8385876126e9565b90916111f6828661213f565b9350806114ab575b50331561145c5733600052603360205260406000205483811061140c57839033600052603360205203604060002055826035540360355560006040518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60203392a3806113fc575b50600091905030156113cc575050611310602093946112cd34935b7f0000000000000000000000000000000000000000000000000000000000000001907f000000000000000000000000000000000000000000000000000000000000000190612d58565b936112d88582612b59565b946040519081527fd229aacb94204188fe8042965fa6b269c62dc5818b21238779ab64bdd17efeec8763ffffffff8a1692a385612b77565b9360018060a01b036097541690611346611329826125a9565b92604051978896879586956242e0f760e61b8752600487016129e9565b03917f0000000000000000000000008ecd10fd6d7822ef16418689f92e5e1d5f144bd96001600160a01b03165af180156113c05760009061138d575b602090604051908152f35b506020813d6020116113b8575b816113a760209383612026565b81010312610a505760209051611382565b3d915061139a565b6040513d6000823e3d90fd5b3403903482116113e85750602093946112cd6113109293611284565b634e487b7160e01b81526011600452602490fd5b61140591612945565b3880611269565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608490fd5b6114b73086888a61266b565b6114f16040516323b872dd60e01b6020820152336024820152306044820152826064820152606481526114eb608482612026565b30612e4c565b60008060405192602084019063095ea7b360e01b8252856024860152604485015260448452611521606485612026565b83519082305af1611530612f38565b8161158d575b5080611583575b15611549575b506111fe565b6114eb61157c926040519063095ea7b360e01b6020830152602482015260006044820152604481526114eb606482612026565b3880611543565b50303b151561153d565b80518015925082156115a2575b505038611536565b6115b59250602080918301019101612e34565b388061159a565b50346102145780600319360112610214576097546040516001600160a01b039091168152602090f35b503461021457602036600319011261021457604060209163ffffffff611609611f8b565b16815260fc83522054604051908152f35b5034610214576020366003190112610214576004356001600160401b0381116104ac5761164b903690600401611f9e565b611656929192612330565b815b818110611663578280f35b6116746103bb610442838588612189565b600181018091111561165857634e487b7160e01b83526011600452602483fd5b50346102145780600319360112610214576116ad612330565b606580546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b5034610214576020366003190112610214576020906040906001600160a01b03611719611f5f565b168152603383522054604051908152f35b50346102145780600319360112610214576020611745612162565b6040516001600160a01b039091168152f35b5060603660031901126102145761176c611f8b565b906044356001600160401b0381116104ac57366023820112156104ac578060040135906001600160401b0382116104a857602481019136602482840101116119a1577f0000000000000000000000008ecd10fd6d7822ef16418689f92e5e1d5f144bd96001600160a01b03163303611952576024356117ea866125a9565b036118ff576020928184116118fb57359350604011610a5057604401359282907fba20947a325f450d232530e5f5fce293e7963499d5309a07cee84a269f2f15a68363ffffffff604051938885521692a36001600160a01b0382116118ab575061189a6118a9927f0000000000000000000000000000000000000000000000000000000000000001907f000000000000000000000000000000000000000000000000000000000000000190612d58565b906001600160a01b0316612945565b005b6084906040519062461bcd60e51b825260048201526024808201527f5479706543617374733a2062797465733332546f41646472657373206f766572604482015263666c6f7760e01b6064820152fd5b8480fd5b60405162461bcd60e51b815260206004820152602560248201527f456e726f6c6c656420726f7574657220646f6573206e6f74206d61746368207360448201526432b73232b960d91b6064820152608490fd5b60405162461bcd60e51b815260206004820152602160248201527f4d61696c626f78436c69656e743a2073656e646572206e6f74206d61696c626f6044820152600f60fb1b6064820152608490fd5b8380fd5b5034610214576040366003190112610214576102516119c2611f8b565b6119ca612330565b60243590612537565b503461021457806003193601126102145760008051602061317f833981519152546040516001600160a01b039091168152602090f35b503461021457806003193601126102145760c95490611a27826121c0565b91611a356040519384612026565b808352601f19611a44826121c0565b0136602085013760c954825b828110611b06575050508151611a7e611a68826121c0565b91611a766040519384612026565b8083526121c0565b602082019290601f1901368437805b8451811015611abb578063ffffffff611aa860019388612204565b5116611ab48286612204565b5201611a8d565b50925090604051928392602084019060208552518091526040840192915b818110611ae7575050500390f35b825163ffffffff16845285945060209384019390920191600101611ad9565b81811015611b4b5760c984527f66be4f155c5ef2ebd3772b228f2f00681e4ed5826cdb3b1943cc11ad15ad1d2881015460019190611b448288612204565b5201611a50565b634e487b7160e01b84526032600452602484fd5b5034610214576020366003190112610214577f4eab7b127c764308788622363ad3e9532de3dfba7845bd4f84c125a22544255a6020611b9c611f5f565b803b15801590611be1575b611bb0906120e3565b611bb8612330565b609780546001600160a01b0319166001600160a01b03929092169182179055604051908152a180f35b506001600160a01b03811615611ba7565b503461021457604036600319011261021457610cf290611c3c6040611c15611f5f565b338452603460209081528285206001600160a01b038316865290529220546024359061213f565b9033612228565b5034610214578060031936011261021457602060405160ff7f0000000000000000000000000000000000000000000000000000000000000012168152f35b5034610214576020366003190112610214576020611cab63ffffffff611ca5611f8b565b16612ade565b9050604051908152f35b503461021457606036600319011261021457611ccf611f5f565b90611cd8611f75565b6001600160a01b03831682526034602090815260408084203385529091529091205491604435919060018401611d13575b610cf29350612388565b828410611d2f57611d2a83610cf295033383612228565b611d09565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b503461021457806003193601126102145760206040517f00000000000000000000000000000000000000000000000000000000000000018152f35b50346102145780600319360112610214576020603554604051908152f35b5034610214576020366003190112610214577fc47cbcc588c67679e52261c45cc315e56562f8d0ccaba16facb9093ff94987996020611e0a611f5f565b803b15801590611e4f575b611e1e906120e3565b611e26612330565b609880546001600160a01b0319166001600160a01b03929092169182179055604051908152a180f35b506001600160a01b03811615611e15565b503461021457604036600319011261021457610cf2611e7d611f5f565b6024359033612228565b823461021457806003193601126102145760365481611ea5826120a9565b8085529160018116908115610e8b5750600114611ecc57610e3c84610e2881860382612026565b6036815260008051602061311f833981519152939250905b808210611efd57509091508101602001610e2882610e18565b919260018160209254838588010152019101909291611ee4565b60005b838110611f2a5750506000910152565b8181015183820152602001611f1a565b90602091611f5381518092818552858086019101611f17565b601f01601f1916010190565b600435906001600160a01b0382168203610a5057565b602435906001600160a01b0382168203610a5057565b6004359063ffffffff82168203610a5057565b9181601f84011215610a50578235916001600160401b038311610a50576020808501948460051b010111610a5057565b6060906003190112610a505760043563ffffffff81168103610a5057906024359060443590565b604081019081106001600160401b0382111761201057604052565b634e487b7160e01b600052604160045260246000fd5b90601f801991011681019081106001600160401b0382111761201057604052565b6001600160401b03811161201057601f01601f191660200190565b81601f82011215610a505780359061207982612047565b926120876040519485612026565b82845260208383010111610a5057816000926020809301838601378301015290565b90600182811c921680156120d9575b60208310146120c357565b634e487b7160e01b600052602260045260246000fd5b91607f16916120b8565b156120ea57565b60405162461bcd60e51b815260206004820152602760248201527f4d61696c626f78436c69656e743a20696e76616c696420636f6e74726163742060448201526673657474696e6760c81b6064820152608490fd5b9190820180921161214c57565b634e487b7160e01b600052601160045260246000fd5b60008051602061313f833981519152546001600160a01b031615612184573090565b600090565b91908110156121995760051b0190565b634e487b7160e01b600052603260045260246000fd5b3563ffffffff81168103610a505790565b6001600160401b0381116120105760051b60200190565b8051156121995760200190565b8051600110156121995760400190565b8051600210156121995760600190565b80518210156121995760209160051b010190565b91908110156121995760061b0190565b6001600160a01b03169081156122df576001600160a01b031691821561228f5760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260348252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b6065546001600160a01b0316330361234457565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b6001600160a01b03169081156124b4576001600160a01b03169182156124635781600052603360205260406000205481811061240f57817fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9260209285600052603384520360406000205584600052603382526040600020818154019055604051908152a3565b60405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fd5b1561250f5750565b60405162461bcd60e51b815260206004820152908190612533906024830190611f3a565b0390fd5b7fc3de732a98b24a2b5c6f67e8a7fb057ffc14046b83968a2c73e4148d2fba978b9163ffffffff60409216908160005260ca60205261258d8360002054151561258761258285612bd1565b612b15565b90612507565b8160005260fc60205280836000205582519182526020820152a1565b63ffffffff16906125b982612ade565b906125ed576125336125cd61258285612bd1565b60405162461bcd60e51b8152602060048201529182916024830190611f3a565b9150565b606580546001600160a01b039283166001600160a01b0319821681179092559091167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b63ffffffff61266991168060005260cb6020526000604081205561258761258261266383612f68565b92612bd1565b565b916126ca6126e694926126c46126d1937f0000000000000000000000000000000000000000000000000000000000000001907f000000000000000000000000000000000000000000000000000000000000000190612d58565b90612b59565b9183612b77565b6097546001600160a01b031692909190612a35565b90565b60008051602061317f833981519152546001600160a01b03169392909184156128ba576040516345ec85c160e11b815263ffffffff939093166004840152602483015260448201526000816064816001600160a01b0387165afa9081156113c0576000916127f4575b50805180156127ed57600114806127d1575b1561277a576127746020916121d7565b51015190565b60405162461bcd60e51b815260206004820152602960248201527f46756e6769626c65546f6b656e526f757465723a20666565206d757374206d616044820152683a31b4103a37b5b2b760b91b6064820152608490fd5b506001600160a01b036127e3826121d7565b5151163014612764565b5050600090565b903d8082843e6128048184612026565b8201916020818403126104ac578051906001600160401b0382116104a8570182601f820112156104ac5780519161283a836121c0565b936128486040519586612026565b83855260208086019460061b840101928184116104a857602001935b83851061287657505050505038612752565b6040858303126104a85760405161288c81611ff5565b85516001600160a01b03811681036118fb579181604093602093528288015183820152815201940193612864565b505050600090565b9063ffffffff6128e29216908160005260cb602052604060002055613049565b50565b156128ec57565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b6001600160a01b03169081156129a4577fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60208261298760009460355461213f565b6035558484526033825260408420818154019055604051908152a3565b60405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606490fd5b9390608093612a259363ffffffff612a1793999899168752602087015260a0604087015260a0860190611f3a565b908482036060860152611f3a565b6001600160a01b03909416910152565b92612a6f6020939294612a47816125a9565b6040516381d2ea9560e01b815296879586956001600160a01b031693909290600487016129e9565b03817f0000000000000000000000008ecd10fd6d7822ef16418689f92e5e1d5f144bd96001600160a01b03165afa9081156113c057600091612aaf575090565b90506020813d602011612ad6575b81612aca60209383612026565b81010312610a50575190565b3d9150612abd565b8060005260cb6020526040600020548015600014612b0d575060005260ca602052604060002054151590600090565b600192909150565b90612669603f60405180947f4e6f20726f7574657220656e726f6c6c656420666f7220646f6d61696e3a200060208301526103268151809260208686019101611f17565b906040519160208301526040820152604081526126e6606082612026565b63ffffffff1660005260fc6020526040600020549060405191600160f01b60208401526000602284015260428301523360601b60628301526001600160601b03199060601b166076820152606a81526126e6608a82612026565b8060009172184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b821015612d1d575b806d04ee2d6d415b85acef8100000000600a921015612d02575b662386f26fc10000811015612cee575b6305f5e100811015612cdd575b612710811015612cce575b6064811015612cc0575b1015612cb5575b600a60216001840193612c5985612047565b94612c676040519687612026565b808652612c76601f1991612047565b013660208701378401015b60001901916f181899199a1a9b1b9c1cb0b131b232b360811b8282061a8353048015612cb057600a9091612c81565b505090565b600190910190612c47565b606460029104930192612c40565b61271060049104930192612c36565b6305f5e10060089104930192612c2b565b662386f26fc1000060109104930192612c1e565b6d04ee2d6d415b85acef810000000060209104930192612c0e565b506040915072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8104612bf4565b80548210156121995760005260206000200190600090565b916000198284099282810292838086109503948086039514612e105784831115612dd35782910960018219018216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b60405162461bcd60e51b81526020600482015260156024820152744d6174683a206d756c446976206f766572666c6f7760581b6044820152606490fd5b505091508115612e1e570490565b634e487b7160e01b600052601260045260246000fd5b90816020910312610a5057518015158103610a505790565b604080519092612eb1926001600160a01b0316906000908190612e6f8786612026565b602085527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564602086015260208151910182855af1612eab612f38565b916130a9565b8051908115918215612f1e575b505015612ec85750565b5162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b612f319250602080918301019101612e34565b3880612ebe565b3d15612f63573d90612f4982612047565b91612f576040519384612026565b82523d6000602084013e565b606090565b600081815260ca602052604090205480156127ed57600019810181811161214c5760c95460001981019190821161214c57808203612ff8575b50505060c9548015612fe25760001901612fbc8160c9612d40565b8154906000199060031b1b1916905560c95560005260ca60205260006040812055600190565b634e487b7160e01b600052603160045260246000fd5b61303161300961301a9360c9612d40565b90549060031b1c92839260c9612d40565b819391549060031b91821b91600019901b19161790565b905560005260ca602052604060002055388080612fa1565b8060005260ca602052604060002054156000146130a35760c954680100000000000000008110156120105761308a61301a82600185940160c95560c9612d40565b905560c9549060005260ca602052604060002055600190565b50600090565b9192901561310b57508151156130bd575090565b3b156130c65790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b82519091501561250f5750805190602001fdfe4a11f94e20a93c79f6ec743a1954ec4fc2c08429ae2122118bf234b2185c81b8e797cab0ddd50f45c2a522220a721ebb6d0f53785d8595512b6122e7164a201f42a7b7dd785cd69714a189dffb3fd7d7174edc9ece837694ce50f7078f7c31ae721d42344eebce0a76684e8fddd9c81a84afda39f3019e5a078a53853f098d11a2646970667358221220495bd76ce0d343bfd7af3dd1e10f985ad41dd8e259ab6a0de2d26daf5470913464736f6c634300081e0033",
"is_contract": true,
"verified": true,
"verification": {
"address": "0x5c2e5dec72280f2ad5bb7f9befc0ef877aedf62d",
"compiler": "0.8.30+commit.73712a01.Emscripten.clang",
"contract": "@hyperlane-xyz/core/contracts/token/HypERC20.sol:HypERC20",
"verified": true,
"match": "runtime-with-metadata",
"creation_verified": true,
"factory_deployment": {
"factory": "0x05e1BaFb96595E8a5085be16091aB7A6309FFED8",
"transaction_hash": "0xea38efa4b5d478eb5ddad162378a9795f48236f8af70c6fd377aef510006130f",
"block_hash": "0x4bc2c92acc7cacd5702ebd065dc1e50081cec1b63662893ccde9103fb72dfdf6",
"block_number": 67741,
"method": "deploy"
},
"constructor_arguments": "0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000008ecd10fd6d7822ef16418689f92e5e1d5f144bd9",
"verified_at": "2026-10-03T15:17:43.318Z",
"chain_id": 20261001,
"abi": [
{
"inputs": [
{
"internalType": "uint8",
"name": "__decimals",
"type": "uint8"
},
{
"internalType": "uint256",
"name": "_scaleNumerator",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_scaleDenominator",
"type": "uint256"
},
{
"internalType": "address",
"name": "_mailbox",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeHook",
"type": "address"
}
],
"name": "FeeHookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeRecipient",
"type": "address"
}
],
"name": "FeeRecipientSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "GasSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "HookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint8",
"name": "version",
"type": "uint8"
}
],
"name": "Initialized",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_ism",
"type": "address"
}
],
"name": "IsmSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "previousOwner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "origin",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "ReceivedTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "destination",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "SentTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [],
"name": "PACKAGE_VERSION",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "decimals",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "subtractedValue",
"type": "uint256"
}
],
"name": "decreaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "destinationDomain",
"type": "uint32"
}
],
"name": "destinationGas",
"outputs": [
{
"internalType": "uint256",
"name": "gasLimit",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "domains",
"outputs": [
{
"internalType": "uint32[]",
"name": "",
"type": "uint32[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_router",
"type": "bytes32"
}
],
"name": "enrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
},
{
"internalType": "bytes32[]",
"name": "_addresses",
"type": "bytes32[]"
}
],
"name": "enrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "feeHook",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeRecipient",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeToken",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_origin",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_sender",
"type": "bytes32"
},
{
"internalType": "bytes",
"name": "_message",
"type": "bytes"
}
],
"name": "handle",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [],
"name": "hook",
"outputs": [
{
"internalType": "contract IPostDispatchHook",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "addedValue",
"type": "uint256"
}
],
"name": "increaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_totalSupply",
"type": "uint256"
},
{
"internalType": "string",
"name": "_name",
"type": "string"
},
{
"internalType": "string",
"name": "_symbol",
"type": "string"
},
{
"internalType": "address",
"name": "_hook",
"type": "address"
},
{
"internalType": "address",
"name": "_interchainSecurityModule",
"type": "address"
},
{
"internalType": "address",
"name": "_owner",
"type": "address"
}
],
"name": "initialize",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "interchainSecurityModule",
"outputs": [
{
"internalType": "contract IInterchainSecurityModule",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "localDomain",
"outputs": [
{
"internalType": "uint32",
"name": "",
"type": "uint32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "mailbox",
"outputs": [
{
"internalType": "contract IMailbox",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destinationDomain",
"type": "uint32"
}
],
"name": "quoteGasPayment",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "quoteTransferRemote",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "token",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"internalType": "struct Quote[]",
"name": "quotes",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "renounceOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "routers",
"outputs": [
{
"internalType": "bytes32",
"name": "",
"type": "bytes32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleDenominator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleNumerator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"components": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"internalType": "struct GasRouter.GasRouterConfig[]",
"name": "gasConfigs",
"type": "tuple[]"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_feeHook",
"type": "address"
}
],
"name": "setFeeHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "recipient",
"type": "address"
}
],
"name": "setFeeRecipient",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "setHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_module",
"type": "address"
}
],
"name": "setInterchainSecurityModule",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "symbol",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "token",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "from",
"type": "address"
},
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "transferRemote",
"outputs": [
{
"internalType": "bytes32",
"name": "messageId",
"type": "bytes32"
}
],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "unenrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
}
],
"name": "unenrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
],
"input": {
"language": "Solidity",
"sources": {
"@hyperlane-xyz/core/contracts/Mailbox.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {Versioned} from \"./upgrade/Versioned.sol\";\nimport {Indexed} from \"./libs/Indexed.sol\";\nimport {Message} from \"./libs/Message.sol\";\nimport {TypeCasts} from \"./libs/TypeCasts.sol\";\nimport {IInterchainSecurityModule, ISpecifiesInterchainSecurityModule} from \"./interfaces/IInterchainSecurityModule.sol\";\nimport {IPostDispatchHook} from \"./interfaces/hooks/IPostDispatchHook.sol\";\nimport {IMessageRecipient} from \"./interfaces/IMessageRecipient.sol\";\nimport {IMailbox} from \"./interfaces/IMailbox.sol\";\nimport {PackageVersioned} from \"./PackageVersioned.sol\";\n\n// ============ External Imports ============\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract Mailbox is\n IMailbox,\n Indexed,\n Versioned,\n OwnableUpgradeable,\n PackageVersioned\n{\n // ============ Libraries ============\n\n using Message for bytes;\n using TypeCasts for bytes32;\n using TypeCasts for address;\n\n // ============ Constants ============\n\n // Domain of chain on which the contract is deployed\n uint32 public immutable localDomain;\n\n // ============ Public Storage ============\n\n // A monotonically increasing nonce for outbound unique message IDs.\n uint32 public nonce;\n\n // The latest dispatched message ID used for auth in post-dispatch hooks.\n bytes32 public latestDispatchedId;\n\n // The default ISM, used if the recipient fails to specify one.\n IInterchainSecurityModule public defaultIsm;\n\n // The default post dispatch hook, used for post processing of opting-in dispatches.\n IPostDispatchHook public defaultHook;\n\n // The required post dispatch hook, used for post processing of ALL dispatches.\n IPostDispatchHook public requiredHook;\n\n // Mapping of message ID to delivery context that processed the message.\n struct Delivery {\n address processor;\n uint48 blockNumber;\n }\n\n mapping(bytes32 messageId => Delivery delivery) internal deliveries;\n\n // ============ Events ============\n\n /**\n * @notice Emitted when the default ISM is updated\n * @param module The new default ISM\n */\n event DefaultIsmSet(address indexed module);\n\n /**\n * @notice Emitted when the default hook is updated\n * @param hook The new default hook\n */\n event DefaultHookSet(address indexed hook);\n\n /**\n * @notice Emitted when the required hook is updated\n * @param hook The new required hook\n */\n event RequiredHookSet(address indexed hook);\n\n // ============ Constructor ============\n constructor(uint32 _localDomain) {\n localDomain = _localDomain;\n }\n\n // ============ Initializers ============\n function initialize(\n address _owner,\n address _defaultIsm,\n address _defaultHook,\n address _requiredHook\n ) external initializer {\n __Ownable_init();\n setDefaultIsm(_defaultIsm);\n setDefaultHook(_defaultHook);\n setRequiredHook(_requiredHook);\n transferOwnership(_owner);\n }\n\n // ============ External Functions ============\n /**\n * @notice Dispatches a message to the destination domain & recipient\n * using the default hook and empty metadata.\n * @param _destinationDomain Domain of destination chain\n * @param _recipientAddress Address of recipient on destination chain as bytes32\n * @param _messageBody Raw bytes content of message body\n * @return The message ID inserted into the Mailbox's merkle tree\n */\n function dispatch(\n uint32 _destinationDomain,\n bytes32 _recipientAddress,\n bytes calldata _messageBody\n ) external payable override returns (bytes32) {\n return\n dispatch(\n _destinationDomain,\n _recipientAddress,\n _messageBody,\n _messageBody[0:0],\n defaultHook\n );\n }\n\n /**\n * @notice Dispatches a message to the destination domain & recipient.\n * @param destinationDomain Domain of destination chain\n * @param recipientAddress Address of recipient on destination chain as bytes32\n * @param messageBody Raw bytes content of message body\n * @param hookMetadata Metadata used by the post dispatch hook\n * @return The message ID inserted into the Mailbox's merkle tree\n */\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata hookMetadata\n ) external payable override returns (bytes32) {\n return\n dispatch(\n destinationDomain,\n recipientAddress,\n messageBody,\n hookMetadata,\n defaultHook\n );\n }\n\n /**\n * @notice Computes quote for dipatching a message to the destination domain & recipient\n * using the default hook and empty metadata.\n * @param destinationDomain Domain of destination chain\n * @param recipientAddress Address of recipient on destination chain as bytes32\n * @param messageBody Raw bytes content of message body\n * @return fee The payment required to dispatch the message\n */\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) external view returns (uint256 fee) {\n return\n quoteDispatch(\n destinationDomain,\n recipientAddress,\n messageBody,\n messageBody[0:0],\n defaultHook\n );\n }\n\n /**\n * @notice Computes quote for dispatching a message to the destination domain & recipient.\n * @param destinationDomain Domain of destination chain\n * @param recipientAddress Address of recipient on destination chain as bytes32\n * @param messageBody Raw bytes content of message body\n * @param defaultHookMetadata Metadata used by the default post dispatch hook\n * @return fee The payment required to dispatch the message\n */\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata defaultHookMetadata\n ) external view returns (uint256 fee) {\n return\n quoteDispatch(\n destinationDomain,\n recipientAddress,\n messageBody,\n defaultHookMetadata,\n defaultHook\n );\n }\n\n /**\n * @notice Attempts to deliver `_message` to its recipient. Verifies\n * `_message` via the recipient's ISM using the provided `_metadata`.\n * @param _metadata Metadata used by the ISM to verify `_message`.\n * @param _message Formatted Hyperlane message (refer to Message.sol).\n */\n function process(\n bytes calldata _metadata,\n bytes calldata _message\n ) external payable override {\n /// CHECKS ///\n\n // Check that the message was intended for this mailbox.\n require(_message.version() == VERSION, \"Mailbox: bad version\");\n require(\n _message.destination() == localDomain,\n \"Mailbox: unexpected destination\"\n );\n\n // Check that the message hasn't already been delivered.\n bytes32 _id = _message.id();\n require(delivered(_id) == false, \"Mailbox: already delivered\");\n\n // Get the recipient's ISM.\n address recipient = _message.recipientAddress();\n IInterchainSecurityModule ism = recipientIsm(recipient);\n\n /// EFFECTS ///\n\n deliveries[_id] = Delivery({\n processor: msg.sender,\n blockNumber: uint48(block.number)\n });\n emit Process(_message.origin(), _message.sender(), recipient);\n emit ProcessId(_id);\n\n /// INTERACTIONS ///\n\n // Verify the message via the interchain security module.\n require(\n ism.verify(_metadata, _message),\n \"Mailbox: ISM verification failed\"\n );\n\n // Deliver the message to the recipient.\n IMessageRecipient(recipient).handle{value: msg.value}(\n _message.origin(),\n _message.sender(),\n _message.body()\n );\n }\n\n /**\n * @notice Returns the account that processed the message.\n * @param _id The message ID to check.\n * @return The account that processed the message.\n */\n function processor(bytes32 _id) external view returns (address) {\n return deliveries[_id].processor;\n }\n\n /**\n * @notice Returns the account that processed the message.\n * @param _id The message ID to check.\n * @return The number of the block that the message was processed at.\n */\n function processedAt(bytes32 _id) external view returns (uint48) {\n return deliveries[_id].blockNumber;\n }\n\n // ============ Public Functions ============\n\n /**\n * @notice Dispatches a message to the destination domain & recipient.\n * @param destinationDomain Domain of destination chain\n * @param recipientAddress Address of recipient on destination chain as bytes32\n * @param messageBody Raw bytes content of message body\n * @param metadata Metadata used by the post dispatch hook\n * @param hook Custom hook to use instead of the default\n * @return The message ID inserted into the Mailbox's merkle tree\n */\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata metadata,\n IPostDispatchHook hook\n ) public payable virtual returns (bytes32) {\n if (address(hook) == address(0)) {\n hook = defaultHook;\n }\n\n /// CHECKS ///\n\n // Format the message into packed bytes.\n bytes memory message = _buildMessage(\n destinationDomain,\n recipientAddress,\n messageBody\n );\n bytes32 id = message.id();\n\n /// EFFECTS ///\n\n latestDispatchedId = id;\n nonce += 1;\n emit Dispatch(msg.sender, destinationDomain, recipientAddress, message);\n emit DispatchId(id);\n\n /// INTERACTIONS ///\n uint256 requiredValue = requiredHook.quoteDispatch(metadata, message);\n // if underpaying, defer to required hook's reverting behavior\n if (msg.value < requiredValue) {\n requiredValue = msg.value;\n }\n requiredHook.postDispatch{value: requiredValue}(metadata, message);\n hook.postDispatch{value: msg.value - requiredValue}(metadata, message);\n\n return id;\n }\n\n /**\n * @notice Computes quote for dispatching a message to the destination domain & recipient.\n * @dev This function sums the quotes from requiredHook and hook, assuming both return\n * values denominated in the same currency. When using ERC-20 fee tokens (via\n * StandardHookMetadata.feeToken), this works because:\n * - Native-only hooks reject non-zero feeToken metadata via supportsMetadata\n * - The requiredHook (typically ProtocolFee) returns 0 when protocolFee is 0\n *\n * IMPORTANT: Mixing fee denominations (native + ERC-20) in a single dispatch is not\n * supported. Callers must ensure all hooks in the chain use the same fee denomination.\n *\n * @param destinationDomain Domain of destination chain\n * @param recipientAddress Address of recipient on destination chain as bytes32\n * @param messageBody Raw bytes content of message body\n * @param metadata Metadata used by the post dispatch hook\n * @param hook Custom hook to use instead of the default\n * @return fee The payment required to dispatch the message\n */\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata metadata,\n IPostDispatchHook hook\n ) public view returns (uint256 fee) {\n if (address(hook) == address(0)) {\n hook = defaultHook;\n }\n\n bytes memory message = _buildMessage(\n destinationDomain,\n recipientAddress,\n messageBody\n );\n return\n requiredHook.quoteDispatch(metadata, message) +\n hook.quoteDispatch(metadata, message);\n }\n\n /**\n * @notice Returns true if the message has been processed.\n * @param _id The message ID to check.\n * @return True if the message has been delivered.\n */\n function delivered(bytes32 _id) public view override returns (bool) {\n return deliveries[_id].blockNumber > 0;\n }\n\n /**\n * @notice Sets the default ISM for the Mailbox.\n * @param _module The new default ISM. Must be a contract.\n */\n function setDefaultIsm(address _module) public onlyOwner {\n require(\n Address.isContract(_module),\n \"Mailbox: default ISM not contract\"\n );\n defaultIsm = IInterchainSecurityModule(_module);\n emit DefaultIsmSet(_module);\n }\n\n /**\n * @notice Sets the default post dispatch hook for the Mailbox.\n * @param _hook The new default post dispatch hook. Must be a contract.\n */\n function setDefaultHook(address _hook) public onlyOwner {\n require(\n Address.isContract(_hook),\n \"Mailbox: default hook not contract\"\n );\n defaultHook = IPostDispatchHook(_hook);\n emit DefaultHookSet(_hook);\n }\n\n /**\n * @notice Sets the required post dispatch hook for the Mailbox.\n * @param _hook The new default post dispatch hook. Must be a contract.\n */\n function setRequiredHook(address _hook) public onlyOwner {\n require(\n Address.isContract(_hook),\n \"Mailbox: required hook not contract\"\n );\n requiredHook = IPostDispatchHook(_hook);\n emit RequiredHookSet(_hook);\n }\n\n /**\n * @notice Returns the ISM to use for the recipient, defaulting to the\n * default ISM if none is specified.\n * @param _recipient The message recipient whose ISM should be returned.\n * @return The ISM to use for `_recipient`.\n */\n function recipientIsm(\n address _recipient\n ) public view returns (IInterchainSecurityModule) {\n // use low-level staticcall in case of revert or empty return data\n (bool success, bytes memory returnData) = _recipient.staticcall(\n abi.encodeCall(\n ISpecifiesInterchainSecurityModule.interchainSecurityModule,\n ()\n )\n );\n // check if call was successful and returned data\n if (success && returnData.length != 0) {\n // check if returnData is a valid address\n address ism = abi.decode(returnData, (address));\n // check if the ISM is a contract\n if (ism != address(0)) {\n return IInterchainSecurityModule(ism);\n }\n }\n // Use the default if a valid one is not specified by the recipient.\n return defaultIsm;\n }\n\n // ============ Internal Functions ============\n function _buildMessage(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) internal view returns (bytes memory) {\n return\n Message.formatMessage(\n VERSION,\n nonce,\n localDomain,\n msg.sender.addressToBytes32(),\n destinationDomain,\n recipientAddress,\n messageBody\n );\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/hooks/MerkleTreeHook.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\nimport {MerkleLib} from \"../libs/Merkle.sol\";\nimport {Message} from \"../libs/Message.sol\";\nimport {MailboxClient} from \"../client/MailboxClient.sol\";\nimport {Indexed} from \"../libs/Indexed.sol\";\nimport {IPostDispatchHook} from \"../interfaces/hooks/IPostDispatchHook.sol\";\nimport {AbstractPostDispatchHook} from \"./libs/AbstractPostDispatchHook.sol\";\nimport {StandardHookMetadata} from \"./libs/StandardHookMetadata.sol\";\n\ncontract MerkleTreeHook is AbstractPostDispatchHook, MailboxClient, Indexed {\n using Message for bytes;\n using MerkleLib for MerkleLib.Tree;\n using StandardHookMetadata for bytes;\n\n // An incremental merkle tree used to store outbound message IDs.\n MerkleLib.Tree internal _tree;\n\n event InsertedIntoTree(bytes32 messageId, uint32 index);\n\n constructor(address _mailbox) MailboxClient(_mailbox) {}\n\n // count cannot exceed 2**TREE_DEPTH, see MerkleLib.sol\n function count() public view returns (uint32) {\n return uint32(_tree.count);\n }\n\n function root() public view returns (bytes32) {\n return _tree.root();\n }\n\n function tree() public view returns (MerkleLib.Tree memory) {\n return _tree;\n }\n\n function latestCheckpoint() external view returns (bytes32, uint32) {\n return (root(), count() - 1);\n }\n\n // ============ External Functions ============\n\n /// @inheritdoc IPostDispatchHook\n function hookType() external pure override returns (uint8) {\n return uint8(IPostDispatchHook.HookTypes.MERKLE_TREE);\n }\n\n // ============ Internal Functions ============\n\n /// @inheritdoc AbstractPostDispatchHook\n function _postDispatch(\n bytes calldata,\n /*metadata*/\n bytes calldata message\n ) internal override {\n require(msg.value == 0, \"MerkleTreeHook: no value expected\");\n\n // ensure messages which were not dispatched are not inserted into the tree\n bytes32 id = message.id();\n require(_isLatestDispatched(id), \"message not dispatching\");\n\n uint32 index = count();\n _tree.insert(id);\n emit InsertedIntoTree(id, index);\n }\n\n /// @inheritdoc AbstractPostDispatchHook\n function _quoteDispatch(\n bytes calldata,\n /*metadata*/\n bytes calldata /*message*/\n ) internal pure override returns (uint256) {\n return 0;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/hooks/ProtocolFee.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n// ============ Internal Imports ============\nimport {Message} from \"../libs/Message.sol\";\nimport {StandardHookMetadata} from \"./libs/StandardHookMetadata.sol\";\nimport {AbstractPostDispatchHook} from \"./libs/AbstractPostDispatchHook.sol\";\nimport {IPostDispatchHook} from \"../interfaces/hooks/IPostDispatchHook.sol\";\n\n// ============ External Imports ============\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/**\n * @title ProtocolFee\n * @notice Collects a static protocol fee from the sender.\n */\ncontract ProtocolFee is AbstractPostDispatchHook, Ownable {\n using StandardHookMetadata for bytes;\n using Address for address payable;\n using Message for bytes;\n\n event ProtocolFeeSet(uint256 protocolFee);\n event BeneficiarySet(address beneficiary);\n event ProtocolFeePaid(address indexed sender, uint256 fee);\n\n // ============ Constants ============\n\n /// @notice The maximum protocol fee that can be set.\n uint256 public immutable MAX_PROTOCOL_FEE;\n\n // ============ Public Storage ============\n\n /// @notice The current protocol fee.\n uint256 public protocolFee;\n /// @notice The beneficiary of protocol fees.\n address public beneficiary;\n\n // ============ Constructor ============\n\n constructor(\n uint256 _maxProtocolFee,\n uint256 _protocolFee,\n address _beneficiary,\n address _owner\n ) {\n MAX_PROTOCOL_FEE = _maxProtocolFee;\n _setProtocolFee(_protocolFee);\n _setBeneficiary(_beneficiary);\n _transferOwnership(_owner);\n }\n\n // ============ External Functions ============\n\n /// @inheritdoc AbstractPostDispatchHook\n /// @dev Rejects metadata with a non-zero ERC20 fee token when the protocol fee\n /// is non-zero, since this hook only accepts native token payment via msg.value.\n /// When protocolFee is 0, fee token metadata is accepted because the hook contributes\n /// nothing to the Mailbox.quoteDispatch sum, avoiding denomination mixing.\n function supportsMetadata(\n bytes calldata metadata\n ) public view override returns (bool) {\n if (protocolFee > 0 && metadata.feeToken(address(0)) != address(0)) {\n return false;\n }\n return super.supportsMetadata(metadata);\n }\n\n /// @inheritdoc IPostDispatchHook\n function hookType() external pure override returns (uint8) {\n return uint8(IPostDispatchHook.HookTypes.PROTOCOL_FEE);\n }\n\n /**\n * @notice Sets the protocol fee.\n * @param _protocolFee The new protocol fee.\n */\n function setProtocolFee(uint256 _protocolFee) external onlyOwner {\n _setProtocolFee(_protocolFee);\n }\n\n /**\n * @notice Sets the beneficiary of protocol fees.\n * @param _beneficiary The new beneficiary.\n */\n function setBeneficiary(address _beneficiary) external onlyOwner {\n _setBeneficiary(_beneficiary);\n }\n\n /**\n * @notice Collects protocol fees from the contract.\n */\n function collectProtocolFees() external {\n payable(beneficiary).sendValue(address(this).balance);\n }\n\n // ============ Internal Functions ============\n\n /// @inheritdoc AbstractPostDispatchHook\n function _postDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) internal override {\n require(\n msg.value >= protocolFee,\n \"ProtocolFee: insufficient protocol fee\"\n );\n\n emit ProtocolFeePaid(message.senderAddress(), protocolFee);\n\n _refund(metadata, message, msg.value - protocolFee);\n }\n\n /// @inheritdoc AbstractPostDispatchHook\n function _quoteDispatch(\n bytes calldata,\n bytes calldata\n ) internal view override returns (uint256) {\n return protocolFee;\n }\n\n /**\n * @notice Sets the protocol fee.\n * @param _protocolFee The new protocol fee.\n */\n function _setProtocolFee(uint256 _protocolFee) internal {\n require(\n _protocolFee <= MAX_PROTOCOL_FEE,\n \"ProtocolFee: exceeds max protocol fee\"\n );\n protocolFee = _protocolFee;\n emit ProtocolFeeSet(_protocolFee);\n }\n\n /**\n * @notice Sets the beneficiary of protocol fees.\n * @param _beneficiary The new beneficiary.\n */\n function _setBeneficiary(address _beneficiary) internal {\n require(_beneficiary != address(0), \"ProtocolFee: invalid beneficiary\");\n beneficiary = _beneficiary;\n emit BeneficiarySet(_beneficiary);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/PausableIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ External Imports ============\nimport {Pausable} from \"@openzeppelin/contracts/security/Pausable.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n// ============ Internal Imports ============\nimport {IInterchainSecurityModule} from \"../interfaces/IInterchainSecurityModule.sol\";\nimport {PackageVersioned} from \"../PackageVersioned.sol\";\n\ncontract PausableIsm is\n IInterchainSecurityModule,\n Ownable,\n Pausable,\n PackageVersioned\n{\n uint8 public constant override moduleType = uint8(Types.NULL);\n\n constructor(address owner) Ownable() Pausable() {\n _transferOwnership(owner);\n }\n\n /**\n * @inheritdoc IInterchainSecurityModule\n * @dev Reverts when paused, otherwise returns `true`.\n */\n function verify(\n bytes calldata,\n bytes calldata\n ) external view whenNotPaused returns (bool) {\n return true;\n }\n\n function pause() external onlyOwner {\n _pause();\n }\n\n function unpause() external onlyOwner {\n _unpause();\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/multisig/StaticMultisigIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n// ============ Internal Imports ============\n\nimport {IInterchainSecurityModule} from \"../../interfaces/IInterchainSecurityModule.sol\";\nimport {AbstractMultisigIsm} from \"./AbstractMultisigIsm.sol\";\nimport {AbstractMerkleRootMultisigIsm} from \"./AbstractMerkleRootMultisigIsm.sol\";\nimport {AbstractMessageIdMultisigIsm} from \"./AbstractMessageIdMultisigIsm.sol\";\nimport {MetaProxy} from \"../../libs/MetaProxy.sol\";\nimport {StaticThresholdAddressSetFactory} from \"../../libs/StaticAddressSetFactory.sol\";\n\n/**\n * @title AbstractMetaProxyMultisigIsm\n * @notice Manages per-domain m-of-n Validator set that is used\n * to verify interchain messages.\n */\nabstract contract AbstractMetaProxyMultisigIsm is AbstractMultisigIsm {\n /**\n * @inheritdoc AbstractMultisigIsm\n */\n function validatorsAndThreshold(\n bytes calldata\n ) public pure override returns (address[] memory, uint8) {\n return abi.decode(MetaProxy.metadata(), (address[], uint8));\n }\n}\n\n// solhint-disable no-empty-blocks\n\n/**\n * @title StaticMerkleRootMultisigIsm\n * @notice Manages per-domain m-of-n validator set that is used\n * to verify interchain messages using a merkle root signature quorum\n * and merkle proof of inclusion.\n */\ncontract StaticMerkleRootMultisigIsm is\n AbstractMerkleRootMultisigIsm,\n AbstractMetaProxyMultisigIsm\n{\n uint8 public constant moduleType =\n uint8(IInterchainSecurityModule.Types.MERKLE_ROOT_MULTISIG);\n}\n\n/**\n * @title StaticMessageIdMultisigIsm\n * @notice Manages per-domain m-of-n validator set that is used\n * to verify interchain messages using a message ID signature quorum.\n */\ncontract StaticMessageIdMultisigIsm is\n AbstractMessageIdMultisigIsm,\n AbstractMetaProxyMultisigIsm\n{\n uint8 public constant moduleType =\n uint8(IInterchainSecurityModule.Types.MESSAGE_ID_MULTISIG);\n}\n\n// solhint-enable no-empty-blocks\n\ncontract StaticMerkleRootMultisigIsmFactory is\n StaticThresholdAddressSetFactory\n{\n function _deployImplementation() internal override returns (address) {\n return address(new StaticMerkleRootMultisigIsm());\n }\n}\n\ncontract StaticMessageIdMultisigIsmFactory is StaticThresholdAddressSetFactory {\n function _deployImplementation() internal override returns (address) {\n return address(new StaticMessageIdMultisigIsm());\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/aggregation/StaticAggregationIsmFactory.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {StaticAggregationIsm} from \"./StaticAggregationIsm.sol\";\nimport {StaticThresholdAddressSetFactory} from \"../../libs/StaticAddressSetFactory.sol\";\n\ncontract StaticAggregationIsmFactory is StaticThresholdAddressSetFactory {\n function _deployImplementation() internal override returns (address) {\n return address(new StaticAggregationIsm());\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/HypERC20Collateral.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n// ============ Internal Imports ============\nimport {TokenMessage} from \"./libs/TokenMessage.sol\";\nimport {TokenRouter} from \"./libs/TokenRouter.sol\";\nimport {MovableCollateralRouter} from \"./libs/MovableCollateralRouter.sol\";\nimport {LpCollateralRouter} from \"./libs/LpCollateralRouter.sol\";\nimport {ITokenBridge, Quote} from \"../interfaces/ITokenBridge.sol\";\nimport {ERC20Collateral} from \"./libs/TokenCollateral.sol\";\nimport {EnumerableMapExtended} from \"../libs/EnumerableMapExtended.sol\";\n\n// ============ External Imports ============\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\n/**\n * @title Hyperlane ERC20 Token Collateral that wraps an existing ERC20 with remote transfer functionality.\n * @author Abacus Works\n */\ncontract HypERC20Collateral is LpCollateralRouter {\n using SafeERC20 for IERC20;\n using ERC20Collateral for IERC20;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;\n\n IERC20 public immutable wrappedToken;\n\n /**\n * @notice Constructor\n * @param erc20 Address of the token to keep as collateral\n */\n constructor(\n address erc20,\n uint256 _scaleNumerator,\n uint256 _scaleDenominator,\n address _mailbox\n ) TokenRouter(_scaleNumerator, _scaleDenominator, _mailbox) {\n require(Address.isContract(erc20), \"HypERC20Collateral: invalid token\");\n wrappedToken = IERC20(erc20);\n }\n\n function initialize(\n address _hook,\n address _interchainSecurityModule,\n address _owner\n ) public initializer {\n _MailboxClient_initialize(_hook, _interchainSecurityModule, _owner);\n _LpCollateralRouter_initialize();\n }\n\n function token() public view override returns (address) {\n return address(wrappedToken);\n }\n\n function _removeBridge(\n uint32 domain,\n ITokenBridge bridge\n ) internal override {\n MovableCollateralRouter._removeBridge(domain, bridge);\n\n uint32[] memory knownDomains = _routers.uint32Keys();\n\n // Iteration is fine as number of enrolled domains is bounded\n for (uint256 i = 0; i < knownDomains.length; i++) {\n EnumerableSet.AddressSet storage bridges = allowed.bridges[\n knownDomains[i]\n ];\n\n if (bridges.contains(address(bridge))) {\n return;\n }\n }\n\n wrappedToken.forceApprove(address(bridge), 0);\n }\n\n /**\n * @dev Transfers `_amount` of `wrappedToken` from `msg.sender` to this contract.\n * @inheritdoc TokenRouter\n */\n function _transferFromSender(uint256 _amount) internal override {\n wrappedToken._transferFromSender(_amount);\n }\n\n /**\n * @dev Transfers `_amount` of `wrappedToken` from this contract to `_recipient`.\n * @inheritdoc TokenRouter\n */\n function _transferTo(\n address _recipient,\n uint256 _amount\n ) internal override {\n wrappedToken._transferTo(_recipient, _amount);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/HypERC20.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity >=0.8.0;\n\nimport {TokenRouter} from \"./libs/TokenRouter.sol\";\nimport {Quote} from \"../interfaces/ITokenBridge.sol\";\nimport {TokenRouter} from \"./libs/TokenRouter.sol\";\n\nimport {ERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\n\n/**\n * @title Hyperlane ERC20 Token Router that extends ERC20 with remote transfer functionality.\n * @author Abacus Works\n * @dev Supply on each chain is not constant but the aggregate supply across all chains is.\n */\ncontract HypERC20 is ERC20Upgradeable, TokenRouter {\n uint8 private immutable _decimals;\n\n constructor(\n uint8 __decimals,\n uint256 _scaleNumerator,\n uint256 _scaleDenominator,\n address _mailbox\n ) TokenRouter(_scaleNumerator, _scaleDenominator, _mailbox) {\n _decimals = __decimals;\n }\n\n /**\n * @notice Initializes the Hyperlane router, ERC20 metadata, and mints initial supply to deployer.\n * @param _totalSupply The initial supply of the token.\n * @param _name The name of the token.\n * @param _symbol The symbol of the token.\n */\n function initialize(\n uint256 _totalSupply,\n string memory _name,\n string memory _symbol,\n address _hook,\n address _interchainSecurityModule,\n address _owner\n ) public initializer {\n // Initialize ERC20 metadata\n __ERC20_init(_name, _symbol);\n _mint(msg.sender, _totalSupply);\n _MailboxClient_initialize(_hook, _interchainSecurityModule, _owner);\n }\n\n function decimals() public view override returns (uint8) {\n return _decimals;\n }\n\n // ============ TokenRouter overrides ============\n\n /**\n * @inheritdoc TokenRouter\n */\n function token() public view override returns (address) {\n return address(this);\n }\n\n /**\n * @inheritdoc TokenRouter\n * @dev Overrides to burn `_amount` of token from `msg.sender` balance.\n * @dev Known overrides:\n * - HypERC4626: Converts the amount to shares and burns from the User (via HypERC20 implementation)\n */\n // solhint-disable-next-line hyperlane/no-virtual-override\n function _transferFromSender(uint256 _amount) internal virtual override {\n _burn(msg.sender, _amount);\n }\n\n /**\n * @inheritdoc TokenRouter\n * @dev Overrides to mint `_amount` of token to `_recipient` balance.\n */\n function _transferTo(\n address _recipient,\n uint256 _amount\n ) internal override {\n _mint(_recipient, _amount);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/upgrade/Versioned.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n/**\n * @title Versioned\n * @notice Version getter for contracts\n **/\ncontract Versioned {\n uint8 public constant VERSION = 3;\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/Indexed.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\ncontract Indexed {\n uint256 public immutable deployedBlock;\n\n constructor() {\n deployedBlock = block.number;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/Message.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nimport {TypeCasts} from \"./TypeCasts.sol\";\n\n/**\n * @title Hyperlane Message Library\n * @notice Library for formatted messages used by Mailbox\n **/\nlibrary Message {\n using TypeCasts for bytes32;\n\n uint256 private constant VERSION_OFFSET = 0;\n uint256 private constant NONCE_OFFSET = 1;\n uint256 private constant ORIGIN_OFFSET = 5;\n uint256 private constant SENDER_OFFSET = 9;\n uint256 private constant DESTINATION_OFFSET = 41;\n uint256 private constant RECIPIENT_OFFSET = 45;\n uint256 private constant BODY_OFFSET = 77;\n\n /**\n * @notice Returns formatted (packed) Hyperlane message with provided fields\n * @dev This function should only be used in memory message construction.\n * @param _version The version of the origin and destination Mailboxes\n * @param _nonce A nonce to uniquely identify the message on its origin chain\n * @param _originDomain Domain of origin chain\n * @param _sender Address of sender as bytes32\n * @param _destinationDomain Domain of destination chain\n * @param _recipient Address of recipient on destination chain as bytes32\n * @param _messageBody Raw bytes of message body\n * @return Formatted message\n */\n function formatMessage(\n uint8 _version,\n uint32 _nonce,\n uint32 _originDomain,\n bytes32 _sender,\n uint32 _destinationDomain,\n bytes32 _recipient,\n bytes calldata _messageBody\n ) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n _version,\n _nonce,\n _originDomain,\n _sender,\n _destinationDomain,\n _recipient,\n _messageBody\n );\n }\n\n /**\n * @notice Returns the message ID.\n * @param _message ABI encoded Hyperlane message.\n * @return ID of `_message`\n */\n function id(bytes memory _message) internal pure returns (bytes32) {\n return keccak256(_message);\n }\n\n /**\n * @notice Returns the message version.\n * @param _message ABI encoded Hyperlane message.\n * @return Version of `_message`\n */\n function version(bytes calldata _message) internal pure returns (uint8) {\n return uint8(bytes1(_message[VERSION_OFFSET:NONCE_OFFSET]));\n }\n\n /**\n * @notice Returns the message nonce.\n * @param _message ABI encoded Hyperlane message.\n * @return Nonce of `_message`\n */\n function nonce(bytes calldata _message) internal pure returns (uint32) {\n return uint32(bytes4(_message[NONCE_OFFSET:ORIGIN_OFFSET]));\n }\n\n /**\n * @notice Returns the message origin domain.\n * @param _message ABI encoded Hyperlane message.\n * @return Origin domain of `_message`\n */\n function origin(bytes calldata _message) internal pure returns (uint32) {\n return uint32(bytes4(_message[ORIGIN_OFFSET:SENDER_OFFSET]));\n }\n\n /**\n * @notice Returns the message sender as bytes32.\n * @param _message ABI encoded Hyperlane message.\n * @return Sender of `_message` as bytes32\n */\n function sender(bytes calldata _message) internal pure returns (bytes32) {\n return bytes32(_message[SENDER_OFFSET:DESTINATION_OFFSET]);\n }\n\n /**\n * @notice Returns the message sender as address.\n * @param _message ABI encoded Hyperlane message.\n * @return Sender of `_message` as address\n */\n function senderAddress(\n bytes calldata _message\n ) internal pure returns (address) {\n return sender(_message).bytes32ToAddress();\n }\n\n /**\n * @notice Returns the message destination domain.\n * @param _message ABI encoded Hyperlane message.\n * @return Destination domain of `_message`\n */\n function destination(\n bytes calldata _message\n ) internal pure returns (uint32) {\n return uint32(bytes4(_message[DESTINATION_OFFSET:RECIPIENT_OFFSET]));\n }\n\n /**\n * @notice Returns the message recipient as bytes32.\n * @param _message ABI encoded Hyperlane message.\n * @return Recipient of `_message` as bytes32\n */\n function recipient(\n bytes calldata _message\n ) internal pure returns (bytes32) {\n return bytes32(_message[RECIPIENT_OFFSET:BODY_OFFSET]);\n }\n\n /**\n * @notice Returns the message recipient as address.\n * @param _message ABI encoded Hyperlane message.\n * @return Recipient of `_message` as address\n */\n function recipientAddress(\n bytes calldata _message\n ) internal pure returns (address) {\n return recipient(_message).bytes32ToAddress();\n }\n\n /**\n * @notice Returns the message body.\n * @param _message ABI encoded Hyperlane message.\n * @return Body of `_message`\n */\n function body(\n bytes calldata _message\n ) internal pure returns (bytes calldata) {\n return bytes(_message[BODY_OFFSET:]);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/TypeCasts.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\nlibrary TypeCasts {\n // alignment preserving cast\n function addressToBytes32(address _addr) internal pure returns (bytes32) {\n return bytes32(uint256(uint160(_addr)));\n }\n\n // alignment preserving cast\n function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {\n require(\n uint256(_buf) <= uint256(type(uint160).max),\n \"TypeCasts: bytes32ToAddress overflow\"\n );\n return address(uint160(uint256(_buf)));\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/IInterchainSecurityModule.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\ninterface IInterchainSecurityModule {\n enum Types {\n UNUSED,\n ROUTING,\n AGGREGATION,\n LEGACY_MULTISIG,\n MERKLE_ROOT_MULTISIG,\n MESSAGE_ID_MULTISIG,\n NULL, // used with relayer carrying no metadata\n CCIP_READ,\n ARB_L2_TO_L1,\n WEIGHTED_MERKLE_ROOT_MULTISIG,\n WEIGHTED_MESSAGE_ID_MULTISIG,\n OP_L2_TO_L1,\n POLYMER\n }\n\n /**\n * @notice Returns an enum that represents the type of security model\n * encoded by this ISM.\n * @dev Relayers infer how to fetch and format metadata.\n */\n function moduleType() external view returns (uint8);\n\n /**\n * @notice Defines a security model responsible for verifying interchain\n * messages based on the provided metadata.\n * @param _metadata Off-chain metadata provided by a relayer, specific to\n * the security model encoded by the module (e.g. validator signatures)\n * @param _message Hyperlane encoded interchain message\n * @return True if the message was verified\n */\n function verify(\n bytes calldata _metadata,\n bytes calldata _message\n ) external returns (bool);\n}\n\ninterface ISpecifiesInterchainSecurityModule {\n function interchainSecurityModule()\n external\n view\n returns (IInterchainSecurityModule);\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/hooks/IPostDispatchHook.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\ninterface IPostDispatchHook {\n enum HookTypes {\n UNUSED,\n ROUTING,\n AGGREGATION,\n MERKLE_TREE,\n INTERCHAIN_GAS_PAYMASTER,\n FALLBACK_ROUTING,\n ID_AUTH_ISM,\n PAUSABLE,\n PROTOCOL_FEE,\n DEPRECATED,\n RATE_LIMITED,\n ARB_L2_TO_L1,\n OP_L2_TO_L1,\n MAILBOX_DEFAULT_HOOK,\n AMOUNT_ROUTING,\n CCTP,\n TIMELOCK_ROUTING,\n PREDICATE_ROUTER_WRAPPER\n }\n\n /**\n * @notice Returns an enum that represents the type of hook\n */\n function hookType() external view returns (uint8);\n\n /**\n * @notice Returns whether the hook supports metadata\n * @param metadata metadata\n * @return Whether the hook supports metadata\n */\n function supportsMetadata(\n bytes calldata metadata\n ) external view returns (bool);\n\n /**\n * @notice Post action after a message is dispatched via the Mailbox\n * @param metadata The metadata required for the hook\n * @param message The message passed from the Mailbox.dispatch() call\n */\n function postDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) external payable;\n\n /**\n * @notice Compute the payment required by the postDispatch call\n * @dev The returned quote is denominated in a single currency - either native ETH\n * (when metadata.feeToken is address(0) or unspecified) or an ERC-20 token\n * (when metadata.feeToken is set). Mixing fee denominations within a single\n * dispatch is not supported.\n *\n * When feeToken is set, hooks that only support native fees should return 0 or\n * revert via supportsMetadata. The Mailbox.quoteDispatch sums quotes from\n * requiredHook and hook, which assumes both use the same denomination.\n *\n * @param metadata The metadata required for the hook\n * @param message The message passed from the Mailbox.dispatch() call\n * @return Quoted payment for the postDispatch call\n */\n function quoteDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) external view returns (uint256);\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/IMessageRecipient.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\ninterface IMessageRecipient {\n function handle(\n uint32 _origin,\n bytes32 _sender,\n bytes calldata _message\n ) external payable;\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/IMailbox.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nimport {IInterchainSecurityModule} from \"./IInterchainSecurityModule.sol\";\nimport {IPostDispatchHook} from \"./hooks/IPostDispatchHook.sol\";\n\ninterface IMailbox {\n // ============ Events ============\n /**\n * @notice Emitted when a new message is dispatched via Hyperlane\n * @param sender The address that dispatched the message\n * @param destination The destination domain of the message\n * @param recipient The message recipient address on `destination`\n * @param message Raw bytes of message\n */\n event Dispatch(\n address indexed sender,\n uint32 indexed destination,\n bytes32 indexed recipient,\n bytes message\n );\n\n /**\n * @notice Emitted when a new message is dispatched via Hyperlane\n * @param messageId The unique message identifier\n */\n event DispatchId(bytes32 indexed messageId);\n\n /**\n * @notice Emitted when a Hyperlane message is processed\n * @param messageId The unique message identifier\n */\n event ProcessId(bytes32 indexed messageId);\n\n /**\n * @notice Emitted when a Hyperlane message is delivered\n * @param origin The origin domain of the message\n * @param sender The message sender address on `origin`\n * @param recipient The address that handled the message\n */\n event Process(\n uint32 indexed origin,\n bytes32 indexed sender,\n address indexed recipient\n );\n\n function localDomain() external view returns (uint32);\n\n function delivered(bytes32 messageId) external view returns (bool);\n\n /// @notice Returns the block number at which `messageId` was processed,\n /// or 0 if it has not been processed.\n /// @dev Implementation in `Mailbox.sol::processedAt`. The block number is\n /// written to `deliveries[id].blockNumber` inside `process(...)` *before*\n /// the ISM verify call, so within a single `process(...)` transaction,\n /// `processedAt(id) == block.number` is true while the ISM is running.\n function processedAt(bytes32 messageId) external view returns (uint48);\n\n function defaultIsm() external view returns (IInterchainSecurityModule);\n\n function defaultHook() external view returns (IPostDispatchHook);\n\n function requiredHook() external view returns (IPostDispatchHook);\n\n function latestDispatchedId() external view returns (bytes32);\n\n function nonce() external view returns (uint32);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) external view returns (uint256 fee);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata body,\n bytes calldata defaultHookMetadata\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata defaultHookMetadata\n ) external view returns (uint256 fee);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata body,\n bytes calldata customHookMetadata,\n IPostDispatchHook customHook\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata customHookMetadata,\n IPostDispatchHook customHook\n ) external view returns (uint256 fee);\n\n function process(\n bytes calldata metadata,\n bytes calldata message\n ) external payable;\n\n function recipientIsm(\n address recipient\n ) external view returns (IInterchainSecurityModule module);\n}\n"
},
"@hyperlane-xyz/core/contracts/PackageVersioned.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n/**\n * @title PackageVersioned\n * @notice Package version getter for contracts\n **/\nabstract contract PackageVersioned {\n // GENERATED CODE - DO NOT EDIT\n string public constant PACKAGE_VERSION = \"12.1.0\";\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/Merkle.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n// work based on eth2 deposit contract, which is used under CC0-1.0\n\nuint256 constant TREE_DEPTH = 32;\nuint256 constant MAX_LEAVES = 2 ** TREE_DEPTH - 1;\n\n/**\n * @title MerkleLib\n * @author Celo Labs Inc.\n * @notice An incremental merkle tree modeled on the eth2 deposit contract.\n **/\nlibrary MerkleLib {\n /**\n * @notice Struct representing incremental merkle tree. Contains current\n * branch and the number of inserted leaves in the tree.\n **/\n struct Tree {\n bytes32[TREE_DEPTH] branch;\n uint256 count;\n }\n\n /**\n * @notice Inserts `_node` into merkle tree\n * @dev Reverts if tree is full\n * @param _node Element to insert into tree\n **/\n function insert(Tree storage _tree, bytes32 _node) internal {\n require(_tree.count < MAX_LEAVES, \"merkle tree full\");\n\n _tree.count += 1;\n uint256 size = _tree.count;\n for (uint256 i = 0; i < TREE_DEPTH; i++) {\n if ((size & 1) == 1) {\n _tree.branch[i] = _node;\n return;\n }\n _node = keccak256(abi.encodePacked(_tree.branch[i], _node));\n size /= 2;\n }\n // As the loop should always end prematurely with the `return` statement,\n // this code should be unreachable. We assert `false` just to be safe.\n assert(false);\n }\n\n /**\n * @notice Calculates and returns`_tree`'s current root given array of zero\n * hashes\n * @param _zeroes Array of zero hashes\n * @return _current Calculated root of `_tree`\n **/\n function rootWithCtx(\n Tree storage _tree,\n bytes32[TREE_DEPTH] memory _zeroes\n ) internal view returns (bytes32 _current) {\n uint256 _index = _tree.count;\n\n for (uint256 i = 0; i < TREE_DEPTH; i++) {\n uint256 _ithBit = (_index >> i) & 0x01;\n bytes32 _next = _tree.branch[i];\n if (_ithBit == 1) {\n _current = keccak256(abi.encodePacked(_next, _current));\n } else {\n _current = keccak256(abi.encodePacked(_current, _zeroes[i]));\n }\n }\n }\n\n /// @notice Calculates and returns`_tree`'s current root\n function root(Tree storage _tree) internal view returns (bytes32) {\n return rootWithCtx(_tree, zeroHashes());\n }\n\n /// @notice Returns array of TREE_DEPTH zero hashes\n /// @return _zeroes Array of TREE_DEPTH zero hashes\n function zeroHashes()\n internal\n pure\n returns (bytes32[TREE_DEPTH] memory _zeroes)\n {\n _zeroes[0] = Z_0;\n _zeroes[1] = Z_1;\n _zeroes[2] = Z_2;\n _zeroes[3] = Z_3;\n _zeroes[4] = Z_4;\n _zeroes[5] = Z_5;\n _zeroes[6] = Z_6;\n _zeroes[7] = Z_7;\n _zeroes[8] = Z_8;\n _zeroes[9] = Z_9;\n _zeroes[10] = Z_10;\n _zeroes[11] = Z_11;\n _zeroes[12] = Z_12;\n _zeroes[13] = Z_13;\n _zeroes[14] = Z_14;\n _zeroes[15] = Z_15;\n _zeroes[16] = Z_16;\n _zeroes[17] = Z_17;\n _zeroes[18] = Z_18;\n _zeroes[19] = Z_19;\n _zeroes[20] = Z_20;\n _zeroes[21] = Z_21;\n _zeroes[22] = Z_22;\n _zeroes[23] = Z_23;\n _zeroes[24] = Z_24;\n _zeroes[25] = Z_25;\n _zeroes[26] = Z_26;\n _zeroes[27] = Z_27;\n _zeroes[28] = Z_28;\n _zeroes[29] = Z_29;\n _zeroes[30] = Z_30;\n _zeroes[31] = Z_31;\n }\n\n /**\n * @notice Calculates and returns the merkle root for the given leaf\n * `_item`, a merkle branch, and the index of `_item` in the tree.\n * @param _item Merkle leaf\n * @param _branch Merkle proof\n * @param _index Index of `_item` in tree\n * @return _current Calculated merkle root\n **/\n function branchRoot(\n bytes32 _item,\n bytes32[TREE_DEPTH] memory _branch, // cheaper than calldata indexing\n uint256 _index\n ) internal pure returns (bytes32 _current) {\n _current = _item;\n\n for (uint256 i = 0; i < TREE_DEPTH; i++) {\n uint256 _ithBit = (_index >> i) & 0x01;\n // cheaper than calldata indexing _branch[i*32:(i+1)*32];\n bytes32 _next = _branch[i];\n if (_ithBit == 1) {\n _current = keccak256(abi.encodePacked(_next, _current));\n } else {\n _current = keccak256(abi.encodePacked(_current, _next));\n }\n }\n }\n\n /**\n * @notice Calculates and returns the merkle root as if the index is\n * the topmost leaf in the tree.\n * @param _item Merkle leaf\n * @param _branch Merkle proof\n * @param _index Index of `_item` in tree\n * @dev Replaces siblings greater than the index (right subtrees) with zeroes.\n * @return _current Calculated merkle root\n **/\n function reconstructRoot(\n bytes32 _item,\n bytes32[TREE_DEPTH] memory _branch, // cheaper than calldata indexing\n uint256 _index\n ) internal pure returns (bytes32 _current) {\n _current = _item;\n\n bytes32[TREE_DEPTH] memory _zeroes = zeroHashes();\n\n for (uint256 i = 0; i < TREE_DEPTH; i++) {\n uint256 _ithBit = (_index >> i) & 0x01;\n // cheaper than calldata indexing _branch[i*32:(i+1)*32];\n if (_ithBit == 1) {\n _current = keccak256(abi.encodePacked(_branch[i], _current));\n } else {\n // remove right subtree from proof\n _current = keccak256(abi.encodePacked(_current, _zeroes[i]));\n }\n }\n }\n\n // keccak256 zero hashes\n bytes32 internal constant Z_0 =\n hex\"0000000000000000000000000000000000000000000000000000000000000000\";\n bytes32 internal constant Z_1 =\n hex\"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5\";\n bytes32 internal constant Z_2 =\n hex\"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30\";\n bytes32 internal constant Z_3 =\n hex\"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85\";\n bytes32 internal constant Z_4 =\n hex\"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344\";\n bytes32 internal constant Z_5 =\n hex\"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d\";\n bytes32 internal constant Z_6 =\n hex\"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968\";\n bytes32 internal constant Z_7 =\n hex\"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83\";\n bytes32 internal constant Z_8 =\n hex\"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af\";\n bytes32 internal constant Z_9 =\n hex\"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0\";\n bytes32 internal constant Z_10 =\n hex\"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5\";\n bytes32 internal constant Z_11 =\n hex\"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892\";\n bytes32 internal constant Z_12 =\n hex\"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c\";\n bytes32 internal constant Z_13 =\n hex\"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb\";\n bytes32 internal constant Z_14 =\n hex\"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc\";\n bytes32 internal constant Z_15 =\n hex\"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2\";\n bytes32 internal constant Z_16 =\n hex\"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f\";\n bytes32 internal constant Z_17 =\n hex\"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a\";\n bytes32 internal constant Z_18 =\n hex\"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0\";\n bytes32 internal constant Z_19 =\n hex\"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0\";\n bytes32 internal constant Z_20 =\n hex\"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2\";\n bytes32 internal constant Z_21 =\n hex\"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9\";\n bytes32 internal constant Z_22 =\n hex\"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377\";\n bytes32 internal constant Z_23 =\n hex\"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652\";\n bytes32 internal constant Z_24 =\n hex\"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef\";\n bytes32 internal constant Z_25 =\n hex\"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d\";\n bytes32 internal constant Z_26 =\n hex\"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0\";\n bytes32 internal constant Z_27 =\n hex\"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e\";\n bytes32 internal constant Z_28 =\n hex\"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e\";\n bytes32 internal constant Z_29 =\n hex\"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322\";\n bytes32 internal constant Z_30 =\n hex\"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735\";\n bytes32 internal constant Z_31 =\n hex\"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9\";\n}\n"
},
"@hyperlane-xyz/core/contracts/client/MailboxClient.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n// ============ Internal Imports ============\nimport {IMailbox} from \"../interfaces/IMailbox.sol\";\nimport {IPostDispatchHook} from \"../interfaces/hooks/IPostDispatchHook.sol\";\nimport {IInterchainSecurityModule} from \"../interfaces/IInterchainSecurityModule.sol\";\nimport {Message} from \"../libs/Message.sol\";\nimport {PackageVersioned} from \"../PackageVersioned.sol\";\n\n// ============ External Imports ============\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nabstract contract MailboxClient is OwnableUpgradeable, PackageVersioned {\n using Message for bytes;\n\n event HookSet(address _hook);\n event IsmSet(address _ism);\n\n IMailbox public immutable mailbox;\n\n uint32 public immutable localDomain;\n\n IPostDispatchHook public hook;\n\n IInterchainSecurityModule internal _interchainSecurityModule;\n\n uint256[48] private __GAP; // gap for upgrade safety\n\n // ============ Modifiers ============\n modifier onlyContract(address _contract) {\n require(\n Address.isContract(_contract),\n \"MailboxClient: invalid mailbox\"\n );\n _;\n }\n\n modifier onlyContractOrNull(address _contract) {\n require(\n Address.isContract(_contract) || _contract == address(0),\n \"MailboxClient: invalid contract setting\"\n );\n _;\n }\n\n /**\n * @notice Only accept messages from a Hyperlane Mailbox contract\n */\n modifier onlyMailbox() {\n require(\n msg.sender == address(mailbox),\n \"MailboxClient: sender not mailbox\"\n );\n _;\n }\n\n constructor(address _mailbox) onlyContract(_mailbox) {\n mailbox = IMailbox(_mailbox);\n localDomain = mailbox.localDomain();\n _transferOwnership(msg.sender);\n }\n\n function interchainSecurityModule()\n external\n view\n virtual\n returns (IInterchainSecurityModule)\n {\n return _interchainSecurityModule;\n }\n\n /**\n * @notice Sets the address of the application's custom hook.\n * @param _hook The address of the hook contract.\n */\n function setHook(\n address _hook\n ) public virtual onlyContractOrNull(_hook) onlyOwner {\n hook = IPostDispatchHook(_hook);\n emit HookSet(_hook);\n }\n\n /**\n * @notice Sets the address of the application's custom interchain security module.\n * @param _module The address of the interchain security module contract.\n */\n function setInterchainSecurityModule(\n address _module\n ) public onlyContractOrNull(_module) onlyOwner {\n _interchainSecurityModule = IInterchainSecurityModule(_module);\n emit IsmSet(_module);\n }\n\n // ======== Initializer =========\n function _MailboxClient_initialize(\n address _hook,\n address __interchainSecurityModule,\n address _owner\n ) internal onlyInitializing {\n __Ownable_init();\n setHook(_hook);\n setInterchainSecurityModule(__interchainSecurityModule);\n _transferOwnership(_owner);\n }\n\n function _isLatestDispatched(bytes32 id) internal view returns (bool) {\n return mailbox.latestDispatchedId() == id;\n }\n\n function _isDelivered(bytes32 id) internal view returns (bool) {\n return mailbox.delivered(id);\n }\n\n /// @dev True only while `mailbox.process()` is delivering `id` in the\n /// current transaction. `process(...)` writes `deliveries[id].blockNumber`\n /// before invoking the ISM, so this binds a check to the message being\n /// processed *now* — stricter than `_isDelivered`, which stays true for any\n /// previously-delivered message.\n function _isProcessing(bytes32 id) internal view returns (bool) {\n return mailbox.processedAt(id) == block.number;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/hooks/libs/AbstractPostDispatchHook.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\n\n// ============ Internal Imports ============\nimport {StandardHookMetadata} from \"./StandardHookMetadata.sol\";\nimport {IPostDispatchHook} from \"../../interfaces/hooks/IPostDispatchHook.sol\";\nimport {PackageVersioned} from \"../../PackageVersioned.sol\";\nimport {Message} from \"../../libs/Message.sol\";\n\n/**\n * @title AbstractPostDispatch\n * @notice Abstract post dispatch hook supporting the current global hook metadata variant.\n * @dev Hooks that charge fees denominated in native tokens should override\n * `supportsMetadata` to reject metadata containing a non-zero fee token address.\n * This prevents denomination mixing when `Mailbox.quoteDispatch` sums quotes from\n * multiple hooks (e.g. `requiredHook` + `hook`), since the return type is a single\n * `uint256` with no token denomination indicator.\n */\nabstract contract AbstractPostDispatchHook is\n IPostDispatchHook,\n PackageVersioned\n{\n using StandardHookMetadata for bytes;\n using Message for bytes;\n using Address for address payable;\n\n // ============ External functions ============\n\n /// @inheritdoc IPostDispatchHook\n /// @dev By default, accepts any valid variant-1 metadata including metadata\n /// with a non-zero fee token. Hooks that charge non-zero native-token fees\n /// should override this to return false when `metadata.feeToken() != address(0)`,\n /// ensuring callers cannot mix native and ERC20 fee denominations.\n function supportsMetadata(\n bytes calldata metadata\n ) public view virtual returns (bool) {\n return\n metadata.length == 0 ||\n metadata.variant() == StandardHookMetadata.VARIANT;\n }\n\n function _refund(\n bytes calldata metadata,\n bytes calldata message,\n uint256 amount\n ) internal {\n if (amount == 0) {\n return;\n }\n\n address refundAddress = metadata.refundAddress(message.senderAddress());\n require(\n refundAddress != address(0),\n \"AbstractPostDispatchHook: no refund address\"\n );\n payable(refundAddress).sendValue(amount);\n }\n\n /// @inheritdoc IPostDispatchHook\n function postDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) external payable override {\n require(\n supportsMetadata(metadata),\n \"AbstractPostDispatchHook: invalid metadata variant\"\n );\n _postDispatch(metadata, message);\n }\n\n /// @inheritdoc IPostDispatchHook\n function quoteDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) public view override returns (uint256) {\n require(\n supportsMetadata(metadata),\n \"AbstractPostDispatchHook: invalid metadata variant\"\n );\n return _quoteDispatch(metadata, message);\n }\n\n // ============ Internal functions ============\n\n /**\n * @notice Post dispatch hook implementation.\n * @param metadata The metadata of the message being dispatched.\n * @param message The message being dispatched.\n */\n function _postDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) internal virtual;\n\n /**\n * @notice Quote dispatch hook implementation.\n * @param metadata The metadata of the message being dispatched.\n * @param message The message being dispatched.\n * @return The quote for the dispatch.\n */\n function _quoteDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) internal view virtual returns (uint256);\n}\n"
},
"@hyperlane-xyz/core/contracts/hooks/libs/StandardHookMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n/**\n * Format of metadata:\n *\n * [0:2] variant (uint16) = 1\n * [2:34] msg.value (uint256)\n * [34:66] Gas limit for message (uint256)\n * [66:86] Refund address (address)\n * [86:106] Fee token address (address) - OPTIONAL, read if length >= 106\n *\n * Fee Token Semantics:\n * - When feeToken is address(0) or unspecified (metadata length < 106), fees are\n * paid in native ETH via msg.value.\n * - When feeToken is set to a non-zero address, fees are paid in that ERC-20 token.\n * The caller must approve the hook to spend the fee token before calling dispatch.\n *\n * IMPORTANT: Mixing fee denominations within a single dispatch is NOT supported.\n * All hooks in the call chain (requiredHook + hook, including any child hooks in\n * aggregation) must use the same fee denomination. Hooks that only support native\n * fees will reject metadata with a non-zero feeToken via supportsMetadata.\n *\n * The Mailbox.quoteDispatch function sums quotes from requiredHook and hook,\n * assuming both return values in the same denomination. This works because:\n * - Native-only hooks return 0 when feeToken is set (via supportsMetadata rejection)\n * - The requiredHook (typically ProtocolFee) returns 0 when protocolFee is 0, allowing\n * ERC-20 fee tokens to be used with the default hook even when requiredHook exists\n */\n\nlibrary StandardHookMetadata {\n struct Metadata {\n uint16 variant;\n uint256 msgValue;\n uint256 gasLimit;\n address refundAddress;\n }\n\n uint8 private constant VARIANT_OFFSET = 0;\n uint8 private constant MSG_VALUE_OFFSET = 2;\n uint8 private constant GAS_LIMIT_OFFSET = 34;\n uint8 private constant REFUND_ADDRESS_OFFSET = 66;\n uint8 private constant FEE_TOKEN_OFFSET = 86;\n\n uint16 public constant VARIANT = 1;\n\n /**\n * @notice Returns the variant of the metadata.\n * @param _metadata ABI encoded standard hook metadata.\n * @return variant of the metadata as uint16.\n */\n function variant(bytes calldata _metadata) internal pure returns (uint16) {\n if (_metadata.length < VARIANT_OFFSET + 2) return 0;\n return uint16(bytes2(_metadata[VARIANT_OFFSET:VARIANT_OFFSET + 2]));\n }\n\n /**\n * @notice Returns the specified value for the message.\n * @param _metadata ABI encoded standard hook metadata.\n * @param _default Default fallback value.\n * @return Value for the message as uint256.\n */\n function msgValue(\n bytes calldata _metadata,\n uint256 _default\n ) internal pure returns (uint256) {\n if (_metadata.length < MSG_VALUE_OFFSET + 32) return _default;\n return\n uint256(bytes32(_metadata[MSG_VALUE_OFFSET:MSG_VALUE_OFFSET + 32]));\n }\n\n /**\n * @notice Returns the specified gas limit for the message.\n * @param _metadata ABI encoded standard hook metadata.\n * @param _default Default fallback gas limit.\n * @return Gas limit for the message as uint256.\n */\n function gasLimit(\n bytes calldata _metadata,\n uint256 _default\n ) internal pure returns (uint256) {\n if (_metadata.length < GAS_LIMIT_OFFSET + 32) return _default;\n return\n uint256(bytes32(_metadata[GAS_LIMIT_OFFSET:GAS_LIMIT_OFFSET + 32]));\n }\n\n function gasLimit(\n bytes memory _metadata\n ) internal pure returns (uint256 _gasLimit) {\n if (_metadata.length < GAS_LIMIT_OFFSET + 32) return 50_000;\n assembly {\n _gasLimit := mload(add(_metadata, add(0x20, GAS_LIMIT_OFFSET)))\n }\n }\n\n /**\n * @notice Returns the specified refund address for the message.\n * @param _metadata ABI encoded standard hook metadata.\n * @param _default Default fallback refund address.\n * @return Refund address for the message as address.\n */\n function refundAddress(\n bytes calldata _metadata,\n address _default\n ) internal pure returns (address) {\n if (_metadata.length < REFUND_ADDRESS_OFFSET + 20) return _default;\n return\n address(\n bytes20(\n _metadata[REFUND_ADDRESS_OFFSET:REFUND_ADDRESS_OFFSET + 20]\n )\n );\n }\n\n /**\n * @notice Returns the fee token address for token-based gas payments.\n * @param _metadata ABI encoded standard hook metadata.\n * @param _default Default fallback fee token (typically address(0) for native).\n * @return Fee token address at [86:106], or _default if metadata too short.\n */\n function feeToken(\n bytes calldata _metadata,\n address _default\n ) internal pure returns (address) {\n if (_metadata.length < FEE_TOKEN_OFFSET + 20) return _default;\n return\n address(bytes20(_metadata[FEE_TOKEN_OFFSET:FEE_TOKEN_OFFSET + 20]));\n }\n\n /**\n * @notice Returns the fee token address for token-based gas payments (memory version).\n * @param _metadata ABI encoded standard hook metadata.\n * @return _feeToken Fee token address at [86:106], or address(0) if metadata too short.\n */\n function feeToken(\n bytes memory _metadata\n ) internal pure returns (address _feeToken) {\n if (_metadata.length < FEE_TOKEN_OFFSET + 20) return address(0);\n assembly {\n let data_start_ptr := add(_metadata, 32) // Skip length prefix\n let mload_ptr := add(data_start_ptr, sub(FEE_TOKEN_OFFSET, 12))\n _feeToken := mload(mload_ptr) // Loads 32 bytes; address takes lower 20 bytes\n }\n }\n\n /**\n * @notice Formats the specified gas limit and refund address into standard hook metadata.\n * @param _msgValue msg.value for the message.\n * @param _gasLimit Gas limit for the message.\n * @param _refundAddress Refund address for the message.\n * @return ABI encoded standard hook metadata.\n */\n function format(\n uint256 _msgValue,\n uint256 _gasLimit,\n address _refundAddress\n ) internal pure returns (bytes memory) {\n return abi.encodePacked(VARIANT, _msgValue, _gasLimit, _refundAddress);\n }\n\n /**\n * @notice Formats the specified gas limit and refund address into standard hook metadata.\n * @param _msgValue msg.value for the message.\n * @param _gasLimit Gas limit for the message.\n * @param _refundAddress Refund address for the message.\n * @param _customMetadata Additional metadata to include in the standard hook metadata.\n * @return ABI encoded standard hook metadata.\n */\n function formatMetadata(\n uint256 _msgValue,\n uint256 _gasLimit,\n address _refundAddress,\n bytes memory _customMetadata\n ) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n VARIANT,\n _msgValue,\n _gasLimit,\n _refundAddress,\n _customMetadata\n );\n }\n\n /**\n * @notice Formats the specified gas limit and refund address into standard hook metadata.\n * @param _msgValue msg.value for the message.\n * @return ABI encoded standard hook metadata.\n */\n function overrideMsgValue(\n uint256 _msgValue\n ) internal view returns (bytes memory) {\n return formatMetadata(_msgValue, uint256(0), msg.sender, \"\");\n }\n\n /**\n * @notice Formats the specified gas limit and refund address into standard hook metadata.\n * @param _gasLimit Gas limit for the message.\n * @return ABI encoded standard hook metadata.\n */\n function overrideGasLimit(\n uint256 _gasLimit\n ) internal view returns (bytes memory) {\n return formatMetadata(uint256(0), _gasLimit, msg.sender, \"\");\n }\n\n /**\n * @notice Formats the specified refund address into standard hook metadata.\n * @param _refundAddress Refund address for the message.\n * @return ABI encoded standard hook metadata.\n */\n function overrideRefundAddress(\n address _refundAddress\n ) internal pure returns (bytes memory) {\n return formatMetadata(uint256(0), uint256(0), _refundAddress, \"\");\n }\n\n /**\n * @notice Formats metadata with fee token for token-based gas payments.\n * @param _msgValue msg.value for the message.\n * @param _gasLimit Gas limit for the message.\n * @param _refundAddress Refund address for the message.\n * @param _feeToken Fee token address for gas payment.\n * @return ABI encoded hook metadata with fee token at [86:106].\n */\n function formatWithFeeToken(\n uint256 _msgValue,\n uint256 _gasLimit,\n address _refundAddress,\n address _feeToken\n ) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n VARIANT,\n _msgValue,\n _gasLimit,\n _refundAddress,\n _feeToken\n );\n }\n\n function getRefundAddress(\n bytes memory _metadata,\n address _default\n ) internal pure returns (address) {\n if (_metadata.length < REFUND_ADDRESS_OFFSET + 20) return _default;\n address result;\n assembly {\n let data_start_ptr := add(_metadata, 32) // Skip length prefix of _metadata\n let mload_ptr := add(data_start_ptr, sub(REFUND_ADDRESS_OFFSET, 12))\n result := mload(mload_ptr) // Loads 32 bytes; address takes lower 20 bytes.\n }\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/access/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
},
"@openzeppelin/contracts/security/Pausable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/aggregation/StaticAggregationIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {AbstractAggregationIsm} from \"./AbstractAggregationIsm.sol\";\nimport {MetaProxy} from \"../../libs/MetaProxy.sol\";\n\n/**\n * @title StaticAggregationIsm\n * @notice Manages per-domain m-of-n ISM sets that are used to verify\n * interchain messages.\n */\ncontract StaticAggregationIsm is AbstractAggregationIsm {\n // ============ Public Functions ============\n\n /**\n * @notice Returns the set of ISMs responsible for verifying _message\n * and the number of ISMs that must verify\n * @dev Can change based on the content of _message\n * @return modules The array of ISM addresses\n * @return threshold The number of ISMs needed to verify\n */\n function modulesAndThreshold(\n bytes calldata\n ) public view override returns (address[] memory, uint8) {\n return abi.decode(MetaProxy.metadata(), (address[], uint8));\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/StaticAddressSetFactory.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n// ============ External Imports ============\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {Create2} from \"@openzeppelin/contracts/utils/Create2.sol\";\n\n// ============ Internal Imports ============\nimport {MetaProxy} from \"./MetaProxy.sol\";\nimport {PackageVersioned} from \"../PackageVersioned.sol\";\nimport {IThresholdAddressFactory} from \"../interfaces/IThresholdAddressFactory.sol\";\n\nabstract contract StaticThresholdAddressSetFactory is\n PackageVersioned,\n IThresholdAddressFactory\n{\n // ============ Immutables ============\n address public immutable implementation;\n\n // ============ Constructor ============\n\n constructor() {\n implementation = _deployImplementation();\n }\n\n function _deployImplementation() internal virtual returns (address);\n\n /**\n * @notice Deploys a StaticThresholdAddressSet contract address for the given\n * values\n * @dev Consider sorting addresses to ensure contract reuse\n * @param _values An array of addresses\n * @param _threshold The threshold value to use\n * @return set The contract address representing this StaticThresholdAddressSet\n */\n function deploy(\n address[] calldata _values,\n uint8 _threshold\n ) public returns (address) {\n require(\n 0 < _threshold && _threshold <= _values.length,\n \"Invalid threshold\"\n );\n (bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(\n _values,\n _threshold\n );\n address _set = _getAddress(_salt, _bytecode);\n if (!Address.isContract(_set)) {\n _set = Create2.deploy(0, _salt, _bytecode);\n }\n return _set;\n }\n\n /**\n * @notice Returns the StaticThresholdAddressSet contract address for the given\n * values\n * @dev Consider sorting addresses to ensure contract reuse\n * @param _values An array of addresses\n * @param _threshold The threshold value to use\n * @return set The contract address representing this StaticThresholdAddressSet\n */\n function getAddress(\n address[] calldata _values,\n uint8 _threshold\n ) external view returns (address) {\n (bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(\n _values,\n _threshold\n );\n return _getAddress(_salt, _bytecode);\n }\n\n /**\n * @notice Returns the StaticThresholdAddressSet contract address for the given\n * values\n * @param _salt The salt used in Create2\n * @param _bytecode The metaproxy bytecode used in Create2\n * @return set The contract address representing this StaticThresholdAddressSet\n */\n function _getAddress(\n bytes32 _salt,\n bytes memory _bytecode\n ) internal view returns (address) {\n bytes32 _bytecodeHash = keccak256(_bytecode);\n return Create2.computeAddress(_salt, _bytecodeHash);\n }\n\n /**\n * @notice Returns the create2 salt and bytecode for the given values\n * @param _values An array of addresses\n * @param _threshold The threshold value to use\n * @return _salt The salt used in Create2\n * @return _bytecode The metaproxy bytecode used in Create2\n */\n function _saltAndBytecode(\n address[] calldata _values,\n uint8 _threshold\n ) internal view returns (bytes32, bytes memory) {\n bytes memory _metadata = abi.encode(_values, _threshold);\n bytes memory _bytecode = MetaProxy.bytecode(implementation, _metadata);\n bytes32 _salt = keccak256(_metadata);\n return (_salt, _bytecode);\n }\n}\n\nabstract contract StaticAddressSetFactory is StaticThresholdAddressSetFactory {\n /**\n * @notice Deploys a StaticAddressSet contract address for the given\n * values\n * @dev Consider sorting addresses to ensure contract reuse\n * @param _values An array of addresses\n * @return set The contract address representing this StaticAddressSet\n */\n function deploy(address[] calldata _values) external returns (address) {\n return super.deploy(_values, uint8(_values.length));\n }\n\n /**\n * @notice Returns the StaticAddressSet contract address for the given\n * values\n * @dev Consider sorting addresses to ensure contract reuse\n * @param _values An array of addresses\n * @return set The contract address representing this StaticAddressSet\n */\n function getAddress(\n address[] calldata _values\n ) external view returns (address) {\n (bytes32 _salt, bytes memory _bytecode) = _saltAndBytecode(\n _values,\n uint8(_values.length)\n );\n return super._getAddress(_salt, _bytecode);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/multisig/AbstractMultisigIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n// ============ External Imports ============\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\n// ============ Internal Imports ============\nimport {IMultisigIsm} from \"../../interfaces/isms/IMultisigIsm.sol\";\nimport {PackageVersioned} from \"../../PackageVersioned.sol\";\n\n/**\n * @title AbstractMultisig\n * @notice Manages per-domain m-of-n Validator sets\n * @dev See ./AbstractMerkleRootMultisigIsm.sol and ./AbstractMessageIdMultisigIsm.sol\n * for concrete implementations of `digest` and `signatureAt`.\n * @dev See ./StaticMultisigIsm.sol for concrete implementations.\n */\nabstract contract AbstractMultisig is PackageVersioned {\n /**\n * @notice Returns the digest to be used for signature verification.\n * @param _metadata ABI encoded module metadata\n * @param _message Formatted Hyperlane message (see Message.sol).\n * @return digest The digest to be signed by validators\n */\n function digest(\n bytes calldata _metadata,\n bytes calldata _message\n ) internal view virtual returns (bytes32);\n\n /**\n * @notice Returns the signature at a given index from the metadata.\n * @param _metadata ABI encoded module metadata\n * @param _index The index of the signature to return\n * @return signature Packed encoding of signature (65 bytes)\n */\n function signatureAt(\n bytes calldata _metadata,\n uint256 _index\n ) internal pure virtual returns (bytes calldata);\n\n /**\n * @notice Returns the number of signatures in the metadata.\n * @param _metadata ABI encoded module metadata\n * @return count The number of signatures\n */\n function signatureCount(\n bytes calldata _metadata\n ) public pure virtual returns (uint256);\n}\n\n/**\n * @title AbstractMultisigIsm\n * @notice Manages per-domain m-of-n Validator sets of AbstractMultisig that are used to verify\n * interchain messages.\n */\nabstract contract AbstractMultisigIsm is AbstractMultisig, IMultisigIsm {\n // ============ Virtual Functions ============\n // ======= OVERRIDE THESE TO IMPLEMENT =======\n\n /**\n * @notice Returns the set of validators responsible for verifying _message\n * and the number of signatures required\n * @dev Can change based on the content of _message\n * @dev Signatures provided to `verify` must be consistent with validator ordering\n * @param _message Hyperlane formatted interchain message\n * @return validators The array of validator addresses\n * @return threshold The number of validator signatures needed\n */\n function validatorsAndThreshold(\n bytes calldata _message\n ) public view virtual returns (address[] memory, uint8);\n\n // ============ Public Functions ============\n\n /**\n * @notice Requires that m-of-n validators verify a merkle root,\n * and verifies a merkle proof of `_message` against that root.\n * @dev Optimization relies on the caller sorting signatures in the same order as validators.\n * @dev Employs https://www.geeksforgeeks.org/two-pointers-technique/ to minimize gas usage.\n * @param _metadata ABI encoded module metadata\n * @param _message Formatted Hyperlane message (see Message.sol).\n */\n function verify(\n bytes calldata _metadata,\n bytes calldata _message\n ) public view returns (bool) {\n bytes32 _digest = digest(_metadata, _message);\n (\n address[] memory _validators,\n uint8 _threshold\n ) = validatorsAndThreshold(_message);\n require(_threshold > 0, \"No MultisigISM threshold present for message\");\n\n uint256 _validatorCount = _validators.length;\n uint256 _validatorIndex = 0;\n // Assumes that signatures are ordered by validator\n for (uint256 i = 0; i < _threshold; ++i) {\n address _signer = ECDSA.recover(_digest, signatureAt(_metadata, i));\n // Loop through remaining validators until we find a match\n while (\n _validatorIndex < _validatorCount &&\n _signer != _validators[_validatorIndex]\n ) {\n ++_validatorIndex;\n }\n // Fail if we never found a match\n require(_validatorIndex < _validatorCount, \"!threshold\");\n ++_validatorIndex;\n }\n return true;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/multisig/AbstractMerkleRootMultisigIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {AbstractMultisig} from \"./AbstractMultisigIsm.sol\";\nimport {MerkleRootMultisigIsmMetadata} from \"../../isms/libs/MerkleRootMultisigIsmMetadata.sol\";\nimport {Message} from \"../../libs/Message.sol\";\nimport {MerkleLib} from \"../../libs/Merkle.sol\";\nimport {CheckpointLib} from \"../../libs/CheckpointLib.sol\";\n\n/**\n * @title `AbstractMerkleRootMultisigIsm` — multi-sig ISM with the validators-censorship resistance guarantee.\n * @notice This ISM allows using a newer signed checkpoint (say #33) to prove existence of an older message (#22) in the validators' MerkleTree.\n * This guarantees censorship resistance as validators cannot hide a message\n * by refusing to sign its checkpoint but later signing a checkpoint for a newer message.\n * If validators decide to censor a message, they are left with only one option — to not produce checkpoints at all.\n * Otherwise, the very next signed checkpoint (#33) can be used by any relayer to prove the previous message inclusion using this ISM.\n * This is censorship resistance is missing in the sibling implementation `AbstractMessageIdMultisigIsm`,\n * since it can only verify messages having the corresponding checkpoints.\n * @dev Provides the default implementation of verifying signatures over a checkpoint and the message inclusion in that checkpoint.\n * This abstract contract can be overridden for customizing the `validatorsAndThreshold()` (static or dynamic).\n * @dev May be adapted in future to support batch message verification against a single root.\n */\nabstract contract AbstractMerkleRootMultisigIsm is AbstractMultisig {\n using MerkleRootMultisigIsmMetadata for bytes;\n using Message for bytes;\n\n // ============ Constants ============\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function digest(\n bytes calldata _metadata,\n bytes calldata _message\n ) internal pure override returns (bytes32) {\n require(\n _metadata.messageIndex() <= _metadata.signedIndex(),\n \"Invalid merkle index metadata\"\n );\n // We verify a merkle proof of (messageId, index) I to compute root J\n bytes32 _signedRoot = MerkleLib.branchRoot(\n _message.id(),\n _metadata.proof(),\n _metadata.messageIndex()\n );\n // We provide (messageId, index) J in metadata for digest derivation\n return\n CheckpointLib.digest(\n _message.origin(),\n _metadata.originMerkleTreeHook(),\n _signedRoot,\n _metadata.signedIndex(),\n _metadata.signedMessageId()\n );\n }\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function signatureAt(\n bytes calldata _metadata,\n uint256 _index\n ) internal pure override returns (bytes calldata) {\n return _metadata.signatureAt(_index);\n }\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function signatureCount(\n bytes calldata _metadata\n ) public pure override returns (uint256) {\n return _metadata.signatureCount();\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/multisig/AbstractMessageIdMultisigIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {AbstractMultisig} from \"./AbstractMultisigIsm.sol\";\nimport {MessageIdMultisigIsmMetadata} from \"../libs/MessageIdMultisigIsmMetadata.sol\";\nimport {Message} from \"../../libs/Message.sol\";\nimport {CheckpointLib} from \"../../libs/CheckpointLib.sol\";\n\n/**\n * @title `AbstractMessageIdMultisigIsm` — multi-sig ISM for the censorship-friendly validators.\n * @notice This ISM minimizes gas/performance overhead of the checkpoints verification by compromising on the censorship resistance.\n * For censorship resistance consider using `AbstractMerkleRootMultisigIsm`.\n * If the validators (`validatorsAndThreshold`) skip messages by not sign checkpoints for them,\n * the relayers will not be able to aggregate a quorum of signatures sufficient to deliver these messages via this ISM.\n * Integrations are free to choose the trade-off between the censorship resistance and the gas/processing overhead.\n * @dev Provides the default implementation of verifying signatures over a checkpoint related to a specific message ID.\n * This abstract contract can be customized to change the `validatorsAndThreshold()` (static or dynamic).\n */\nabstract contract AbstractMessageIdMultisigIsm is AbstractMultisig {\n using Message for bytes;\n using MessageIdMultisigIsmMetadata for bytes;\n\n // ============ Constants ============\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function digest(\n bytes calldata _metadata,\n bytes calldata _message\n ) internal pure override returns (bytes32) {\n return\n CheckpointLib.digest(\n _message.origin(),\n _metadata.originMerkleTreeHook(),\n _metadata.root(),\n _metadata.index(),\n _message.id()\n );\n }\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function signatureAt(\n bytes calldata _metadata,\n uint256 _index\n ) internal pure override returns (bytes calldata) {\n return _metadata.signatureAt(_index);\n }\n\n /**\n * @inheritdoc AbstractMultisig\n */\n function signatureCount(\n bytes calldata _metadata\n ) public pure override returns (uint256) {\n return _metadata.signatureCount();\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/MetaProxy.sol": {
"content": "// SPDX-License-Identifier: CC0-1.0\npragma solidity >=0.7.6;\n\n/// @dev Adapted from https://eips.ethereum.org/EIPS/eip-3448\nlibrary MetaProxy {\n bytes32 private constant PREFIX =\n hex\"600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73\";\n bytes13 private constant SUFFIX = hex\"5af43d3d93803e603457fd5bf3\";\n\n function bytecode(\n address _implementation,\n bytes memory _metadata\n ) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n PREFIX,\n bytes20(_implementation),\n SUFFIX,\n _metadata,\n _metadata.length\n );\n }\n\n function metadata() internal pure returns (bytes memory) {\n bytes memory data;\n assembly {\n let posOfMetadataSize := sub(calldatasize(), 32)\n let size := calldataload(posOfMetadataSize)\n let dataPtr := sub(posOfMetadataSize, size)\n data := mload(64)\n // increment free memory pointer by metadata size + 32 bytes (length)\n mstore(64, add(data, add(size, 32)))\n mstore(data, size)\n let memPtr := add(data, 32)\n calldatacopy(memPtr, dataPtr, size)\n }\n return data;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/TokenRouter.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {TypeCasts} from \"../../libs/TypeCasts.sol\";\nimport {GasRouter} from \"../../client/GasRouter.sol\";\nimport {TokenMessage} from \"./TokenMessage.sol\";\nimport {Quote, ITokenBridge, ITokenFee} from \"../../interfaces/ITokenBridge.sol\";\nimport {Quotes} from \"./Quotes.sol\";\nimport {StandardHookMetadata} from \"../../hooks/libs/StandardHookMetadata.sol\";\n\n// ============ External Imports ============\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {StorageSlot} from \"@openzeppelin/contracts/utils/StorageSlot.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n/**\n * @title Hyperlane Token Router that extends Router with abstract token (ERC20/ERC721) remote transfer functionality.\n * @dev Overridable functions:\n * - token(): specify the managed token address\n * - _transferFromSender(uint256): pull tokens/ETH from msg.sender\n * - _transferTo(address,uint256): send tokens/ETH to the recipient\n * - _externalFeeAmount(uint32,bytes32,uint256): compute external fees (default returns 0)\n * @dev Override transferRemote only to implement custom logic that can't be accomplished with the above functions.\n *\n * @author Abacus Works\n */\nabstract contract TokenRouter is GasRouter, ITokenBridge {\n using TypeCasts for bytes32;\n using TypeCasts for address;\n using TokenMessage for bytes;\n using StandardHookMetadata for bytes;\n using StorageSlot for bytes32;\n using Quotes for Quote[];\n using Math for uint256;\n using SafeERC20 for IERC20;\n\n /**\n * @dev Emitted on `transferRemote` when a transfer message is dispatched.\n * @param destination The identifier of the destination chain.\n * @param recipient The address of the recipient on the destination chain.\n * @param amountOrId The amount or ID of tokens sent in to the remote recipient.\n */\n event SentTransferRemote(\n uint32 indexed destination,\n bytes32 indexed recipient,\n uint256 amountOrId\n );\n\n /**\n * @dev Emitted on `_handle` when a transfer message is processed.\n * @param origin The identifier of the origin chain.\n * @param recipient The address of the recipient on the destination chain.\n * @param amountOrId The amount or ID of tokens received from the remote sender.\n */\n event ReceivedTransferRemote(\n uint32 indexed origin,\n bytes32 indexed recipient,\n uint256 amountOrId\n );\n\n uint256 public immutable scaleNumerator;\n uint256 public immutable scaleDenominator;\n\n // cannot use compiler assigned slot without\n // breaking backwards compatibility of storage layout\n bytes32 private constant FEE_RECIPIENT_SLOT =\n keccak256(\"FungibleTokenRouter.feeRecipient\");\n bytes32 private constant FEE_HOOK_SLOT = keccak256(\"TokenRouter.feeHook\");\n\n event FeeRecipientSet(address feeRecipient);\n event FeeHookSet(address feeHook);\n\n constructor(\n uint256 _scaleNumerator,\n uint256 _scaleDenominator,\n address _mailbox\n ) GasRouter(_mailbox) {\n require(\n _scaleNumerator > 0 && _scaleDenominator > 0,\n \"TokenRouter: scale cannot be 0\"\n );\n scaleNumerator = _scaleNumerator;\n scaleDenominator = _scaleDenominator;\n }\n\n // ===========================\n // ========== Main API ==========\n // ===========================\n\n /**\n * @notice Returns the address of the token managed by this router. It can be one of three options:\n * - ERC20 token address for fungible tokens that are being collateralized (HypERC20Collateral, HypERC4626, etc.)\n * - 0x0 address for native tokens (ETH, MATIC, etc.) (HypNative, etc.)\n * - address(this) for synthetic ERC20 tokens (HypERC20, etc.)\n * It is being used for quotes and fees from the fee recipient and pulling/push the tokens from the sender/receipient.\n * @dev This function must be implemented by derived contracts to specify the token address.\n * @return The address of the token contract.\n */\n function token() public view virtual returns (address);\n\n /**\n * @inheritdoc ITokenFee\n * @notice Implements the standardized fee quoting interface for token transfers based on\n * overridable internal functions of _quoteGasPayment, _feeRecipientAndAmount, and _externalFeeAmount.\n * @param _destination The identifier of the destination chain.\n * @param _recipient The address of the recipient on the destination chain.\n * @param _amount The amount or identifier of tokens to be sent to the remote recipient\n * @return quotes An array of Quote structs representing the fees in different tokens.\n * @dev This function may return multiple quotes with the same denomination. Convention is to return:\n * [index 0] native fees charged by the mailbox dispatch\n * [index 1] then any internal warp route fees (amount bridged plus fee recipient)\n * [index 2] then any external bridging fees (if any, else 0)\n * These are surfaced as separate elements to enable clients to interpret/render fees independently.\n * There is a Quotes library with an extract function for onchain quoting in a specific denomination,\n * but we discourage onchain quoting in favor of offchain quoting and overpaying with refunds.\n */\n function quoteTransferRemote(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) external view virtual override returns (Quote[] memory quotes) {\n address _feeToken = feeToken();\n quotes = new Quote[](3);\n quotes[0] = Quote({\n token: _feeToken, // address(0) for native, token() for ERC20 payments\n amount: _quoteGasPayment(\n _destination,\n _recipient,\n _amount,\n _feeToken\n )\n });\n (, uint256 feeAmount) = _feeRecipientAndAmount(\n _destination,\n _recipient,\n _amount\n );\n quotes[1] = Quote({token: token(), amount: _amount + feeAmount});\n quotes[2] = Quote({\n token: token(),\n amount: _externalFeeAmount(_destination, _recipient, _amount)\n });\n }\n\n /**\n * @notice Transfers `_amount` token to `_recipient` on the `_destination` domain.\n * @dev Delegates transfer logic to `_transferFromSender` implementation.\n * Emits `SentTransferRemote` event on the origin chain.\n * Override with custom behavior for storing or forwarding tokens.\n * Known overrides:\n * - OPL2ToL1TokenBridgeNative: adds hook metadata for message dispatch.\n * - EverclearTokenBridge: creates Everclear intent for cross-chain token transfer.\n * - TokenBridgeCctpBase: adds CCTP-specific metadata for message dispatch.\n * - HypERC4626Collateral: deposits into vault and handles shares.\n * When overriding, mirror the general flow of this function for consistency:\n * 1. Calculate fees and charge the sender.\n * 2. Prepare the token message with recipient, amount, and any additional metadata.\n * 3. Emit `SentTransferRemote` event.\n * 4. Dispatch the message.\n * @param _destination The identifier of the destination chain.\n * @param _recipient The address of the recipient on the destination chain.\n * @param _amount The amount or identifier of tokens to be sent to the remote recipient.\n * @return messageId The identifier of the dispatched message.\n */\n function transferRemote(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) public payable virtual returns (bytes32 messageId) {\n return _transferRemote(_destination, _recipient, _amount);\n }\n\n /// @notice Internal transfer implementation.\n function _transferRemote(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) internal virtual returns (bytes32 messageId) {\n address _feeHook = feeHook();\n address _feeToken = feeToken();\n\n // 1. Calculate the fee amounts, charge the sender and distribute to feeRecipient if necessary\n (, uint256 remainingNativeValue) = _calculateFeesAndCharge(\n _destination,\n _recipient,\n _amount,\n msg.value,\n _feeHook\n );\n\n uint256 scaledAmount = _outboundAmount(_amount);\n\n // 2. Prepare the token message with the recipient and amount\n bytes memory _tokenMessage = TokenMessage.format(\n _recipient,\n scaledAmount\n );\n\n messageId = _emitAndDispatch(\n _destination,\n _recipient,\n scaledAmount,\n remainingNativeValue,\n _tokenMessage,\n _feeToken\n );\n }\n\n // ===========================\n // ========== Internal convenience functions for readability ==========\n // ==========================\n\n function _calculateFeesAndCharge(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount,\n uint256 _msgValue,\n address _feeHook\n ) internal returns (uint256 externalFee, uint256 remainingNativeValue) {\n (address _feeRecipient, uint256 feeAmount) = _feeRecipientAndAmount(\n _destination,\n _recipient,\n _amount\n );\n externalFee = _externalFeeAmount(_destination, _recipient, _amount);\n uint256 charge = _amount + feeAmount + externalFee;\n\n address _token = token();\n\n // ERC20 fee hook: use token() for gas payments\n if (_feeHook != address(0)) {\n uint256 hookFee = _quoteGasPayment(\n _destination,\n _recipient,\n _amount,\n _token\n );\n\n // For collateral routers (token() != address(this)), we can add hook fee to charge\n // because _transferFromSender pulls tokens TO the router.\n // For synthetic routers (token() == address(this)), we must pull separately\n // because _transferFromSender burns tokens, so router never receives them.\n if (_token != address(this)) {\n // Collateral router: add hook fee to charge\n charge += hookFee;\n } else {\n // Synthetic router: pull hook fee tokens separately\n IERC20(_token).safeTransferFrom(\n msg.sender,\n address(this),\n hookFee\n );\n }\n\n // Per-call approval only: standing approvals to fee hooks are unsafe\n // because postDispatch is publicly callable with arbitrary message data,\n // allowing a third party to spend the approval. Funds would go to the\n // hook beneficiary (not the attacker), but the caller still loses tokens.\n IERC20(_token).forceApprove(_feeHook, hookFee);\n }\n\n _transferFromSender(charge);\n\n if (feeAmount > 0) {\n // transfer atomically so we don't need to keep track of collateral\n // and fee balances separately\n _transferFee(_feeRecipient, feeAmount);\n }\n\n // Calculate remaining native value for other hooks\n // When token() is ERC20 (non-native), all native value is available for other hooks\n // When token() is native (address(0)), subtract the charge from msg.value\n remainingNativeValue = _token != address(0)\n ? _msgValue\n : _msgValue - charge;\n }\n\n // Convenience overload that computes feeHook() internally.\n function _calculateFeesAndCharge(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount,\n uint256 _msgValue\n ) internal returns (uint256 externalFee, uint256 remainingNativeValue) {\n return\n _calculateFeesAndCharge(\n _destination,\n _recipient,\n _amount,\n _msgValue,\n feeHook()\n );\n }\n\n // Emits the SentTransferRemote event and dispatches the message with explicit feeToken.\n function _emitAndDispatch(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount,\n uint256 _messageDispatchValue,\n bytes memory _tokenMessage,\n address _feeToken\n ) internal returns (bytes32 messageId) {\n // effects\n emit SentTransferRemote(_destination, _recipient, _amount);\n\n // interactions\n messageId = _Router_dispatch(\n _destination,\n _messageDispatchValue,\n _tokenMessage,\n _generateHookMetadata(_destination, _feeToken),\n address(hook)\n );\n }\n\n // Convenience overload that computes feeToken from feeHook().\n function _emitAndDispatch(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount,\n uint256 _messageDispatchValue,\n bytes memory _tokenMessage\n ) internal returns (bytes32 messageId) {\n address _feeToken = feeToken();\n return\n _emitAndDispatch(\n _destination,\n _recipient,\n _amount,\n _messageDispatchValue,\n _tokenMessage,\n _feeToken\n );\n }\n\n // ===========================\n // ========== Fees & Quoting ==========\n // ===========================\n\n /**\n * @notice Sets the fee recipient for the router.\n * @dev Allows for address(0) to be set, which disables fees.\n * @param recipient The address that receives fees.\n */\n function setFeeRecipient(address recipient) public onlyOwner {\n require(recipient != address(this), \"Fee recipient cannot be self\");\n FEE_RECIPIENT_SLOT.getAddressSlot().value = recipient;\n emit FeeRecipientSet(recipient);\n }\n\n /**\n * @notice Returns the address of the fee recipient.\n * @dev Returns address(0) if no fee recipient is set.\n * @dev Can be overridden with address(0) to disable fees entirely.\n * @return address of the fee recipient.\n */\n function feeRecipient() public view virtual returns (address) {\n return FEE_RECIPIENT_SLOT.getAddressSlot().value;\n }\n\n /**\n * @notice Initializes the TokenRouter with fee hook configuration.\n * @param _feeHook The fee hook contract address.\n */\n function _TokenRouter_initialize(address _feeHook) internal {\n _setFeeHook(_feeHook);\n }\n\n /**\n * @notice Sets the fee hook contract address.\n * @param _feeHook The fee hook address.\n */\n function setFeeHook(address _feeHook) external onlyOwner {\n _setFeeHook(_feeHook);\n }\n\n /**\n * @notice Internal function to set the fee hook address.\n * @param _feeHook The fee hook address.\n */\n function _setFeeHook(address _feeHook) internal {\n if (_feeHook != address(0)) {\n require(\n token() != address(0),\n \"TokenRouter: fee hook requires ERC20 token\"\n );\n }\n FEE_HOOK_SLOT.getAddressSlot().value = _feeHook;\n emit FeeHookSet(_feeHook);\n }\n\n /**\n * @notice Returns the fee hook contract address.\n * @return The fee hook address.\n */\n function feeHook() public view returns (address) {\n return FEE_HOOK_SLOT.getAddressSlot().value;\n }\n\n /**\n * @notice Returns the fee token address for gas payments.\n * @return The token address if a fee hook is configured, otherwise address(0) for native payments.\n */\n function feeToken() public view returns (address) {\n return feeHook() != address(0) ? token() : address(0);\n }\n\n // To be overridden by derived contracts if they have additional fees\n /**\n * @notice Returns the external fee amount for the given parameters.\n * param _destination The identifier of the destination chain.\n * param _recipient The address of the recipient on the destination chain.\n * param _amount The amount or identifier of tokens to be sent to the remote recipient\n * @return feeAmount The external fee amount.\n * @dev This fee must be denominated in the `token()` defined by this router.\n * @dev The default implementation returns 0, meaning no external fees are charged.\n * This function is intended to be overridden by derived contracts that have additional fees.\n * Known overrides:\n * - TokenBridgeCctpBase: for CCTP-specific fees\n * - EverclearTokenBridge: for Everclear-specific fees\n */\n function _externalFeeAmount(\n uint32, // _destination,\n bytes32, // _recipient,\n uint256 // _amount\n ) internal view virtual returns (uint256 feeAmount) {\n return 0;\n }\n\n /**\n * @notice Returns the fee recipient amount for the given parameters.\n * @param _destination The identifier of the destination chain.\n * @param _recipient The address of the recipient on the destination chain.\n * @param _amount The amount or identifier of tokens to be sent to the remote recipient\n * @return _feeRecipient The address of the fee recipient.\n * @return feeAmount The fee recipient amount.\n * @dev This function is is not intended to be overridden as storage and logic is contained in TokenRouter.\n */\n function _feeRecipientAndAmount(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) internal view returns (address _feeRecipient, uint256 feeAmount) {\n _feeRecipient = feeRecipient();\n if (_feeRecipient == address(0)) {\n return (_feeRecipient, 0);\n }\n\n Quote[] memory quotes = ITokenFee(_feeRecipient).quoteTransferRemote(\n _destination,\n _recipient,\n _amount\n );\n if (quotes.length == 0) {\n return (_feeRecipient, 0);\n }\n\n require(\n quotes.length == 1 && quotes[0].token == token(),\n \"FungibleTokenRouter: fee must match token\"\n );\n feeAmount = quotes[0].amount;\n }\n\n /**\n * @notice Returns the gas payment required to dispatch a message to the given domain's router.\n * @param _destination The identifier of the destination chain.\n * @param _recipient The address of the recipient on the destination chain.\n * @param _amount The amount or identifier of tokens to be sent to the remote recipient\n * @return payment How much value to send in transferRemote call (native or feeToken based on config).\n * @dev This function is intended to be overridden by derived contracts that trigger multiple messages.\n * Known overrides:\n * - OPL2ToL1TokenBridgeNative: Quote for two messages (prove and finalize).\n */\n function _quoteGasPayment(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount,\n address _feeToken\n ) internal view virtual returns (uint256) {\n return\n _Router_quoteDispatch(\n _destination,\n TokenMessage.format(_recipient, _outboundAmount(_amount)),\n _generateHookMetadata(_destination, _feeToken),\n address(hook)\n );\n }\n\n /**\n * @notice Generates hook metadata for dispatch, including feeToken if configured.\n * @param _destination The destination chain.\n * @param _feeToken The fee token address (address(0) for native).\n * @return Hook metadata with the specified feeToken.\n */\n function _generateHookMetadata(\n uint32 _destination,\n address _feeToken\n ) internal view returns (bytes memory) {\n uint256 gasLimit = destinationGas[_destination];\n return\n StandardHookMetadata.formatWithFeeToken(\n 0,\n gasLimit,\n msg.sender,\n _feeToken\n );\n }\n\n // ===========================\n // ========== Internal virtual functions for token handling ==========\n // ===========================\n\n /**\n * @dev Should transfer `_amount` of tokens from `msg.sender` to this token router.\n * Called by `transferRemote` before message dispatch.\n * Known overrides:\n * - HypERC20: Burns the tokens from the sender.\n * - HypERC20Collateral: Pulls the tokens from the sender.\n * - HypNative: Asserts msg.value >= _amount\n * - TokenBridgeCctpBase: (like HypERC20Collateral) Pulls the tokens from the sender.\n * - EverclearEthTokenBridge: Wraps the native token (ETH) to WETH\n * - HypERC4626: Converts the amounts to shares and burns from the User (via HypERC20 implementation)\n * - HypFiatToken: Pulls the tokens from the sender and burns them on the FiatToken contract.\n * - HypXERC20: Burns the tokens from the sender.\n * - HypXERC20Lockbox: Pulls the tokens from the sender, locks them in the XERC20Lockbox contract and burns the resulting xERC20 tokens.\n */\n function _transferFromSender(uint256 _amountOrId) internal virtual;\n\n /**\n * @dev Should transfer `_amountOrId` of tokens from this token router to `_recipient`.\n * @dev Called by `handle` after message decoding.\n * Known overrides:\n * - HypERC20: Mints the tokens to the recipient.\n * - HypERC20Collateral: Releases the tokens to the recipient.\n * - HypNative: Releases native tokens to the recipient.\n * - TokenBridgeCctpBase: Do nothing (CCTP transfers tokens to the recipient directly).\n * - EverclearEthTokenBridge: Unwraps WETH to ETH and sends to the recipient.\n * - HypERC4626: Converts the amount to shares and mints to the User (via HypERC20 implementation)\n * - HypFiatToken: Mints the tokens to the recipient on the FiatToken contract.\n * - HypXERC20: Mints the tokens to the recipient.\n * - HypXERC20Lockbox: Withdraws the underlying tokens from the Lockbox and sends to the recipient.\n * - OpL1NativeTokenBridge: Do nothing (the L2 bridge transfers the native tokens to the recipient directly).\n */\n function _transferTo(\n address _recipient,\n uint256 _amountOrId\n ) internal virtual;\n\n /**\n * @dev Should transfer `_amount` of tokens from this token router to the fee recipient.\n * @dev Called by `_calculateFeesAndCharge` when fee recipient is set and feeAmount > 0.\n * @dev The default implementation delegates to `_transferTo`, which works for most token routers\n * where tokens are held by the router (e.g., collateral routers, synthetic token routers).\n * @dev Override this function for bridges where tokens are NOT held by the router but fees still\n * need to be paid (e.g., CCTP, Everclear). In those cases, use direct token transfers from the\n * router's balance collected via `_transferFromSender`.\n * Known overrides:\n * - TokenBridgeCctpBase: Directly transfers tokens from router balance.\n * - EverclearTokenBridge: Directly transfers tokens from router balance.\n */\n function _transferFee(\n address _recipient,\n uint256 _amount\n ) internal virtual {\n _transferTo(_recipient, _amount);\n }\n\n /**\n * @dev Scales local amount to message amount by the scale fraction.\n * Applies: messageAmount = (localAmount * scaleNumerator) / scaleDenominator\n * - If scaleNumerator > scaleDenominator: scales up (e.g., 2/1)\n * - If scaleNumerator < scaleDenominator: scales down (e.g., 1/2)\n * - If scaleNumerator == scaleDenominator: no scaling (e.g., 1/1)\n * Known overrides:\n * - HypERC4626: Scales by exchange rate\n */\n function _outboundAmount(\n uint256 _localAmount\n ) internal view virtual returns (uint256 _messageAmount) {\n _messageAmount = _localAmount.mulDiv(\n scaleNumerator,\n scaleDenominator,\n Math.Rounding.Down\n );\n }\n\n /**\n * @dev Scales message amount to local amount by the inverse scale fraction.\n * Applies: localAmount = (messageAmount * scaleDenominator) / scaleNumerator\n * - If scaleNumerator > scaleDenominator: scales down (e.g., 1/2 for 2/1 outbound)\n * - If scaleNumerator < scaleDenominator: scales up (e.g., 2/1 for 1/2 outbound)\n * - If scaleNumerator == scaleDenominator: no scaling (e.g., 1/1)\n * Known overrides:\n * - HypERC4626: Scales by exchange rate\n */\n function _inboundAmount(\n uint256 _messageAmount\n ) internal view virtual returns (uint256 _localAmount) {\n _localAmount = _messageAmount.mulDiv(\n scaleDenominator,\n scaleNumerator,\n Math.Rounding.Down\n );\n }\n\n /**\n * @notice Handles the incoming transfer message.\n * It decodes the message, emits the ReceivedTransferRemote event, and transfers tokens to the recipient.\n * @param _origin The identifier of the origin chain.\n * @dev param _sender The address of the sender router on the origin chain.\n * @param _message The message data containing recipient and amount.\n * @dev Override this function if custom logic is required for sending out the tokens.\n * Known overrides:\n * - EverclearTokenBridge: Receives the tokens and sends them to the recipient.\n * - EverclearEthBridge: Receives WETH, unwraps it and sends native ETH to the recipient.\n * - HypERC4626: Updates the exchange rate from the metadata\n */\n // solhint-disable-next-line hyperlane/no-virtual-override\n function _handle(\n uint32 _origin,\n bytes32,\n bytes calldata _message\n ) internal virtual override {\n bytes32 recipient = _message.recipient();\n uint256 amount = _message.amount();\n\n // effects\n emit ReceivedTransferRemote(_origin, recipient, amount);\n\n // interactions\n _transferTo(recipient.bytes32ToAddress(), _inboundAmount(amount));\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/ITokenBridge.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nstruct Quote {\n address token; // address(0) for the native token, or ERC20 for token payments\n uint256 amount;\n}\n\ninterface ITokenFee {\n /**\n * @notice Provide the value transfer quote\n * @param _destination The destination domain of the message\n * @param _recipient The message recipient address on `destination`\n * @param _amount The amount to send to the recipient\n * @return quotes Indicate how much of each token to approve and/or send.\n * @dev Good practice is to use the first entry of the quotes for the IGP fee (native or ERC20).\n * @dev Good practice is to use the last entry of the quotes for the token to be transferred.\n * @dev There should not be duplicate `token` addresses in the returned quotes.\n */\n function quoteTransferRemote(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) external view returns (Quote[] memory quotes);\n}\n\ninterface ITokenBridge is ITokenFee {\n /**\n * @notice Transfer value to another domain\n * @param _destination The destination domain of the message\n * @param _recipient The message recipient address on `destination`\n * @param _amount The amount to send to the recipient\n * @return messageId The identifier of the dispatched message.\n */\n function transferRemote(\n uint32 _destination,\n bytes32 _recipient,\n uint256 _amount\n ) external payable returns (bytes32);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(address from, address to, uint256 amount) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[45] private __gap;\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/TokenMessage.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nlibrary TokenMessage {\n uint8 internal constant RECIPIENT_OFFSET = 0;\n uint8 internal constant AMOUNT_OFFSET = 32;\n uint8 internal constant METADATA_OFFSET = 64;\n\n function format(\n bytes32 _recipient,\n uint256 _amount,\n bytes memory _metadata\n ) internal pure returns (bytes memory) {\n return abi.encodePacked(_recipient, _amount, _metadata);\n }\n\n function format(\n bytes32 _recipient,\n uint256 _amount\n ) internal pure returns (bytes memory) {\n return abi.encodePacked(_recipient, _amount);\n }\n\n function recipient(bytes calldata message) internal pure returns (bytes32) {\n return bytes32(message[RECIPIENT_OFFSET:RECIPIENT_OFFSET + 32]);\n }\n\n function amount(bytes calldata message) internal pure returns (uint256) {\n return uint256(bytes32(message[AMOUNT_OFFSET:AMOUNT_OFFSET + 32]));\n }\n\n // alias for ERC721\n function tokenId(bytes calldata message) internal pure returns (uint256) {\n return amount(message);\n }\n\n function metadata(\n bytes calldata message\n ) internal pure returns (bytes calldata) {\n return message[METADATA_OFFSET:];\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/MovableCollateralRouter.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity >=0.8.0;\n\nimport {ITokenBridge, Quote} from \"../../interfaces/ITokenBridge.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {TokenRouter} from \"./TokenRouter.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {Router} from \"../../client/Router.sol\";\nimport {Quotes} from \"./Quotes.sol\";\n\nstruct MovableCollateralRouterStorage {\n // TODO: replace the single recipient override with a per-domain recipient\n // set when routes need multiple allowed same-chain rebalance recipients.\n mapping(uint32 routerDomain => bytes32 recipient) recipient;\n mapping(uint32 routerDomain => EnumerableSet.AddressSet bridges) bridges;\n EnumerableSet.AddressSet rebalancers;\n}\n\nabstract contract MovableCollateralRouter is TokenRouter {\n using SafeERC20 for IERC20;\n using EnumerableSet for EnumerableSet.AddressSet;\n using Quotes for Quote[];\n\n MovableCollateralRouterStorage internal allowed;\n\n /// @dev For a move driven by `AtomicLocalRebalancingBridge`, `recipient` is\n /// this router's configured recipient rather than the address the bridge\n /// funds, and `amount` is the source outflow rather than the (decimal-\n /// converted) amount delivered. Off-chain consumers should read the bridge's\n /// `LocalRebalanceExecuted` event for that flow instead.\n event CollateralMoved(\n uint32 indexed domain,\n bytes32 recipient,\n uint256 amount,\n address indexed rebalancer\n );\n\n modifier onlyRebalancer() {\n require(isAllowedRebalancer(_msgSender()), \"MCR: Only Rebalancer\");\n _;\n }\n\n modifier onlyAllowedBridge(uint32 domain, ITokenBridge bridge) {\n EnumerableSet.AddressSet storage bridges = allowed.bridges[domain];\n require(bridges.contains(address(bridge)), \"MCR: Not allowed bridge\");\n _;\n }\n\n /// @notice Set of addresses that are allowed to rebalance.\n function allowedRebalancers() external view returns (address[] memory) {\n return allowed.rebalancers.values();\n }\n\n /// @notice Returns whether an address is allowed to rebalance.\n function isAllowedRebalancer(\n address rebalancer\n ) public view returns (bool) {\n return allowed.rebalancers.contains(rebalancer);\n }\n\n /// @notice Mapping of domain to allowed rebalance recipient.\n /// @dev Keys constrained to a subset of Router.domains()\n function allowedRecipient(uint32 domain) external view returns (bytes32) {\n return allowed.recipient[domain];\n }\n\n /// @notice Mapping of domain to allowed rebalance bridges.\n /// @dev Keys constrained to a subset of Router.domains()\n function allowedBridges(\n uint32 domain\n ) external view returns (address[] memory) {\n return allowed.bridges[domain].values();\n }\n\n function setRecipient(\n uint32 domain,\n bytes32 recipient\n ) external virtual onlyOwner {\n // constrain to a subset of Router.domains()\n _mustHaveRemoteRouter(domain);\n allowed.recipient[domain] = recipient;\n }\n\n function removeRecipient(uint32 domain) external onlyOwner {\n delete allowed.recipient[domain];\n }\n\n function addBridge(\n uint32 domain,\n ITokenBridge bridge\n ) external virtual onlyOwner {\n // constrain to a subset of Router.domains()\n _mustHaveRemoteRouter(domain);\n _addBridge(domain, bridge);\n }\n\n function _addBridge(uint32 domain, ITokenBridge bridge) internal virtual {\n allowed.bridges[domain].add(address(bridge));\n }\n\n function removeBridge(\n uint32 domain,\n ITokenBridge bridge\n ) external onlyOwner {\n _removeBridge(domain, bridge);\n }\n\n function _removeBridge(\n uint32 domain,\n ITokenBridge bridge\n ) internal virtual {\n allowed.bridges[domain].remove(address(bridge));\n }\n\n /**\n * @notice Clears legacy standing token approval for a bridge.\n * @custom:deprecated Despite the name this revokes rather than approves.\n * `rebalance` grants exact per-call approval from the bridge quote;\n * the selector is retained so existing upgrade / governance tooling\n * stays compatible and can clear old max allowances.\n */\n function approveTokenForBridge(\n IERC20 token,\n ITokenBridge bridge\n ) external onlyOwner {\n // Revokes the allowance; it does not approve.\n token.forceApprove(address(bridge), 0);\n }\n\n function addRebalancer(address rebalancer) external onlyOwner {\n allowed.rebalancers.add(rebalancer);\n }\n\n function removeRebalancer(address rebalancer) external onlyOwner {\n allowed.rebalancers.remove(rebalancer);\n }\n\n /**\n * @notice Rebalances the collateral between router domains.\n * @param domain The domain to rebalance to.\n * @param collateralAmount The amount of collateral to rebalance.\n * @param bridge The bridge to use for the rebalance.\n * @dev The caller must be an allowed rebalancer and the bridge must be an allowed bridge for the domain.\n * @dev The recipient is the enrolled router if no recipient is set for the domain.\n */\n function rebalance(\n uint32 domain,\n uint256 collateralAmount,\n ITokenBridge bridge\n ) external payable onlyRebalancer onlyAllowedBridge(domain, bridge) {\n bytes32 recipient = _recipient(domain);\n\n Quote[] memory quotes = bridge.quoteTransferRemote(\n domain,\n recipient,\n collateralAmount\n );\n\n address collateralToken = token();\n\n // charge the rebalancer any bridging fees denominated in the collateral\n // token to avoid undercollateralization\n uint256 collateralFees = quotes.extract(collateralToken);\n if (collateralFees > collateralAmount) {\n _transferFromSender(collateralFees - collateralAmount);\n }\n\n // need to handle native quote separately from collateral quote because\n // token() may be address(0), in which case we need to use address(this).balance\n // to move native collateral tokens across chains\n uint256 nativeFees = quotes.extract(address(0));\n if (nativeFees > address(this).balance) {\n revert(\"Rebalance native fee exceeds balance\");\n }\n\n // Grant only the route collateral amount for this transfer. Expected\n // bridges consume the full quoted collateral allowance.\n if (collateralToken != address(0)) {\n IERC20(collateralToken).forceApprove(\n address(bridge),\n collateralFees\n );\n }\n\n bridge.transferRemote{value: nativeFees}(\n domain,\n recipient,\n collateralAmount\n );\n\n // Revoke any allowance the bridge did not consume.\n if (collateralToken != address(0)) {\n IERC20(collateralToken).forceApprove(address(bridge), 0);\n }\n\n emit CollateralMoved(domain, recipient, collateralAmount, msg.sender);\n }\n\n function _recipient(\n uint32 domain\n ) internal view returns (bytes32 recipient) {\n recipient = allowed.recipient[domain];\n if (recipient == bytes32(0)) {\n recipient = _mustHaveRemoteRouter(domain);\n }\n }\n\n /// @dev This function in `EnumerableSet` was introduced in OpenZeppelin v5. We are using 4.9\n /// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.3.0-rc.0/contracts/utils/structs/EnumerableSet.sol#L126\n function _clear(EnumerableSet.Set storage set) private {\n uint256 len = set._values.length;\n for (uint256 i = 0; i < len; ++i) {\n delete set._indexes[set._values[i]];\n }\n _unsafeSetLength(set._values, 0);\n }\n\n /// @dev A helper for `_clear`. See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/39f5a0284e7eb539354e44b76fcbb69033b22b56/contracts/utils/Arrays.sol#L466\n function _unsafeSetLength(bytes32[] storage array, uint256 len) internal {\n assembly (\"memory-safe\") {\n sstore(array.slot, len)\n }\n }\n\n /// @dev Constrains keys of rebalance mappings to Router.domains()\n function _unenrollRemoteRouter(uint32 domain) internal override {\n Router._unenrollRemoteRouter(domain);\n if (!_MovableCollateralRouter_hasRebalanceRoutes(domain)) {\n _clearRebalanceState(domain);\n }\n }\n\n /// @dev Whether `domain` still has any route that can drive a rebalance.\n /// Base tracks only classic remote routers; `CrossCollateralRouter` also\n /// considers its cross-collateral routes.\n function _MovableCollateralRouter_hasRebalanceRoutes(\n uint32 domain\n ) internal view virtual returns (bool) {\n return routers(domain) != bytes32(0);\n }\n\n /// @dev Clears the rebalance config (recipient + allowed bridges) for a\n /// domain that no longer has any route, so a removed route cannot retain\n /// rebalance authority.\n function _clearRebalanceState(uint32 domain) internal {\n delete allowed.recipient[domain];\n _clear(allowed.bridges[domain]._inner);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/LpCollateralRouter.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {MovableCollateralRouter, MovableCollateralRouterStorage} from \"./MovableCollateralRouter.sol\";\n\n// ============ External Imports ============\nimport {ERC4626Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol\";\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nstruct LpCollateralRouterStorage {\n // MovableCollateralRouter layout\n MovableCollateralRouterStorage __MOVABLE_COLLATERAL_GAP;\n // ERC4626 layout\n // - (ERC20 layout)\n mapping(address => uint256) _balances;\n mapping(address => mapping(address => uint256)) _allowances;\n uint256 _totalSupply;\n string _name;\n string _symbol;\n // @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:376\n uint256[45] __ERC20_GAP;\n // - (ERC4626 layout)\n address _asset;\n uint8 _underlyingDecimals;\n // @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol:267\n uint256[49] __ERC4626_GAP;\n // user defined fields\n uint256 lpAssets;\n}\n\nabstract contract LpCollateralRouter is\n MovableCollateralRouter,\n ERC4626Upgradeable\n{\n uint256 private lpAssets;\n\n event Donation(address sender, uint256 amount);\n\n function _LpCollateralRouter_initialize() internal onlyInitializing {\n __ERC4626_init(IERC20Upgradeable(token()));\n }\n\n function totalAssets() public view override returns (uint256) {\n return lpAssets;\n }\n\n function asset() public view override returns (address) {\n return token();\n }\n\n // modeled after ERC4626Upgradeable._deposit\n function _deposit(\n address caller,\n address receiver,\n uint256 assets,\n uint256 shares\n ) internal override {\n // checks\n _transferFromSender(assets);\n\n // effects\n lpAssets += assets;\n\n // interactions\n _mint(receiver, shares);\n\n emit Deposit(caller, receiver, assets, shares);\n }\n\n // modeled after ERC4626Upgradeable._withdraw\n function _withdraw(\n address caller,\n address receiver,\n address owner,\n uint256 assets,\n uint256 shares\n ) internal override {\n // checks\n if (caller != owner) {\n _spendAllowance(owner, caller, shares);\n }\n _burn(owner, shares);\n\n // effects\n lpAssets -= assets;\n\n // interactions\n _transferTo(receiver, assets);\n\n emit Withdraw(caller, receiver, owner, assets, shares);\n }\n\n // can be used to distribute rewards to LPs pro rata\n function donate(uint256 amount) public payable {\n // checks\n _transferFromSender(amount);\n\n // effects\n lpAssets += amount;\n emit Donation(msg.sender, amount);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/TokenCollateral.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity >=0.8.0;\n\nimport {IWETH} from \"../interfaces/IWETH.sol\";\n\n// ============ External Imports ============\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\n\n/**\n * @title Handles deposits and withdrawals of native token collateral.\n */\nlibrary NativeCollateral {\n function _transferFromSender(uint256 _amount) internal {\n require(msg.value >= _amount, \"Native: amount exceeds msg.value\");\n }\n\n function _transferTo(address _recipient, uint256 _amount) internal {\n Address.sendValue(payable(_recipient), _amount);\n }\n}\n\n/**\n * @title Handles deposits and withdrawals of WETH collateral.\n * @dev TokenRouters must have `token() == address(0)` to use this library.\n */\nlibrary WETHCollateral {\n function _transferFromSender(IWETH token, uint256 _amount) internal {\n NativeCollateral._transferFromSender(_amount);\n token.deposit{value: _amount}();\n }\n\n function _transferTo(\n IWETH token,\n address _recipient,\n uint256 _amount\n ) internal {\n token.withdraw(_amount);\n NativeCollateral._transferTo(_recipient, _amount);\n }\n}\n\n/**\n * @title Handles deposits and withdrawals of ERC20 collateral.\n */\nlibrary ERC20Collateral {\n using SafeERC20 for IERC20;\n\n function _transferFromSender(IERC20 token, uint256 _amount) internal {\n token.safeTransferFrom(msg.sender, address(this), _amount);\n }\n\n function _transferTo(\n IERC20 token,\n address _recipient,\n uint256 _amount\n ) internal {\n token.safeTransfer(_recipient, _amount);\n }\n}\n\n/**\n * @title Handles deposits and withdrawals of ERC721 collateral.\n */\nlibrary ERC721Collateral {\n function _transferFromSender(IERC721 token, uint256 _tokenId) internal {\n // safeTransferFrom not used here because recipient is this contract\n token.transferFrom(msg.sender, address(this), _tokenId);\n }\n\n function _transferTo(\n IERC721 token,\n address _recipient,\n uint256 _tokenId\n ) internal {\n token.safeTransferFrom(address(this), _recipient, _tokenId);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/EnumerableMapExtended.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n// ============ External Imports ============\nimport \"@openzeppelin/contracts/utils/structs/EnumerableMap.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\n// extends EnumerableMap with uint256 => bytes32 type\n// modelled after https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/utils/structs/EnumerableMap.sol\nlibrary EnumerableMapExtended {\n using EnumerableMap for EnumerableMap.Bytes32ToBytes32Map;\n using EnumerableSet for EnumerableSet.Bytes32Set;\n\n struct UintToBytes32Map {\n EnumerableMap.Bytes32ToBytes32Map _inner;\n }\n\n // ============ Library Functions ============\n function keys(\n UintToBytes32Map storage map\n ) internal view returns (uint256[] memory _keys) {\n uint256 _length = map._inner.length();\n _keys = new uint256[](_length);\n for (uint256 i = 0; i < _length; i++) {\n _keys[i] = uint256(map._inner._keys.at(i));\n }\n }\n\n function uint32Keys(\n UintToBytes32Map storage map\n ) internal view returns (uint32[] memory _keys) {\n uint256[] memory uint256keys = keys(map);\n _keys = new uint32[](uint256keys.length);\n for (uint256 i = 0; i < uint256keys.length; i++) {\n _keys[i] = uint32(uint256keys[i]);\n }\n }\n\n function set(\n UintToBytes32Map storage map,\n uint256 key,\n bytes32 value\n ) internal {\n map._inner.set(bytes32(key), value);\n }\n\n function get(\n UintToBytes32Map storage map,\n uint256 key\n ) internal view returns (bytes32) {\n return map._inner.get(bytes32(key));\n }\n\n function tryGet(\n UintToBytes32Map storage map,\n uint256 key\n ) internal view returns (bool, bytes32) {\n return map._inner.tryGet(bytes32(key));\n }\n\n function remove(\n UintToBytes32Map storage map,\n uint256 key\n ) internal returns (bool) {\n return map._inner.remove(bytes32(key));\n }\n\n function contains(\n UintToBytes32Map storage map,\n uint256 key\n ) internal view returns (bool) {\n return map._inner.contains(bytes32(key));\n }\n\n function length(\n UintToBytes32Map storage map\n ) internal view returns (uint256) {\n return map._inner.length();\n }\n\n function at(\n UintToBytes32Map storage map,\n uint256 index\n ) internal view returns (uint256, bytes32) {\n (bytes32 key, bytes32 value) = map._inner.at(index);\n return (uint256(key), value);\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n }\n}\n"
},
"@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/aggregation/AbstractAggregationIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n// ============ Internal Imports ============\nimport {IInterchainSecurityModule} from \"../../interfaces/IInterchainSecurityModule.sol\";\nimport {IAggregationIsm} from \"../../interfaces/isms/IAggregationIsm.sol\";\nimport {AggregationIsmMetadata} from \"../../isms/libs/AggregationIsmMetadata.sol\";\nimport {PackageVersioned} from \"../../PackageVersioned.sol\";\n\n/**\n * @title AggregationIsm\n * @notice Manages per-domain m-of-n ISM sets that are used to verify\n * interchain messages.\n */\nabstract contract AbstractAggregationIsm is IAggregationIsm, PackageVersioned {\n // ============ Constants ============\n\n // solhint-disable-next-line const-name-snakecase\n uint8 public constant moduleType =\n uint8(IInterchainSecurityModule.Types.AGGREGATION);\n\n // ============ Virtual Functions ============\n // ======= OVERRIDE THESE TO IMPLEMENT =======\n\n /**\n * @notice Returns the set of ISMs responsible for verifying _message\n * and the number of ISMs that must verify\n * @dev Can change based on the content of _message\n * @param _message Hyperlane formatted interchain message\n * @return modules The array of ISM addresses\n * @return threshold The number of ISMs needed to verify\n */\n function modulesAndThreshold(\n bytes calldata _message\n ) public view virtual returns (address[] memory, uint8);\n\n // ============ Public Functions ============\n\n /**\n * @notice Requires that m-of-n ISMs verify the provided interchain message.\n * @param _metadata ABI encoded module metadata (see AggregationIsmMetadata.sol)\n * @param _message Formatted Hyperlane message (see Message.sol).\n */\n function verify(\n bytes calldata _metadata,\n bytes calldata _message\n ) public returns (bool) {\n (address[] memory _isms, uint8 _threshold) = modulesAndThreshold(\n _message\n );\n uint256 _count = _isms.length;\n for (uint8 i = 0; i < _count; i++) {\n if (!AggregationIsmMetadata.hasMetadata(_metadata, i)) continue;\n IInterchainSecurityModule _ism = IInterchainSecurityModule(\n _isms[i]\n );\n require(\n _ism.verify(\n AggregationIsmMetadata.metadataAt(_metadata, i),\n _message\n ),\n \"!verify\"\n );\n _threshold -= 1;\n }\n require(_threshold == 0, \"!threshold\");\n return true;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Create2.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n /// @solidity memory-safe-assembly\n assembly {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n }\n require(addr != address(0), \"Create2: Failed on deploy\");\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40) // Get free memory pointer\n\n // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |\n // |-------------------|---------------------------------------------------------------------------|\n // | bytecodeHash | CCCCCCCCCCCCC...CC |\n // | salt | BBBBBBBBBBBBB...BB |\n // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |\n // | 0xFF | FF |\n // |-------------------|---------------------------------------------------------------------------|\n // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n mstore(add(ptr, 0x40), bytecodeHash)\n mstore(add(ptr, 0x20), salt)\n mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n mstore8(start, 0xff)\n addr := keccak256(start, 85)\n }\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/IThresholdAddressFactory.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\ninterface IThresholdAddressFactory {\n function deploy(\n address[] calldata _values,\n uint8 _threshold\n ) external returns (address);\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/libs/MerkleRootMultisigIsmMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/**\n * Format of metadata:\n * [ 0: 32] Origin merkle tree address\n * [ 32: 36] Index of message ID in merkle tree\n * [ 36: 68] Signed checkpoint message ID\n * [ 68:1092] Merkle proof\n * [1092:1096] Signed checkpoint index (computed from proof and index)\n * [1096:????] Validator signatures (length := threshold * 65)\n */\nlibrary MerkleRootMultisigIsmMetadata {\n uint8 private constant ORIGIN_MERKLE_TREE_OFFSET = 0;\n uint8 private constant MESSAGE_INDEX_OFFSET = 32;\n uint8 private constant MESSAGE_ID_OFFSET = 36;\n uint8 private constant MERKLE_PROOF_OFFSET = 68;\n uint16 private constant MERKLE_PROOF_LENGTH = 32 * 32;\n uint16 private constant SIGNED_INDEX_OFFSET = 1092;\n uint16 private constant SIGNATURES_OFFSET = 1096;\n uint8 private constant SIGNATURE_LENGTH = 65;\n\n /**\n * @notice Returns the origin merkle tree hook of the signed checkpoint as bytes32.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Origin merkle tree hook of the signed checkpoint as bytes32\n */\n function originMerkleTreeHook(\n bytes calldata _metadata\n ) internal pure returns (bytes32) {\n return\n bytes32(\n _metadata[ORIGIN_MERKLE_TREE_OFFSET:ORIGIN_MERKLE_TREE_OFFSET +\n 32]\n );\n }\n\n /**\n * @notice Returns the index of the message being proven.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Index of the target message in the merkle tree.\n */\n function messageIndex(\n bytes calldata _metadata\n ) internal pure returns (uint32) {\n return\n uint32(\n bytes4(_metadata[MESSAGE_INDEX_OFFSET:MESSAGE_INDEX_OFFSET + 4])\n );\n }\n\n /**\n * @notice Returns the index of the signed checkpoint.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Index of the signed checkpoint\n */\n function signedIndex(\n bytes calldata _metadata\n ) internal pure returns (uint32) {\n return\n uint32(\n bytes4(_metadata[SIGNED_INDEX_OFFSET:SIGNED_INDEX_OFFSET + 4])\n );\n }\n\n /**\n * @notice Returns the message ID of the signed checkpoint.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Message ID of the signed checkpoint\n */\n function signedMessageId(\n bytes calldata _metadata\n ) internal pure returns (bytes32) {\n return bytes32(_metadata[MESSAGE_ID_OFFSET:MESSAGE_ID_OFFSET + 32]);\n }\n\n /**\n * @notice Returns the merkle proof branch of the message.\n * @dev This appears to be more gas efficient than returning a calldata\n * slice and using that.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Merkle proof branch of the message.\n */\n function proof(\n bytes calldata _metadata\n ) internal pure returns (bytes32[32] memory) {\n return\n abi.decode(\n _metadata[MERKLE_PROOF_OFFSET:MERKLE_PROOF_OFFSET +\n MERKLE_PROOF_LENGTH],\n (bytes32[32])\n );\n }\n\n /**\n * @notice Returns the validator ECDSA signature at `_index`.\n * @dev Assumes signatures are sorted by validator\n * @dev Assumes `_metadata` encodes `threshold` signatures.\n * @dev Assumes `_index` is less than `threshold`\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @param _index The index of the signature to return.\n * @return The validator ECDSA signature at `_index`.\n */\n function signatureAt(\n bytes calldata _metadata,\n uint256 _index\n ) internal pure returns (bytes calldata) {\n uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH);\n uint256 _end = _start + SIGNATURE_LENGTH;\n return _metadata[_start:_end];\n }\n\n /**\n * @notice Returns the number of signatures in the metadata.\n * @param _metadata ABI encoded Merkle Root Multisig ISM metadata.\n * @return The number of signatures in the metadata.\n */\n function signatureCount(\n bytes calldata _metadata\n ) internal pure returns (uint256) {\n uint256 signatures = _metadata.length - SIGNATURES_OFFSET;\n require(\n signatures % SIGNATURE_LENGTH == 0,\n \"Invalid signatures length\"\n );\n return signatures / SIGNATURE_LENGTH;\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/libs/CheckpointLib.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {TypeCasts} from \"./TypeCasts.sol\";\n\nstruct Checkpoint {\n uint32 origin;\n bytes32 merkleTree;\n bytes32 root;\n uint32 index;\n bytes32 messageId;\n}\n\nlibrary CheckpointLib {\n using TypeCasts for bytes32;\n\n /**\n * @notice Returns the digest validators are expected to sign when signing checkpoints.\n * @param _origin The origin domain of the checkpoint.\n * @param _merkleTreeHook The address of the origin merkle tree hook as bytes32.\n * @param _checkpointRoot The root of the checkpoint.\n * @param _checkpointIndex The index of the checkpoint.\n * @param _messageId The message ID of the checkpoint.\n * @dev Message ID must match leaf content of checkpoint root at index.\n * @return The digest of the checkpoint.\n */\n function digest(\n uint32 _origin,\n bytes32 _merkleTreeHook,\n bytes32 _checkpointRoot,\n uint32 _checkpointIndex,\n bytes32 _messageId\n ) internal pure returns (bytes32) {\n bytes32 _domainHash = domainHash(_origin, _merkleTreeHook);\n return\n ECDSA.toEthSignedMessageHash(\n keccak256(\n abi.encodePacked(\n _domainHash,\n _checkpointRoot,\n _checkpointIndex,\n _messageId\n )\n )\n );\n }\n\n /**\n * @notice Returns the digest validators are expected to sign when signing checkpoints.\n * @param checkpoint The checkpoint (struct) to hash.\n * @return The digest of the checkpoint.\n */\n function digest(\n Checkpoint memory checkpoint\n ) internal pure returns (bytes32) {\n return\n digest(\n checkpoint.origin,\n checkpoint.merkleTree,\n checkpoint.root,\n checkpoint.index,\n checkpoint.messageId\n );\n }\n\n function merkleTreeAddress(\n Checkpoint calldata checkpoint\n ) internal pure returns (address) {\n return checkpoint.merkleTree.bytes32ToAddress();\n }\n\n /**\n * @notice Returns the domain hash that validators are expected to use\n * when signing checkpoints.\n * @param _origin The origin domain of the checkpoint.\n * @param _merkleTreeHook The address of the origin merkle tree as bytes32.\n * @return The domain hash.\n */\n function domainHash(\n uint32 _origin,\n bytes32 _merkleTreeHook\n ) internal pure returns (bytes32) {\n // Including the origin merkle tree address in the signature allows the slashing\n // protocol to enroll multiple trees. Otherwise, a valid signature for\n // tree A would be indistinguishable from a fraudulent signature for tree B.\n // The slashing protocol should slash if validators sign attestations for\n // anything other than a whitelisted tree.\n return\n keccak256(abi.encodePacked(_origin, _merkleTreeHook, \"HYPERLANE\"));\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/libs/MessageIdMultisigIsmMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/**\n * Format of metadata:\n * [ 0: 32] Origin merkle tree address\n * [ 32: 64] Signed checkpoint root\n * [ 64: 68] Signed checkpoint index\n * [ 68:????] Validator signatures (length := threshold * 65)\n */\nlibrary MessageIdMultisigIsmMetadata {\n uint8 private constant ORIGIN_MERKLE_TREE_OFFSET = 0;\n uint8 private constant MERKLE_ROOT_OFFSET = 32;\n uint8 private constant MERKLE_INDEX_OFFSET = 64;\n uint8 private constant SIGNATURES_OFFSET = 68;\n uint8 private constant SIGNATURE_LENGTH = 65;\n\n /**\n * @notice Returns the origin merkle tree hook of the signed checkpoint as bytes32.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Origin merkle tree hook of the signed checkpoint as bytes32\n */\n function originMerkleTreeHook(\n bytes calldata _metadata\n ) internal pure returns (bytes32) {\n return\n bytes32(\n _metadata[ORIGIN_MERKLE_TREE_OFFSET:ORIGIN_MERKLE_TREE_OFFSET +\n 32]\n );\n }\n\n /**\n * @notice Returns the merkle root of the signed checkpoint.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Merkle root of the signed checkpoint\n */\n function root(bytes calldata _metadata) internal pure returns (bytes32) {\n return bytes32(_metadata[MERKLE_ROOT_OFFSET:MERKLE_ROOT_OFFSET + 32]);\n }\n\n /**\n * @notice Returns the merkle index of the signed checkpoint.\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @return Merkle index of the signed checkpoint\n */\n function index(bytes calldata _metadata) internal pure returns (uint32) {\n return\n uint32(\n bytes4(_metadata[MERKLE_INDEX_OFFSET:MERKLE_INDEX_OFFSET + 4])\n );\n }\n\n /**\n * @notice Returns the validator ECDSA signature at `_index`.\n * @dev Assumes signatures are sorted by validator\n * @dev Assumes `_metadata` encodes `threshold` signatures.\n * @dev Assumes `_index` is less than `threshold`\n * @param _metadata ABI encoded Multisig ISM metadata.\n * @param _index The index of the signature to return.\n * @return The validator ECDSA signature at `_index`.\n */\n function signatureAt(\n bytes calldata _metadata,\n uint256 _index\n ) internal pure returns (bytes calldata) {\n uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH);\n uint256 _end = _start + SIGNATURE_LENGTH;\n return _metadata[_start:_end];\n }\n\n /**\n * @notice Returns the number of signatures in the metadata.\n * @param _metadata ABI encoded MessageId Multisig ISM metadata.\n * @return The number of signatures in the metadata.\n */\n function signatureCount(\n bytes calldata _metadata\n ) internal pure returns (uint256) {\n uint256 signatures = _metadata.length - SIGNATURES_OFFSET;\n require(\n signatures % SIGNATURE_LENGTH == 0,\n \"Invalid signatures length\"\n );\n return signatures / SIGNATURE_LENGTH;\n }\n}\n"
},
"@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // Deprecated in v4.8\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n mstore(0x1c, hash)\n message := keccak256(0x00, 0x3c)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, \"\\x19\\x01\")\n mstore(add(ptr, 0x02), domainSeparator)\n mstore(add(ptr, 0x22), structHash)\n data := keccak256(ptr, 0x42)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Data with intended validator, created from a\n * `validator` and `data` according to the version 0 of EIP-191.\n *\n * See {recover}.\n */\n function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/isms/IMultisigIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\nimport {IInterchainSecurityModule} from \"../IInterchainSecurityModule.sol\";\n\ninterface IMultisigIsm is IInterchainSecurityModule {\n /**\n * @notice Returns the set of validators responsible for verifying _message\n * and the number of signatures required\n * @dev Can change based on the content of _message\n * @dev Signatures provided to `verify` must be consistent with validator ordering\n * @param _message Hyperlane formatted interchain message\n * @return validators The array of validator addresses\n * @return threshold The number of validator signatures needed\n */\n function validatorsAndThreshold(\n bytes calldata _message\n ) external view returns (address[] memory validators, uint8 threshold);\n}\n"
},
"@hyperlane-xyz/core/contracts/client/GasRouter.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\n// ============ Internal Imports ============\nimport {Router} from \"./Router.sol\";\nimport {EnumerableMapExtended} from \"../libs/EnumerableMapExtended.sol\";\nimport {StandardHookMetadata} from \"../hooks/libs/StandardHookMetadata.sol\";\n\nabstract contract GasRouter is Router {\n using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;\n\n event GasSet(uint32 domain, uint256 gas);\n\n // ============ Mutable Storage ============\n mapping(uint32 destinationDomain => uint256 gasLimit) public destinationGas;\n\n struct GasRouterConfig {\n uint32 domain;\n uint256 gas;\n }\n\n constructor(address _mailbox) Router(_mailbox) {}\n\n /**\n * @notice Sets the gas amount dispatched for each configured domain.\n * @param gasConfigs The array of GasRouterConfig structs\n */\n function setDestinationGas(\n GasRouterConfig[] calldata gasConfigs\n ) external onlyOwner {\n for (uint256 i = 0; i < gasConfigs.length; i += 1) {\n _setDestinationGas(gasConfigs[i].domain, gasConfigs[i].gas);\n }\n }\n\n /**\n * @notice Sets the gas amount dispatched for each configured domain.\n * @param domain The destination domain ID\n * @param gas The gas limit\n */\n function setDestinationGas(uint32 domain, uint256 gas) external onlyOwner {\n _setDestinationGas(domain, gas);\n }\n\n /**\n * @notice Returns the gas payment required to dispatch a message to the given domain's router.\n * @param _destinationDomain The domain of the router.\n * @return _gasPayment Payment computed by the registered InterchainGasPaymaster.\n */\n function quoteGasPayment(\n uint32 _destinationDomain\n ) public view virtual returns (uint256) {\n return\n _Router_quoteDispatch(\n _destinationDomain,\n \"\",\n _GasRouter_hookMetadata(_destinationDomain),\n address(hook)\n );\n }\n\n function _GasRouter_hookMetadata(\n uint32 _destination\n ) internal view returns (bytes memory) {\n return\n StandardHookMetadata.overrideGasLimit(destinationGas[_destination]);\n }\n\n function _setDestinationGas(uint32 domain, uint256 gas) internal virtual {\n require(\n _routers.contains(uint256(domain)),\n _domainNotFoundError(domain)\n );\n destinationGas[domain] = gas;\n emit GasSet(domain, gas);\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/libs/Quotes.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity >=0.8.0;\n\nimport {Quote} from \"../../interfaces/ITokenBridge.sol\";\n\nlibrary Quotes {\n function extract(\n Quote[] memory quotes,\n address token\n ) internal pure returns (uint256 sum) {\n sum = 0;\n for (uint256 i = 0; i < quotes.length; i++) {\n if (quotes[i].token == token) {\n sum += quotes[i].amount;\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/utils/structs/EnumerableMap.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableMap.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.\n\npragma solidity ^0.8.0;\n\nimport \"./EnumerableSet.sol\";\n\n/**\n * @dev Library for managing an enumerable variant of Solidity's\n * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]\n * type.\n *\n * Maps have the following properties:\n *\n * - Entries are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Entries are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n * // Add the library methods\n * using EnumerableMap for EnumerableMap.UintToAddressMap;\n *\n * // Declare a set state variable\n * EnumerableMap.UintToAddressMap private myMap;\n * }\n * ```\n *\n * The following map types are supported:\n *\n * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0\n * - `address -> uint256` (`AddressToUintMap`) since v4.6.0\n * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0\n * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0\n * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableMap.\n * ====\n */\nlibrary EnumerableMap {\n using EnumerableSet for EnumerableSet.Bytes32Set;\n\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Map type with\n // bytes32 keys and values.\n // The Map implementation uses private functions, and user-facing\n // implementations (such as Uint256ToAddressMap) are just wrappers around\n // the underlying Map.\n // This means that we can only create new EnumerableMaps for types that fit\n // in bytes32.\n\n struct Bytes32ToBytes32Map {\n // Storage of keys\n EnumerableSet.Bytes32Set _keys;\n mapping(bytes32 => bytes32) _values;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {\n map._values[key] = value;\n return map._keys.add(key);\n }\n\n /**\n * @dev Removes a key-value pair from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {\n delete map._values[key];\n return map._keys.remove(key);\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {\n return map._keys.contains(key);\n }\n\n /**\n * @dev Returns the number of key-value pairs in the map. O(1).\n */\n function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {\n return map._keys.length();\n }\n\n /**\n * @dev Returns the key-value pair stored at position `index` in the map. O(1).\n *\n * Note that there are no guarantees on the ordering of entries inside the\n * array, and it may change when more entries are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {\n bytes32 key = map._keys.at(index);\n return (key, map._values[key]);\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {\n bytes32 value = map._values[key];\n if (value == bytes32(0)) {\n return (contains(map, key), bytes32(0));\n } else {\n return (true, value);\n }\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {\n bytes32 value = map._values[key];\n require(value != 0 || contains(map, key), \"EnumerableMap: nonexistent key\");\n return value;\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(\n Bytes32ToBytes32Map storage map,\n bytes32 key,\n string memory errorMessage\n ) internal view returns (bytes32) {\n bytes32 value = map._values[key];\n require(value != 0 || contains(map, key), errorMessage);\n return value;\n }\n\n /**\n * @dev Return the an array containing all the keys\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {\n return map._keys.values();\n }\n\n // UintToUintMap\n\n struct UintToUintMap {\n Bytes32ToBytes32Map _inner;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {\n return set(map._inner, bytes32(key), bytes32(value));\n }\n\n /**\n * @dev Removes a value from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {\n return remove(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {\n return contains(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns the number of elements in the map. O(1).\n */\n function length(UintToUintMap storage map) internal view returns (uint256) {\n return length(map._inner);\n }\n\n /**\n * @dev Returns the element stored at position `index` in the map. O(1).\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {\n (bytes32 key, bytes32 value) = at(map._inner, index);\n return (uint256(key), uint256(value));\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) {\n (bool success, bytes32 value) = tryGet(map._inner, bytes32(key));\n return (success, uint256(value));\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {\n return uint256(get(map._inner, bytes32(key)));\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(UintToUintMap storage map, uint256 key, string memory errorMessage) internal view returns (uint256) {\n return uint256(get(map._inner, bytes32(key), errorMessage));\n }\n\n /**\n * @dev Return the an array containing all the keys\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function keys(UintToUintMap storage map) internal view returns (uint256[] memory) {\n bytes32[] memory store = keys(map._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintToAddressMap\n\n struct UintToAddressMap {\n Bytes32ToBytes32Map _inner;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {\n return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {\n return remove(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {\n return contains(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns the number of elements in the map. O(1).\n */\n function length(UintToAddressMap storage map) internal view returns (uint256) {\n return length(map._inner);\n }\n\n /**\n * @dev Returns the element stored at position `index` in the map. O(1).\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {\n (bytes32 key, bytes32 value) = at(map._inner, index);\n return (uint256(key), address(uint160(uint256(value))));\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {\n (bool success, bytes32 value) = tryGet(map._inner, bytes32(key));\n return (success, address(uint160(uint256(value))));\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {\n return address(uint160(uint256(get(map._inner, bytes32(key)))));\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(\n UintToAddressMap storage map,\n uint256 key,\n string memory errorMessage\n ) internal view returns (address) {\n return address(uint160(uint256(get(map._inner, bytes32(key), errorMessage))));\n }\n\n /**\n * @dev Return the an array containing all the keys\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) {\n bytes32[] memory store = keys(map._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressToUintMap\n\n struct AddressToUintMap {\n Bytes32ToBytes32Map _inner;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {\n return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));\n }\n\n /**\n * @dev Removes a value from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(AddressToUintMap storage map, address key) internal returns (bool) {\n return remove(map._inner, bytes32(uint256(uint160(key))));\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(AddressToUintMap storage map, address key) internal view returns (bool) {\n return contains(map._inner, bytes32(uint256(uint160(key))));\n }\n\n /**\n * @dev Returns the number of elements in the map. O(1).\n */\n function length(AddressToUintMap storage map) internal view returns (uint256) {\n return length(map._inner);\n }\n\n /**\n * @dev Returns the element stored at position `index` in the map. O(1).\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {\n (bytes32 key, bytes32 value) = at(map._inner, index);\n return (address(uint160(uint256(key))), uint256(value));\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {\n (bool success, bytes32 value) = tryGet(map._inner, bytes32(uint256(uint160(key))));\n return (success, uint256(value));\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(AddressToUintMap storage map, address key) internal view returns (uint256) {\n return uint256(get(map._inner, bytes32(uint256(uint160(key)))));\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(\n AddressToUintMap storage map,\n address key,\n string memory errorMessage\n ) internal view returns (uint256) {\n return uint256(get(map._inner, bytes32(uint256(uint160(key))), errorMessage));\n }\n\n /**\n * @dev Return the an array containing all the keys\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function keys(AddressToUintMap storage map) internal view returns (address[] memory) {\n bytes32[] memory store = keys(map._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // Bytes32ToUintMap\n\n struct Bytes32ToUintMap {\n Bytes32ToBytes32Map _inner;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {\n return set(map._inner, key, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {\n return remove(map._inner, key);\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {\n return contains(map._inner, key);\n }\n\n /**\n * @dev Returns the number of elements in the map. O(1).\n */\n function length(Bytes32ToUintMap storage map) internal view returns (uint256) {\n return length(map._inner);\n }\n\n /**\n * @dev Returns the element stored at position `index` in the map. O(1).\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32, uint256) {\n (bytes32 key, bytes32 value) = at(map._inner, index);\n return (key, uint256(value));\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool, uint256) {\n (bool success, bytes32 value) = tryGet(map._inner, key);\n return (success, uint256(value));\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {\n return uint256(get(map._inner, key));\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(\n Bytes32ToUintMap storage map,\n bytes32 key,\n string memory errorMessage\n ) internal view returns (uint256) {\n return uint256(get(map._inner, key, errorMessage));\n }\n\n /**\n * @dev Return the an array containing all the keys\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) {\n bytes32[] memory store = keys(map._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20Upgradeable.sol\";\nimport \"../utils/SafeERC20Upgradeable.sol\";\nimport \"../../../interfaces/IERC4626Upgradeable.sol\";\nimport \"../../../utils/math/MathUpgradeable.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * [CAUTION]\n * ====\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\n * with a \"donation\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\n * expensive than it is profitable. More details about the underlying math can be found\n * xref:erc4626.adoc#inflation-attack[here].\n *\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\n * `_convertToShares` and `_convertToAssets` functions.\n *\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\n * ====\n *\n * _Available since v4.7._\n */\nabstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {\n using MathUpgradeable for uint256;\n\n IERC20Upgradeable private _asset;\n uint8 private _underlyingDecimals;\n\n /**\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\n */\n function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {\n __ERC4626_init_unchained(asset_);\n }\n\n function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n _underlyingDecimals = success ? assetDecimals : 18;\n _asset = asset_;\n }\n\n /**\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n */\n function _tryGetAssetDecimals(IERC20Upgradeable asset_) private view returns (bool, uint8) {\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\n abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector)\n );\n if (success && encodedDecimals.length >= 32) {\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\n if (returnedDecimals <= type(uint8).max) {\n return (true, uint8(returnedDecimals));\n }\n }\n return (false, 0);\n }\n\n /**\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\n * \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\n *\n * See {IERC20Metadata-decimals}.\n */\n function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {\n return _underlyingDecimals + _decimalsOffset();\n }\n\n /** @dev See {IERC4626-asset}. */\n function asset() public view virtual override returns (address) {\n return address(_asset);\n }\n\n /** @dev See {IERC4626-totalAssets}. */\n function totalAssets() public view virtual override returns (uint256) {\n return _asset.balanceOf(address(this));\n }\n\n /** @dev See {IERC4626-convertToShares}. */\n function convertToShares(uint256 assets) public view virtual override returns (uint256) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-convertToAssets}. */\n function convertToAssets(uint256 shares) public view virtual override returns (uint256) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-maxDeposit}. */\n function maxDeposit(address) public view virtual override returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxMint}. */\n function maxMint(address) public view virtual override returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxWithdraw}. */\n function maxWithdraw(address owner) public view virtual override returns (uint256) {\n return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-maxRedeem}. */\n function maxRedeem(address owner) public view virtual override returns (uint256) {\n return balanceOf(owner);\n }\n\n /** @dev See {IERC4626-previewDeposit}. */\n function previewDeposit(uint256 assets) public view virtual override returns (uint256) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-previewMint}. */\n function previewMint(uint256 shares) public view virtual override returns (uint256) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Up);\n }\n\n /** @dev See {IERC4626-previewWithdraw}. */\n function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Up);\n }\n\n /** @dev See {IERC4626-previewRedeem}. */\n function previewRedeem(uint256 shares) public view virtual override returns (uint256) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-deposit}. */\n function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {\n require(assets <= maxDeposit(receiver), \"ERC4626: deposit more than max\");\n\n uint256 shares = previewDeposit(assets);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-mint}.\n *\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\n * In this case, the shares will be minted without requiring any assets to be deposited.\n */\n function mint(uint256 shares, address receiver) public virtual override returns (uint256) {\n require(shares <= maxMint(receiver), \"ERC4626: mint more than max\");\n\n uint256 assets = previewMint(shares);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return assets;\n }\n\n /** @dev See {IERC4626-withdraw}. */\n function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) {\n require(assets <= maxWithdraw(owner), \"ERC4626: withdraw more than max\");\n\n uint256 shares = previewWithdraw(assets);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-redeem}. */\n function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) {\n require(shares <= maxRedeem(owner), \"ERC4626: redeem more than max\");\n\n uint256 assets = previewRedeem(shares);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return assets;\n }\n\n /**\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n */\n function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256) {\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\n }\n\n /**\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n */\n function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256) {\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\n }\n\n /**\n * @dev Deposit/mint common workflow.\n */\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n // assets are transferred and before the shares are minted, which is a valid state.\n // slither-disable-next-line reentrancy-no-eth\n SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);\n _mint(receiver, shares);\n\n emit Deposit(caller, receiver, assets, shares);\n }\n\n /**\n * @dev Withdraw/redeem common workflow.\n */\n function _withdraw(\n address caller,\n address receiver,\n address owner,\n uint256 assets,\n uint256 shares\n ) internal virtual {\n if (caller != owner) {\n _spendAllowance(owner, caller, shares);\n }\n\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n // shares are burned and after the assets are transferred, which is a valid state.\n _burn(owner, shares);\n SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);\n\n emit Withdraw(caller, receiver, owner, assets, shares);\n }\n\n function _decimalsOffset() internal view virtual returns (uint8) {\n return 0;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"@hyperlane-xyz/core/contracts/client/Router.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\n// ============ Internal Imports ============\nimport {IMessageRecipient} from \"../interfaces/IMessageRecipient.sol\";\nimport {IPostDispatchHook} from \"../interfaces/hooks/IPostDispatchHook.sol\";\nimport {MailboxClient} from \"./MailboxClient.sol\";\nimport {EnumerableMapExtended} from \"../libs/EnumerableMapExtended.sol\";\n\n// ============ External Imports ============\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\n\nabstract contract Router is MailboxClient, IMessageRecipient {\n using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;\n using Strings for uint32;\n\n // ============ Mutable Storage ============\n /// @dev Mapping of domain => router. For a given domain we have one router we send/receive messages from.\n EnumerableMapExtended.UintToBytes32Map internal _routers;\n\n uint256[48] private __GAP; // gap for upgrade safety\n\n constructor(address _mailbox) MailboxClient(_mailbox) {}\n\n // ============ External functions ============\n function domains() external view returns (uint32[] memory) {\n return _routers.uint32Keys();\n }\n\n /**\n * @notice Returns the address of the Router contract for the given domain\n * @param _domain The remote domain ID.\n * @dev Returns 0 address if no router is enrolled for the given domain\n * @return router The address of the Router contract for the given domain\n */\n function routers(uint32 _domain) public view virtual returns (bytes32) {\n (, bytes32 _router) = _routers.tryGet(_domain);\n return _router;\n }\n\n /**\n * @notice Unregister the domain\n * @param _domain The domain of the remote Application Router\n */\n function unenrollRemoteRouter(uint32 _domain) external virtual onlyOwner {\n _unenrollRemoteRouter(_domain);\n }\n\n /**\n * @notice Register the address of a Router contract for the same Application on a remote chain\n * @param _domain The domain of the remote Application Router\n * @param _router The address of the remote Application Router\n */\n function enrollRemoteRouter(\n uint32 _domain,\n bytes32 _router\n ) external virtual onlyOwner {\n _enrollRemoteRouter(_domain, _router);\n }\n\n /**\n * @notice Batch version of `enrollRemoteRouter`\n * @param _domains The domains of the remote Application Routers\n * @param _addresses The addresses of the remote Application Routers\n */\n function enrollRemoteRouters(\n uint32[] calldata _domains,\n bytes32[] calldata _addresses\n ) external virtual onlyOwner {\n require(_domains.length == _addresses.length, \"!length\");\n uint256 length = _domains.length;\n for (uint256 i = 0; i < length; i += 1) {\n _enrollRemoteRouter(_domains[i], _addresses[i]);\n }\n }\n\n /**\n * @notice Batch version of `unenrollRemoteRouter`\n * @param _domains The domains of the remote Application Routers\n */\n function unenrollRemoteRouters(\n uint32[] calldata _domains\n ) external virtual onlyOwner {\n uint256 length = _domains.length;\n for (uint256 i = 0; i < length; i += 1) {\n _unenrollRemoteRouter(_domains[i]);\n }\n }\n\n /**\n * @notice Handles an incoming message\n * @param _origin The origin domain\n * @param _sender The sender address\n * @param _message The message\n */\n // solhint-disable-next-line hyperlane/no-virtual-override\n function handle(\n uint32 _origin,\n bytes32 _sender,\n bytes calldata _message\n ) external payable virtual override onlyMailbox {\n bytes32 _router = _mustHaveRemoteRouter(_origin);\n require(_router == _sender, \"Enrolled router does not match sender\");\n _handle(_origin, _sender, _message);\n }\n\n // ============ Virtual functions ============\n function _handle(\n uint32 _origin,\n bytes32 _sender,\n bytes calldata _message\n ) internal virtual;\n\n // ============ Internal functions ============\n\n /**\n * @notice Set the router for a given domain\n * @param _domain The domain\n * @param _address The new router\n */\n function _enrollRemoteRouter(\n uint32 _domain,\n bytes32 _address\n ) internal virtual {\n _routers.set(_domain, _address);\n }\n\n /**\n * @notice Remove the router for a given domain\n * @param _domain The domain\n */\n function _unenrollRemoteRouter(uint32 _domain) internal virtual {\n require(_routers.remove(_domain), _domainNotFoundError(_domain));\n }\n\n /**\n * @notice Return true if the given domain / router is the address of a remote Application Router\n * @param _domain The domain of the potential remote Application Router\n * @param _address The address of the potential remote Application Router\n */\n function _isRemoteRouter(\n uint32 _domain,\n bytes32 _address\n ) internal view returns (bool) {\n return routers(_domain) == _address;\n }\n\n /**\n * @notice Assert that the given domain has an Application Router registered and return its address\n * @param _domain The domain of the chain for which to get the Application Router\n * @return _router The address of the remote Application Router on _domain\n */\n function _mustHaveRemoteRouter(\n uint32 _domain\n ) internal view returns (bytes32) {\n (bool contained, bytes32 _router) = _routers.tryGet(_domain);\n if (contained) {\n return _router;\n }\n revert(_domainNotFoundError(_domain));\n }\n\n function _domainNotFoundError(\n uint32 _domain\n ) internal pure returns (string memory) {\n return\n string.concat(\n \"No router enrolled for domain: \",\n _domain.toString()\n );\n }\n\n function _Router_dispatch(\n uint32 _destinationDomain,\n uint256 _value,\n bytes memory _messageBody\n ) internal returns (bytes32) {\n return\n _Router_dispatch(\n _destinationDomain,\n _value,\n _messageBody,\n \"\",\n address(hook)\n );\n }\n\n function _Router_dispatch(\n uint32 _destinationDomain,\n uint256 _value,\n bytes memory _messageBody,\n bytes memory _hookMetadata,\n address _hook\n ) internal returns (bytes32) {\n bytes32 _router = _mustHaveRemoteRouter(_destinationDomain);\n return\n mailbox.dispatch{value: _value}(\n _destinationDomain,\n _router,\n _messageBody,\n _hookMetadata,\n IPostDispatchHook(_hook)\n );\n }\n\n function _Router_quoteDispatch(\n uint32 _destinationDomain,\n bytes memory _messageBody\n ) internal view returns (uint256) {\n return\n _Router_quoteDispatch(\n _destinationDomain,\n _messageBody,\n \"\",\n address(hook)\n );\n }\n\n function _Router_quoteDispatch(\n uint32 _destinationDomain,\n bytes memory _messageBody,\n bytes memory _hookMetadata,\n address _hook\n ) internal view returns (uint256) {\n bytes32 _router = _mustHaveRemoteRouter(_destinationDomain);\n return\n mailbox.quoteDispatch(\n _destinationDomain,\n _router,\n _messageBody,\n _hookMetadata,\n IPostDispatchHook(_hook)\n );\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/token/interfaces/IWETH.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity ^0.8.22;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IWETH is IERC20 {\n function deposit() external payable;\n function withdraw(uint256 amount) external;\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n * doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n * token.safeTransferFrom(msg.sender, address(this), value);\n * ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n *\n * CAUTION: See Security Considerations above.\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@hyperlane-xyz/core/contracts/interfaces/isms/IAggregationIsm.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\nimport {IInterchainSecurityModule} from \"../IInterchainSecurityModule.sol\";\n\ninterface IAggregationIsm is IInterchainSecurityModule {\n /**\n * @notice Returns the set of modules responsible for verifying _message\n * and the number of modules that must verify\n * @dev Can change based on the content of _message\n * @param _message Hyperlane formatted interchain message\n * @return modules The array of ISM addresses\n * @return threshold The number of modules needed to verify\n */\n function modulesAndThreshold(\n bytes calldata _message\n ) external view returns (address[] memory modules, uint8 threshold);\n}\n"
},
"@hyperlane-xyz/core/contracts/isms/libs/AggregationIsmMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/**\n * Format of metadata:\n *\n * [????:????] Metadata start/end uint32 ranges, packed as uint64\n * [????:????] ISM metadata, packed encoding\n */\nlibrary AggregationIsmMetadata {\n uint256 private constant RANGE_SIZE = 4;\n\n /**\n * @notice Returns whether or not metadata was provided for the ISM at\n * `_index`\n * @dev Callers must ensure _index is less than the number of metadatas\n * provided\n * @param _metadata Encoded Aggregation ISM metadata\n * @param _index The index of the ISM to check for metadata for\n * @return Whether or not metadata was provided for the ISM at `_index`\n */\n function hasMetadata(\n bytes calldata _metadata,\n uint8 _index\n ) internal pure returns (bool) {\n (uint32 _start, ) = _metadataRange(_metadata, _index);\n return _start > 0;\n }\n\n /**\n * @notice Returns the metadata provided for the ISM at `_index`\n * @dev Callers must ensure _index is less than the number of metadatas\n * provided\n * @dev Callers must ensure `hasMetadata(_metadata, _index)`\n * @param _metadata Encoded Aggregation ISM metadata\n * @param _index The index of the ISM to return metadata for\n * @return The metadata provided for the ISM at `_index`\n */\n function metadataAt(\n bytes calldata _metadata,\n uint8 _index\n ) internal pure returns (bytes calldata) {\n (uint32 _start, uint32 _end) = _metadataRange(_metadata, _index);\n return _metadata[_start:_end];\n }\n\n /**\n * @notice Returns the range of the metadata provided for the ISM at\n * `_index`, or zeroes if not provided\n * @dev Callers must ensure _index is less than the number of metadatas\n * provided\n * @param _metadata Encoded Aggregation ISM metadata\n * @param _index The index of the ISM to return metadata range for\n * @return The range of the metadata provided for the ISM at `_index`, or\n * zeroes if not provided\n */\n function _metadataRange(\n bytes calldata _metadata,\n uint8 _index\n ) private pure returns (uint32, uint32) {\n uint256 _start = (uint32(_index) * RANGE_SIZE * 2);\n uint256 _mid = _start + RANGE_SIZE;\n uint256 _end = _mid + RANGE_SIZE;\n return (\n uint32(bytes4(_metadata[_start:_mid])),\n uint32(bytes4(_metadata[_mid:_end]))\n );\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toString(int256 value) internal pure returns (string memory) {\n return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20PermitUpgradeable token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/interfaces/IERC4626Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20Upgradeable.sol\";\nimport \"../token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/**\n * @dev Interface of the ERC4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n *\n * _Available since v4.7._\n */\ninterface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed sender,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /**\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n *\n * - MUST be an ERC-20 token contract.\n * - MUST NOT revert.\n */\n function asset() external view returns (address assetTokenAddress);\n\n /**\n * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n *\n * - SHOULD include any compounding that occurs from yield.\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT revert.\n */\n function totalAssets() external view returns (uint256 totalManagedAssets);\n\n /**\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n * through a deposit call.\n *\n * - MUST return a limited value if receiver is subject to some deposit limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n * - MUST NOT revert.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n * in the same transaction.\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * deposit execution, and are accounted for during deposit.\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n * - MUST return a limited value if receiver is subject to some mint limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n * - MUST NOT revert.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n * same transaction.\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n * would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n * execution, and are accounted for during mint.\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n * Vault, through a withdraw call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n * called\n * in the same transaction.\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * withdraw execution, and are accounted for during withdraw.\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n * through a redeem call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n * same transaction.\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n * redemption would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * redeem execution, and are accounted for during redeem.\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/math/SignedMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n * doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n * token.safeTransferFrom(msg.sender, address(this), value);\n * ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20PermitUpgradeable {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n *\n * CAUTION: See Security Considerations above.\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"viaIR": true,
"evmVersion": "paris",
"outputSelection": {
"@hyperlane-xyz/core/contracts/token/HypERC20.sol": {
"HypERC20": [
"abi",
"metadata",
"evm.bytecode",
"evm.deployedBytecode"
],
"": [
"ast"
]
}
}
}
},
"metadata": {
"compiler": {
"version": "0.8.30+commit.73712a01"
},
"language": "Solidity",
"output": {
"abi": [
{
"inputs": [
{
"internalType": "uint8",
"name": "__decimals",
"type": "uint8"
},
{
"internalType": "uint256",
"name": "_scaleNumerator",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_scaleDenominator",
"type": "uint256"
},
{
"internalType": "address",
"name": "_mailbox",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeHook",
"type": "address"
}
],
"name": "FeeHookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "feeRecipient",
"type": "address"
}
],
"name": "FeeRecipientSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "GasSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "HookSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint8",
"name": "version",
"type": "uint8"
}
],
"name": "Initialized",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "address",
"name": "_ism",
"type": "address"
}
],
"name": "IsmSet",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "previousOwner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "origin",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "ReceivedTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint32",
"name": "destination",
"type": "uint32"
},
{
"indexed": true,
"internalType": "bytes32",
"name": "recipient",
"type": "bytes32"
},
{
"indexed": false,
"internalType": "uint256",
"name": "amountOrId",
"type": "uint256"
}
],
"name": "SentTransferRemote",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [],
"name": "PACKAGE_VERSION",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "decimals",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "subtractedValue",
"type": "uint256"
}
],
"name": "decreaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "destinationDomain",
"type": "uint32"
}
],
"name": "destinationGas",
"outputs": [
{
"internalType": "uint256",
"name": "gasLimit",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "domains",
"outputs": [
{
"internalType": "uint32[]",
"name": "",
"type": "uint32[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_router",
"type": "bytes32"
}
],
"name": "enrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
},
{
"internalType": "bytes32[]",
"name": "_addresses",
"type": "bytes32[]"
}
],
"name": "enrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "feeHook",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeRecipient",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "feeToken",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_origin",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_sender",
"type": "bytes32"
},
{
"internalType": "bytes",
"name": "_message",
"type": "bytes"
}
],
"name": "handle",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [],
"name": "hook",
"outputs": [
{
"internalType": "contract IPostDispatchHook",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "addedValue",
"type": "uint256"
}
],
"name": "increaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_totalSupply",
"type": "uint256"
},
{
"internalType": "string",
"name": "_name",
"type": "string"
},
{
"internalType": "string",
"name": "_symbol",
"type": "string"
},
{
"internalType": "address",
"name": "_hook",
"type": "address"
},
{
"internalType": "address",
"name": "_interchainSecurityModule",
"type": "address"
},
{
"internalType": "address",
"name": "_owner",
"type": "address"
}
],
"name": "initialize",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "interchainSecurityModule",
"outputs": [
{
"internalType": "contract IInterchainSecurityModule",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "localDomain",
"outputs": [
{
"internalType": "uint32",
"name": "",
"type": "uint32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "mailbox",
"outputs": [
{
"internalType": "contract IMailbox",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destinationDomain",
"type": "uint32"
}
],
"name": "quoteGasPayment",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "quoteTransferRemote",
"outputs": [
{
"components": [
{
"internalType": "address",
"name": "token",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"internalType": "struct Quote[]",
"name": "quotes",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "renounceOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "routers",
"outputs": [
{
"internalType": "bytes32",
"name": "",
"type": "bytes32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleDenominator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "scaleNumerator",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"components": [
{
"internalType": "uint32",
"name": "domain",
"type": "uint32"
},
{
"internalType": "uint256",
"name": "gas",
"type": "uint256"
}
],
"internalType": "struct GasRouter.GasRouterConfig[]",
"name": "gasConfigs",
"type": "tuple[]"
}
],
"name": "setDestinationGas",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_feeHook",
"type": "address"
}
],
"name": "setFeeHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "recipient",
"type": "address"
}
],
"name": "setFeeRecipient",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_hook",
"type": "address"
}
],
"name": "setHook",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_module",
"type": "address"
}
],
"name": "setInterchainSecurityModule",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "symbol",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "token",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "from",
"type": "address"
},
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_destination",
"type": "uint32"
},
{
"internalType": "bytes32",
"name": "_recipient",
"type": "bytes32"
},
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "transferRemote",
"outputs": [
{
"internalType": "bytes32",
"name": "messageId",
"type": "bytes32"
}
],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32",
"name": "_domain",
"type": "uint32"
}
],
"name": "unenrollRemoteRouter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint32[]",
"name": "_domains",
"type": "uint32[]"
}
],
"name": "unenrollRemoteRouters",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
],
"devdoc": {
"author": "Abacus Works",
"details": "Supply on each chain is not constant but the aggregate supply across all chains is.",
"events": {
"Approval(address,address,uint256)": {
"details": "Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance."
},
"Initialized(uint8)": {
"details": "Triggered when the contract has been initialized or reinitialized."
},
"ReceivedTransferRemote(uint32,bytes32,uint256)": {
"details": "Emitted on `_handle` when a transfer message is processed.",
"params": {
"amountOrId": "The amount or ID of tokens received from the remote sender.",
"origin": "The identifier of the origin chain.",
"recipient": "The address of the recipient on the destination chain."
}
},
"SentTransferRemote(uint32,bytes32,uint256)": {
"details": "Emitted on `transferRemote` when a transfer message is dispatched.",
"params": {
"amountOrId": "The amount or ID of tokens sent in to the remote recipient.",
"destination": "The identifier of the destination chain.",
"recipient": "The address of the recipient on the destination chain."
}
},
"Transfer(address,address,uint256)": {
"details": "Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero."
}
},
"kind": "dev",
"methods": {
"allowance(address,address)": {
"details": "See {IERC20-allowance}."
},
"approve(address,uint256)": {
"details": "See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address."
},
"balanceOf(address)": {
"details": "See {IERC20-balanceOf}."
},
"decimals()": {
"details": "Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it's overridden. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}."
},
"decreaseAllowance(address,uint256)": {
"details": "Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`."
},
"enrollRemoteRouter(uint32,bytes32)": {
"params": {
"_domain": "The domain of the remote Application Router",
"_router": "The address of the remote Application Router"
}
},
"enrollRemoteRouters(uint32[],bytes32[])": {
"params": {
"_addresses": "The addresses of the remote Application Routers",
"_domains": "The domains of the remote Application Routers"
}
},
"feeHook()": {
"returns": {
"_0": "The fee hook address."
}
},
"feeRecipient()": {
"details": "Returns address(0) if no fee recipient is set.Can be overridden with address(0) to disable fees entirely.",
"returns": {
"_0": "address of the fee recipient."
}
},
"feeToken()": {
"returns": {
"_0": "The token address if a fee hook is configured, otherwise address(0) for native payments."
}
},
"handle(uint32,bytes32,bytes)": {
"params": {
"_message": "The message",
"_origin": "The origin domain",
"_sender": "The sender address"
}
},
"increaseAllowance(address,uint256)": {
"details": "Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address."
},
"initialize(uint256,string,string,address,address,address)": {
"params": {
"_name": "The name of the token.",
"_symbol": "The symbol of the token.",
"_totalSupply": "The initial supply of the token."
}
},
"name()": {
"details": "Returns the name of the token."
},
"owner()": {
"details": "Returns the address of the current owner."
},
"quoteGasPayment(uint32)": {
"params": {
"_destinationDomain": "The domain of the router."
},
"returns": {
"_0": "_gasPayment Payment computed by the registered InterchainGasPaymaster."
}
},
"quoteTransferRemote(uint32,bytes32,uint256)": {
"details": "This function may return multiple quotes with the same denomination. Convention is to return: [index 0] native fees charged by the mailbox dispatch [index 1] then any internal warp route fees (amount bridged plus fee recipient) [index 2] then any external bridging fees (if any, else 0) These are surfaced as separate elements to enable clients to interpret/render fees independently. There is a Quotes library with an extract function for onchain quoting in a specific denomination, but we discourage onchain quoting in favor of offchain quoting and overpaying with refunds.",
"params": {
"_amount": "The amount or identifier of tokens to be sent to the remote recipient",
"_destination": "The identifier of the destination chain.",
"_recipient": "The address of the recipient on the destination chain."
},
"returns": {
"quotes": "An array of Quote structs representing the fees in different tokens."
}
},
"renounceOwnership()": {
"details": "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."
},
"routers(uint32)": {
"details": "Returns 0 address if no router is enrolled for the given domain",
"params": {
"_domain": "The remote domain ID."
},
"returns": {
"_0": "router The address of the Router contract for the given domain"
}
},
"setDestinationGas((uint32,uint256)[])": {
"params": {
"gasConfigs": "The array of GasRouterConfig structs"
}
},
"setDestinationGas(uint32,uint256)": {
"params": {
"domain": "The destination domain ID",
"gas": "The gas limit"
}
},
"setFeeHook(address)": {
"params": {
"_feeHook": "The fee hook address."
}
},
"setFeeRecipient(address)": {
"details": "Allows for address(0) to be set, which disables fees.",
"params": {
"recipient": "The address that receives fees."
}
},
"setHook(address)": {
"params": {
"_hook": "The address of the hook contract."
}
},
"setInterchainSecurityModule(address)": {
"params": {
"_module": "The address of the interchain security module contract."
}
},
"symbol()": {
"details": "Returns the symbol of the token, usually a shorter version of the name."
},
"token()": {
"details": "This function must be implemented by derived contracts to specify the token address.",
"returns": {
"_0": "The address of the token contract."
}
},
"totalSupply()": {
"details": "See {IERC20-totalSupply}."
},
"transfer(address,uint256)": {
"details": "See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`."
},
"transferFrom(address,address,uint256)": {
"details": "See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`."
},
"transferOwnership(address)": {
"details": "Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner."
},
"transferRemote(uint32,bytes32,uint256)": {
"details": "Delegates transfer logic to `_transferFromSender` implementation. Emits `SentTransferRemote` event on the origin chain. Override with custom behavior for storing or forwarding tokens. Known overrides: - OPL2ToL1TokenBridgeNative: adds hook metadata for message dispatch. - EverclearTokenBridge: creates Everclear intent for cross-chain token transfer. - TokenBridgeCctpBase: adds CCTP-specific metadata for message dispatch. - HypERC4626Collateral: deposits into vault and handles shares. When overriding, mirror the general flow of this function for consistency: 1. Calculate fees and charge the sender. 2. Prepare the token message with recipient, amount, and any additional metadata. 3. Emit `SentTransferRemote` event. 4. Dispatch the message.",
"params": {
"_amount": "The amount or identifier of tokens to be sent to the remote recipient.",
"_destination": "The identifier of the destination chain.",
"_recipient": "The address of the recipient on the destination chain."
},
"returns": {
"messageId": "The identifier of the dispatched message."
}
},
"unenrollRemoteRouter(uint32)": {
"params": {
"_domain": "The domain of the remote Application Router"
}
},
"unenrollRemoteRouters(uint32[])": {
"params": {
"_domains": "The domains of the remote Application Routers"
}
}
},
"title": "Hyperlane ERC20 Token Router that extends ERC20 with remote transfer functionality.",
"version": 1
},
"userdoc": {
"kind": "user",
"methods": {
"enrollRemoteRouter(uint32,bytes32)": {
"notice": "Register the address of a Router contract for the same Application on a remote chain"
},
"enrollRemoteRouters(uint32[],bytes32[])": {
"notice": "Batch version of `enrollRemoteRouter`"
},
"feeHook()": {
"notice": "Returns the fee hook contract address."
},
"feeRecipient()": {
"notice": "Returns the address of the fee recipient."
},
"feeToken()": {
"notice": "Returns the fee token address for gas payments."
},
"handle(uint32,bytes32,bytes)": {
"notice": "Handles an incoming message"
},
"initialize(uint256,string,string,address,address,address)": {
"notice": "Initializes the Hyperlane router, ERC20 metadata, and mints initial supply to deployer."
},
"quoteGasPayment(uint32)": {
"notice": "Returns the gas payment required to dispatch a message to the given domain's router."
},
"quoteTransferRemote(uint32,bytes32,uint256)": {
"notice": "Implements the standardized fee quoting interface for token transfers based on overridable internal functions of _quoteGasPayment, _feeRecipientAndAmount, and _externalFeeAmount."
},
"routers(uint32)": {
"notice": "Returns the address of the Router contract for the given domain"
},
"setDestinationGas((uint32,uint256)[])": {
"notice": "Sets the gas amount dispatched for each configured domain."
},
"setDestinationGas(uint32,uint256)": {
"notice": "Sets the gas amount dispatched for each configured domain."
},
"setFeeHook(address)": {
"notice": "Sets the fee hook contract address."
},
"setFeeRecipient(address)": {
"notice": "Sets the fee recipient for the router."
},
"setHook(address)": {
"notice": "Sets the address of the application's custom hook."
},
"setInterchainSecurityModule(address)": {
"notice": "Sets the address of the application's custom interchain security module."
},
"token()": {
"notice": "Returns the address of the token managed by this router. It can be one of three options: - ERC20 token address for fungible tokens that are being collateralized (HypERC20Collateral, HypERC4626, etc.) - 0x0 address for native tokens (ETH, MATIC, etc.) (HypNative, etc.) - address(this) for synthetic ERC20 tokens (HypERC20, etc.) It is being used for quotes and fees from the fee recipient and pulling/push the tokens from the sender/receipient."
},
"transferRemote(uint32,bytes32,uint256)": {
"notice": "Transfers `_amount` token to `_recipient` on the `_destination` domain."
},
"unenrollRemoteRouter(uint32)": {
"notice": "Unregister the domain"
},
"unenrollRemoteRouters(uint32[])": {
"notice": "Batch version of `unenrollRemoteRouter`"
}
},
"version": 1
}
},
"settings": {
"compilationTarget": {
"@hyperlane-xyz/core/contracts/token/HypERC20.sol": "HypERC20"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [],
"viaIR": true
},
"sources": {
"@hyperlane-xyz/core/contracts/PackageVersioned.sol": {
"keccak256": "0x972f70a6053548a508c149506d5f18f9e7987dd1a0a198ca828182866ea6c2ba",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://fe9218b5df820326d9f2de0a0655a5657e06daca949253b913b5fc710bff90b1",
"dweb:/ipfs/QmV4TawNXAUzx3HdDQ6tsReN45jvDoUpEbT5PnDMLqYqCw"
]
},
"@hyperlane-xyz/core/contracts/client/GasRouter.sol": {
"keccak256": "0xd1ee79d598b2f5f4230766d8c764ab9dc77b40d6f9da40e1d85262915e09b89f",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://3abb9530098ed116c3b19f68548f982d4acdecd5186d15fce7be9f1ec5d83a4c",
"dweb:/ipfs/QmQmm8wWQEGJARU5376sRfCTrtN7cVJ3MVMPyv5fAwRsUX"
]
},
"@hyperlane-xyz/core/contracts/client/MailboxClient.sol": {
"keccak256": "0xe09c109dc8c4fad4fdf9a8198cab0caed183033ae228d4d87a5c5ea4b824a435",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://918439fdd0be8efa65a8b36938296e46353080fe6734dfc96e4cee0a8de3bf78",
"dweb:/ipfs/QmVhxFx3FTMe3nrfk17xNi6LxJb7u2ZEjtChGy1oCULkZD"
]
},
"@hyperlane-xyz/core/contracts/client/Router.sol": {
"keccak256": "0x5e87e9ddbf0ed57f7fdc41d965e296bac2cb274dff0f394306e74ce1a7777b0b",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://d67020dc0fcb74db77aaa304ab0ce877f02a2d76149002bf19d080673aa3b9ac",
"dweb:/ipfs/QmWNvjzcJVfaFuijNRGKT8pYwbAkH3wmZHtpmyRZyNeLX3"
]
},
"@hyperlane-xyz/core/contracts/hooks/libs/StandardHookMetadata.sol": {
"keccak256": "0x972e1023165a8fca7f09a62e4533e67317823a134a3190d689271fb897a41829",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://0633187fa56cdfaabaad04a25032ced809b031abb1d2ff8264dfa35c92c27f1e",
"dweb:/ipfs/QmRQwJPnxCFUYJrkd5KuwK41qDsYSSEe72ukDUpM89rVFn"
]
},
"@hyperlane-xyz/core/contracts/interfaces/IInterchainSecurityModule.sol": {
"keccak256": "0x8688e0596eec175bb02180ceb7c0ef272ea1c46c01a32061dad1a7f6c672bdda",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://5ed68e8c0a667f69ca7ff53d83a07ca10d2c96cd38fa1498d4fa5c99c6c85f4b",
"dweb:/ipfs/QmZ2eCeKmftZUEwfWfNfGPhE9FCo2a2RQXrhoEk9Ft8jtU"
]
},
"@hyperlane-xyz/core/contracts/interfaces/IMailbox.sol": {
"keccak256": "0x836c3b6125c963a97ab140b01a82f1bab135ff46b1964d18603dce417ed0e7fa",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://4472eb0ffdbed054b02fa5c10ac3ffa12d3506b19771cdd760603c4819f9ee50",
"dweb:/ipfs/QmVjbVNtmiobLSLurDyMki1WNqw2LCN8trExb9m2kZ8rBf"
]
},
"@hyperlane-xyz/core/contracts/interfaces/IMessageRecipient.sol": {
"keccak256": "0x145e8332a91295a710deb3cb1ab689144262ef6ec66d9570c600b778e9dd964d",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://a22ad97b1d8d3a37e8b4ad1519b893ac7cdf718c3a340999ffef4fb04060f119",
"dweb:/ipfs/QmXp3w8yPm1vHyNrrSLr4YtRMP44eLadHnXSAjSecqB7H6"
]
},
"@hyperlane-xyz/core/contracts/interfaces/ITokenBridge.sol": {
"keccak256": "0xf2d206e588408fb0a2ea48cbf9346a1227777d79a087eb6b22dddb599be332b4",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://139400456496d7ea4e60c1648f3bc3512845745d249caeb79e55858d7612de28",
"dweb:/ipfs/QmUXCtH57mC1PPDAe6e8hw23CajmWYsBWZqDTFD4m6y8L4"
]
},
"@hyperlane-xyz/core/contracts/interfaces/hooks/IPostDispatchHook.sol": {
"keccak256": "0xa23968578650878f614f3eea742e1557bc07512053d484260672aa9895791c67",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://ffa5c14593f218f020857cef2fb3d2ae1a574d2b0f8ec42694fc5086b92a3cb0",
"dweb:/ipfs/QmYq5pFDScp6Yjw6YxoWXxHCDgbxucfyZZ3vyMShzVFrnV"
]
},
"@hyperlane-xyz/core/contracts/libs/EnumerableMapExtended.sol": {
"keccak256": "0xbd661cdeba756caf35191b71a85461a9ff79c047ec98ec05063748dfc0419595",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://d88af58f2f47a6ad7c24abef9419d1474cba6e372830cc82794e37943dc3d9ce",
"dweb:/ipfs/QmbaTGUtTbtxmVnZWTq5Kt6ATmHXmrUssXPXGd6F3NkEMc"
]
},
"@hyperlane-xyz/core/contracts/libs/Message.sol": {
"keccak256": "0x5319af5ade07bcb021d6373f0713f24f34431def78cda16fea6755f580fb5e78",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://f531eecebd22a535398def83b078aff4f72d88940a0e9474ad3244a555f00d53",
"dweb:/ipfs/QmQjtjpf4qwaM9QVyWBsogRvZeokKESTVdsX3z9mt1wZFa"
]
},
"@hyperlane-xyz/core/contracts/libs/TypeCasts.sol": {
"keccak256": "0xa4329f368c22062ccc725593c5c552796ce923cf66191cb9681f4f17fea8631f",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://4e8c22116d69888bbda6db11f5dfafb362ac9da4226373c7162953de81f57229",
"dweb:/ipfs/QmdvzDSFiftDgzDwbPBLMWdGBATbmkqCP5aKNdomm1cY33"
]
},
"@hyperlane-xyz/core/contracts/token/HypERC20.sol": {
"keccak256": "0xcf2379ebbc9de1d6c2d7b108c883094e06a3a6843e43efd850a4559c272c1031",
"license": "Apache-2.0",
"urls": [
"bzz-raw://a37c06ce6dd256e0685eb17b06e97dcb80ed45e18550ee34475af19f2f588262",
"dweb:/ipfs/QmPioJoe2gYkMA1dEnKsiFAEhJkKKnQZmdx3NLbgHRW9GU"
]
},
"@hyperlane-xyz/core/contracts/token/libs/Quotes.sol": {
"keccak256": "0x7988c30d300502fae65b6e45bbfe990910285ddb8eabed86e2b41d954f2eeafc",
"license": "Apache-2.0",
"urls": [
"bzz-raw://4f591933d426563a1f7d469a9e87b94416da76090ae7c58d1a8dfee309cd15e8",
"dweb:/ipfs/QmNkoE7Xpy32KN1FcZsSyKSVaAKE97SSzY4qXS7dQ34nyn"
]
},
"@hyperlane-xyz/core/contracts/token/libs/TokenMessage.sol": {
"keccak256": "0xb9dfb7844e1084a3a2f40f2bba764d8494325fa04dc3c70e0d30c30bc125996e",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://003d2a20fdd5ca2f46fe8f98b527bf284b0776c0a223bd3eebaafd467fe5e8d4",
"dweb:/ipfs/QmfC1Erb7KVjLqvxKXn3NjPjFiTm4mXMAZXWNZ1gJKvGM1"
]
},
"@hyperlane-xyz/core/contracts/token/libs/TokenRouter.sol": {
"keccak256": "0x109495491f44a9b3e6b4cbfae46a12a8f3705eb2c0cf9992dff18c0239121fb5",
"license": "MIT OR Apache-2.0",
"urls": [
"bzz-raw://e15b14c0976c40a378523b1ab6148234777348a22052dc0441e2bebc7b120e89",
"dweb:/ipfs/QmPKbGAKC41QBzVSBkt46Ls1BqBbbhytgBkkPraQMkwPJZ"
]
},
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
"keccak256": "0x359a1ab89b46b9aba7bcad3fb651924baf4893d15153049b9976b0fc9be1358e",
"license": "MIT",
"urls": [
"bzz-raw://e89863421b4014b96a4b62be76eb3b9f0a8afe9684664a6f389124c0964bfe5c",
"dweb:/ipfs/Qmbk7xr1irpDuU1WdxXgxELBXxs61rHhCgod7heVcvFx16"
]
},
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"keccak256": "0x89be10e757d242e9b18d5a32c9fbe2019f6d63052bbe46397a430a1d60d7f794",
"license": "MIT",
"urls": [
"bzz-raw://f103ee2e4aecd37aac6ceefe670709cdd7613dee25fa2d4d9feaf7fc0aaa155e",
"dweb:/ipfs/QmRiNZLoJk5k3HPMYGPGjZFd2ke1ZxjhJZkM45Ec9GH9hv"
]
},
"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol": {
"keccak256": "0xa9311aeb22f459e57d4dac77ee76cf43fb28ad3215278456211b5852b0e9e970",
"license": "MIT",
"urls": [
"bzz-raw://ebdf0d3e42bd25223e45a213311d6d7e177d56a2c541a78b58c0c9d10bbdfbf9",
"dweb:/ipfs/QmfMyehJ6pxHrh7yL4793J6i7dofXnS2zH3cTtC8JdQMV9"
]
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"keccak256": "0x0e1f0f5f62f67a881cd1a9597acbc0a5e4071f3c2c10449a183b922ae7272e3f",
"license": "MIT",
"urls": [
"bzz-raw://c25f742ff154998d19a669e2508c3597b363e123ce9144cd0fcf6521229f401f",
"dweb:/ipfs/QmQXRuFzStEWqeEPbhQU6cAg9PaSowxJVo4PDKyRod7dco"
]
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
"keccak256": "0x605434219ebbe4653f703640f06969faa5a1d78f0bfef878e5ddbb1ca369ceeb",
"license": "MIT",
"urls": [
"bzz-raw://4c9c634f99dd02d73ce7498b03a6305e251c05eeebb71457306561c1fab0fa7d",
"dweb:/ipfs/QmbYRBbZHy8YoaQKXdPryiL3CSS7uUaRfRYi1TUj9cTqJQ"
]
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"keccak256": "0x9c80f545915582e63fe206c6ce27cbe85a86fc10b9cd2a0e8c9488fb7c2ee422",
"license": "MIT",
"urls": [
"bzz-raw://310136ad60820af4177a11a61d77a3686faf5fca4942b600e08fc940db38396b",
"dweb:/ipfs/QmbCzMNSTL7Zi7M4UCSqBrkHtp4jjxUnGbkneCZKdR1qeq"
]
},
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
"keccak256": "0x75097e35253e7fb282ee4d7f27a80eaacfa759923185bf17302a89cbc059c5ef",
"license": "MIT",
"urls": [
"bzz-raw://8b06267c5f80bad727af3e48b1382333d591dad51376399ef2f6b0ee6d58bf95",
"dweb:/ipfs/QmdU5La1agcQvghnfMpWZGDPz2TUDTCxUwTLKmuMRXBpAx"
]
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"keccak256": "0x287b55befed2961a7eabd7d7b1b2839cbca8a5b80ef8dcbb25ed3d4c2002c305",
"license": "MIT",
"urls": [
"bzz-raw://bd39944e8fc06be6dbe2dd1d8449b5336e23c6a7ba3e8e9ae5ae0f37f35283f5",
"dweb:/ipfs/QmPV3FGYjVwvKSgAXKUN3r9T9GwniZz83CxBpM7vyj2G53"
]
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"keccak256": "0xb264c03a3442eb37a68ad620cefd1182766b58bee6cec40343480392d6b14d69",
"license": "MIT",
"urls": [
"bzz-raw://28879d01fd22c07b44f006612775f8577defbe459cb01685c5e25cd518c91a71",
"dweb:/ipfs/QmVgfkwv2Fxw6hhTcDUZhE7NkoSKjab3ipM7UaRbt6uXb5"
]
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"keccak256": "0xabefac93435967b4d36a4fabcbdbb918d1f0b7ae3c3d85bc30923b326c927ed1",
"license": "MIT",
"urls": [
"bzz-raw://9d213d3befca47da33f6db0310826bcdb148299805c10d77175ecfe1d06a9a68",
"dweb:/ipfs/QmRgCn6SP1hbBkExUADFuDo8xkT4UU47yjNF5FhCeRbQmS"
]
},
"@openzeppelin/contracts/utils/Address.sol": {
"keccak256": "0x006dd67219697fe68d7fbfdea512e7c4cb64a43565ed86171d67e844982da6fa",
"license": "MIT",
"urls": [
"bzz-raw://2455248c8ddd9cc6a7af76a13973cddf222072427e7b0e2a7d1aff345145e931",
"dweb:/ipfs/QmfYjnjRbWqYpuxurqveE6HtzsY1Xx323J428AKQgtBJZm"
]
},
"@openzeppelin/contracts/utils/StorageSlot.sol": {
"keccak256": "0xf09e68aa0dc6722a25bc46490e8d48ed864466d17313b8a0b254c36b54e49899",
"license": "MIT",
"urls": [
"bzz-raw://e26daf81e2252dc1fe1ce0e4b55c2eb7c6d1ee84ae6558d1a9554432ea1d32da",
"dweb:/ipfs/Qmb1UANWiWq5pCKbmHSu772hd4nt374dVaghGmwSVNuk8Q"
]
},
"@openzeppelin/contracts/utils/Strings.sol": {
"keccak256": "0x3088eb2868e8d13d89d16670b5f8612c4ab9ff8956272837d8e90106c59c14a0",
"license": "MIT",
"urls": [
"bzz-raw://b81d9ff6559ea5c47fc573e17ece6d9ba5d6839e213e6ebc3b4c5c8fe4199d7f",
"dweb:/ipfs/QmPCW1bFisUzJkyjroY3yipwfism9RRCigCcK1hbXtVM8n"
]
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"keccak256": "0xe4455ac1eb7fc497bb7402579e7b4d64d928b846fce7d2b6fde06d366f21c2b3",
"license": "MIT",
"urls": [
"bzz-raw://cc8841b3cd48ad125e2f46323c8bad3aa0e88e399ec62acb9e57efa7e7c8058c",
"dweb:/ipfs/QmSqE4mXHA2BXW58deDbXE8MTcsL5JSKNDbm23sVQxRLPS"
]
},
"@openzeppelin/contracts/utils/math/SignedMath.sol": {
"keccak256": "0xf92515413956f529d95977adc9b0567d583c6203fc31ab1c23824c35187e3ddc",
"license": "MIT",
"urls": [
"bzz-raw://c50fcc459e49a9858b6d8ad5f911295cb7c9ab57567845a250bf0153f84a95c7",
"dweb:/ipfs/QmcEW85JRzvDkQggxiBBLVAasXWdkhEysqypj9EaB6H2g6"
]
},
"@openzeppelin/contracts/utils/structs/EnumerableMap.sol": {
"keccak256": "0x7ebfe2422bc571599c2ec20577d7848e1e7a0acf85fa7c2d9636618bbbdf6fca",
"license": "MIT",
"urls": [
"bzz-raw://77fb3f64d470c92c3142e3c07d2f18ad78723a1f1e680a251dcde37e865d0636",
"dweb:/ipfs/QmXAeNPRRGfNSRxi1d17QjkNTBZFemhiMzJVvEJgMWwqUW"
]
},
"@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
"keccak256": "0x9f4357008a8f7d8c8bf5d48902e789637538d8c016be5766610901b4bba81514",
"license": "MIT",
"urls": [
"bzz-raw://20bf19b2b851f58a4c24543de80ae70b3e08621f9230eb335dc75e2d4f43f5df",
"dweb:/ipfs/QmSYuH1AhvJkPK8hNvoPqtExBcgTB42pPRHgTHkS5c5zYW"
]
}
},
"version": 1
}
},
"deployment": null
}