Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/chain-adapters/Polygon_Adapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./interfaces/AdapterInterface.sol";
import "../external/interfaces/WETH9Interface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../libraries/CircleCCTPAdapter.sol";
import "../external/interfaces/CCTPInterfaces.sol";
import { IOFT } from "../interfaces/IOFT.sol";
import { OFTTransportAdapterWithStore } from "../libraries/OFTTransportAdapterWithStore.sol";
/**
* @notice Send tokens to Polygon.
*/
interface IRootChainManager {
/**
* @notice Send msg.value of ETH to Polygon
* @param user Recipient of ETH on Polygon.
*/
function depositEtherFor(address user) external payable;
/**
* @notice Send ERC20 tokens to Polygon.
* @param user Recipient of L2 equivalent tokens on Polygon.
* @param rootToken L1 Address of token to send.
* @param depositData Data to pass to L2 including amount of tokens to send. Should be abi.encode(amount).
*/
function depositFor(address user, address rootToken, bytes calldata depositData) external;
}
/**
* @notice Send arbitrary messages to Polygon.
*/
interface IFxStateSender {
/**
* @notice Send arbitrary message to Polygon.
* @param _receiver Address on Polygon to receive message.
* @param _data Message to send to `_receiver` on Polygon.
*/
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
/**
* @notice Similar to RootChainManager, but for Matic (Plasma) bridge.
*/
interface DepositManager {
/**
* @notice Send tokens to Polygon. Only used to send MATIC in this Polygon_Adapter.
* @param token L1 token to send. Should be MATIC.
* @param user Recipient of L2 equivalent tokens on Polygon.
* @param amount Amount of `token` to send.
*/
function depositERC20ForUser(address token, address user, uint256 amount) external;
}
/**
* @notice Sends cross chain messages Polygon L2 network.
* @dev Public functions calling external contracts do not guard against reentrancy because they are expected to be
* called via delegatecall, which will execute this contract's logic within the context of the originating contract.
* For example, the HubPool will delegatecall these functions, therefore its only necessary that the HubPool's methods
* that call this contract's logic guard against reentrancy.
* @custom:security-contact bugs@across.to
*/
// solhint-disable-next-line contract-name-camelcase
contract Polygon_Adapter is AdapterInterface, CircleCCTPAdapter, OFTTransportAdapterWithStore {
using SafeERC20 for IERC20;
IRootChainManager public immutable ROOT_CHAIN_MANAGER;
IFxStateSender public immutable FX_STATE_SENDER;
DepositManager public immutable DEPOSIT_MANAGER;
address public immutable ERC20_PREDICATE;
address public immutable L1_MATIC;
WETH9Interface public immutable L1_WETH;
/**
* @notice Constructs new Adapter.
* @param _rootChainManager RootChainManager Polygon system contract to deposit tokens over the PoS bridge.
* @param _fxStateSender FxStateSender Polygon system contract to send arbitrary messages to L2.
* @param _depositManager DepositManager Polygon system contract to deposit tokens over the Plasma bridge (Matic).
* @param _erc20Predicate ERC20Predicate Polygon system contract to approve when depositing to the PoS bridge.
* @param _l1Matic matic address on l1.
* @param _l1Weth WETH address on L1.
* @param _l1Usdc USDC address on L1.
* @param _cctpTokenMessenger TokenMessenger contract to bridge via CCTP.
* @param _adapterStore Helper storage contract to support bridging via OFT
* @param _oftDstEid destination endpoint id for OFT messaging
* @param _oftFeeCap A fee cap we apply to OFT bridge native payment. A good default is 1 ether
*/
constructor(
IRootChainManager _rootChainManager,
IFxStateSender _fxStateSender,
DepositManager _depositManager,
address _erc20Predicate,
address _l1Matic,
WETH9Interface _l1Weth,
IERC20 _l1Usdc,
ITokenMessenger _cctpTokenMessenger,
address _adapterStore,
uint32 _oftDstEid,
uint256 _oftFeeCap
)
CircleCCTPAdapter(_l1Usdc, _cctpTokenMessenger, CircleDomainIds.Polygon)
OFTTransportAdapterWithStore(_oftDstEid, _oftFeeCap, _adapterStore)
{
ROOT_CHAIN_MANAGER = _rootChainManager;
FX_STATE_SENDER = _fxStateSender;
DEPOSIT_MANAGER = _depositManager;
ERC20_PREDICATE = _erc20Predicate;
L1_MATIC = _l1Matic;
L1_WETH = _l1Weth;
}
/**
* @notice Send cross-chain message to target on Polygon.
* @param target Contract on Polygon that will receive message.
* @param message Data to send to target.
*/
function relayMessage(address target, bytes calldata message) external payable override {
FX_STATE_SENDER.sendMessageToChild(target, message);
emit MessageRelayed(target, message);
}
/**
* @notice Bridge tokens to Polygon.
* @param l1Token L1 token to deposit.
* @param l2Token L2 token to receive.
* @param amount Amount of L1 tokens to deposit and L2 tokens to receive.
* @param to Bridge recipient.
*/
function relayTokens(address l1Token, address l2Token, uint256 amount, address to) external payable override {
address oftMessenger = _getOftMessenger(l1Token);
// If the l1Token is weth then unwrap it to ETH then send the ETH to the standard bridge.
if (l1Token == address(L1_WETH)) {
L1_WETH.withdraw(amount);
ROOT_CHAIN_MANAGER.depositEtherFor{ value: amount }(to);
}
// If the l1Token is USDC, then we send it to the CCTP bridge
else if (_isCCTPEnabled() && l1Token == address(usdcToken)) {
_transferUsdc(to, amount);
} else if (oftMessenger != address(0)) {
_transferViaOFT(IERC20(l1Token), IOFT(oftMessenger), to, amount);
} else if (l1Token == L1_MATIC) {
IERC20(l1Token).safeIncreaseAllowance(address(DEPOSIT_MANAGER), amount);
DEPOSIT_MANAGER.depositERC20ForUser(l1Token, to, amount);
} else {
IERC20(l1Token).safeIncreaseAllowance(ERC20_PREDICATE, amount);
ROOT_CHAIN_MANAGER.depositFor(to, l1Token, abi.encode(amount));
}
emit TokensRelayed(l1Token, l2Token, amount, to);
}
}
"
},
"contracts/chain-adapters/interfaces/AdapterInterface.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/**
* @notice Sends cross chain messages and tokens to contracts on a specific L2 network.
* This interface is implemented by an adapter contract that is deployed on L1.
*/
interface AdapterInterface {
event MessageRelayed(address target, bytes message);
event TokensRelayed(address l1Token, address l2Token, uint256 amount, address to);
/**
* @notice Send message to `target` on L2.
* @dev This method is marked payable because relaying the message might require a fee
* to be paid by the sender to forward the message to L2. However, it will not send msg.value
* to the target contract on L2.
* @param target L2 address to send message to.
* @param message Message to send to `target`.
*/
function relayMessage(address target, bytes calldata message) external payable;
/**
* @notice Send `amount` of `l1Token` to `to` on L2. `l2Token` is the L2 address equivalent of `l1Token`.
* @dev This method is marked payable because relaying the message might require a fee
* to be paid by the sender to forward the message to L2. However, it will not send msg.value
* to the target contract on L2.
* @param l1Token L1 token to bridge.
* @param l2Token L2 token to receive.
* @param amount Amount of `l1Token` to bridge.
* @param to Bridge recipient.
*/
function relayTokens(
address l1Token,
address l2Token,
uint256 amount,
address to
) external payable;
}
"
},
"contracts/external/interfaces/WETH9Interface.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/**
* @notice Interface for the WETH9 contract.
*/
interface WETH9Interface {
/**
* @notice Burn Wrapped Ether and receive native Ether.
* @param wad Amount of WETH to unwrap and send to caller.
*/
function withdraw(uint256 wad) external;
/**
* @notice Lock native Ether and mint Wrapped Ether ERC20
* @dev msg.value is amount of Wrapped Ether to mint/Ether to lock.
*/
function deposit() external payable;
/**
* @notice Get balance of WETH held by `guy`.
* @param guy Address to get balance of.
* @return wad Amount of WETH held by `guy`.
*/
function balanceOf(address guy) external view returns (uint256 wad);
/**
* @notice Transfer `wad` of WETH from caller to `guy`.
* @param guy Address to send WETH to.
* @param wad Amount of WETH to send.
* @return ok True if transfer succeeded.
*/
function transfer(address guy, uint256 wad) external returns (bool);
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// 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);
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// 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));
}
}
"
},
"contracts/libraries/CircleCCTPAdapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../external/interfaces/CCTPInterfaces.sol";
import { AddressToBytes32 } from "../libraries/AddressConverters.sol";
library CircleDomainIds {
uint32 public constant Ethereum = 0;
uint32 public constant Optimism = 2;
uint32 public constant Arbitrum = 3;
uint32 public constant Solana = 5;
uint32 public constant Base = 6;
uint32 public constant Polygon = 7;
uint32 public constant DoctorWho = 10;
uint32 public constant Linea = 11;
uint32 public constant UNINITIALIZED = type(uint32).max;
}
/**
* @notice Facilitate bridging USDC via Circle's CCTP.
* @dev This contract is intended to be inherited by other chain-specific adapters and spoke pools.
* @custom:security-contact bugs@across.to
*/
abstract contract CircleCCTPAdapter {
using SafeERC20 for IERC20;
using AddressToBytes32 for address;
/**
* @notice The domain ID that CCTP will transfer funds to.
* @dev This identifier is assigned by Circle and is not related to a chain ID.
* @dev Official domain list can be found here: https://developers.circle.com/stablecoins/docs/supported-domains
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint32 public immutable recipientCircleDomainId;
/**
* @notice The official USDC contract address on this chain.
* @dev Posted officially here: https://developers.circle.com/stablecoins/docs/usdc-on-main-networks
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IERC20 public immutable usdcToken;
/**
* @notice The official Circle CCTP token bridge contract endpoint.
* @dev Posted officially here: https://developers.circle.com/stablecoins/docs/evm-smart-contracts
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
ITokenMessenger public immutable cctpTokenMessenger;
/**
* @notice Indicates if the CCTP V2 TokenMessenger is being used.
* @dev This is determined by checking if the feeRecipient() function exists and returns a non-zero address.
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
bool public immutable cctpV2;
/**
* @notice intiailizes the CircleCCTPAdapter contract.
* @param _usdcToken USDC address on the current chain.
* @param _cctpTokenMessenger TokenMessenger contract to bridge via CCTP. If the zero address is passed, CCTP bridging will be disabled.
* @param _recipientCircleDomainId The domain ID that CCTP will transfer funds to.
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(
IERC20 _usdcToken,
/// @dev This should ideally be an address but it's kept as an ITokenMessenger to avoid rippling changes to the
/// constructors for every SpokePool/Adapter.
ITokenMessenger _cctpTokenMessenger,
uint32 _recipientCircleDomainId
) {
usdcToken = _usdcToken;
cctpTokenMessenger = _cctpTokenMessenger;
recipientCircleDomainId = _recipientCircleDomainId;
// Only the CCTP V2 TokenMessenger has a feeRecipient() function, so we use it to
// figure out if we are using CCTP V2 or V1. `success` can be true even if the contract doesn't
// implement feeRecipient but it has a fallback function so to be extra safe, we check the return value
// of feeRecipient() as well.
(bool success, bytes memory feeRecipient) = address(cctpTokenMessenger).staticcall(
abi.encodeWithSignature("feeRecipient()")
);
// In case of a call to nonexistent contract or a call to a contract with a fallback function which
// doesn't return any data, feeRecipient can be empty so check its length.
// Even with this check, it's possible that the contract has implemented a fallback function that returns
// 32 bytes of data but its not actually the feeRecipient address. This is extremely low risk but worth
// mentioning that the following check is not 100% safe.
cctpV2 = (success &&
feeRecipient.length == 32 &&
address(uint160(uint256(bytes32(feeRecipient)))) != address(0));
}
/**
* @notice Returns whether or not the CCTP bridge is enabled.
* @dev If the CCTPTokenMessenger is the zero address, CCTP bridging is disabled.
*/
function _isCCTPEnabled() internal view returns (bool) {
return address(cctpTokenMessenger) != address(0);
}
/**
* @notice Transfers USDC from the current domain to the given address on the new domain.
* @dev This function will revert if the CCTP bridge is disabled. I.e. if the zero address is passed to the constructor for the cctpTokenMessenger.
* @param to Address to receive USDC on the new domain.
* @param amount Amount of USDC to transfer.
*/
function _transferUsdc(address to, uint256 amount) internal {
_transferUsdc(to.toBytes32(), amount);
}
/**
* @notice Transfers USDC from the current domain to the given address on the new domain.
* @dev This function will revert if the CCTP bridge is disabled. I.e. if the zero address is passed to the constructor for the cctpTokenMessenger.
* @param to Address to receive USDC on the new domain represented as bytes32.
* @param amount Amount of USDC to transfer.
*/
function _transferUsdc(bytes32 to, uint256 amount) internal {
// Only approve the exact amount to be transferred
usdcToken.safeIncreaseAllowance(address(cctpTokenMessenger), amount);
// Submit the amount to be transferred to bridge via the TokenMessenger.
// If the amount to send exceeds the burn limit per message, then split the message into smaller parts.
// @dev We do not care about casting cctpTokenMessenger to ITokenMessengerV2 since both V1 and V2
// expose a localMinter() view function that returns either an ITokenMinterV1 or ITokenMinterV2. Regardless,
// we only care about the burnLimitsPerMessage function which is available in both versions and performs
// the same logic, therefore we purposefully do not re-cast the cctpTokenMessenger and cctpMinter
// to the specific version.
ITokenMinter cctpMinter = cctpTokenMessenger.localMinter();
uint256 burnLimit = cctpMinter.burnLimitsPerMessage(address(usdcToken));
uint256 remainingAmount = amount;
while (remainingAmount > 0) {
uint256 partAmount = remainingAmount > burnLimit ? burnLimit : remainingAmount;
if (cctpV2) {
// Uses the CCTP V2 "standard transfer" speed and
// therefore pays no additional fee for the transfer to be sped up.
ITokenMessengerV2(address(cctpTokenMessenger)).depositForBurn(
partAmount,
recipientCircleDomainId,
to,
address(usdcToken),
// The following parameters are new in this function from V2 to V1, can read more here:
// https://developers.circle.com/stablecoins/evm-smart-contracts
bytes32(0), // destinationCaller is set to bytes32(0) to indicate that anyone can call
// receiveMessage on the destination to finalize the transfer
0, // maxFee can be set to 0 for a "standard transfer"
2000 // minFinalityThreshold can be set to 2000 for a "standard transfer",
// https://github.com/circlefin/evm-cctp-contracts/blob/63ab1f0ac06ce0793c0bbfbb8d09816bc211386d/src/v2/FinalityThresholds.sol#L21
);
} else {
cctpTokenMessenger.depositForBurn(partAmount, recipientCircleDomainId, to, address(usdcToken));
}
remainingAmount -= partAmount;
}
}
}
"
},
"contracts/external/interfaces/CCTPInterfaces.sol": {
"content": "/**
* Copyright (C) 2015, 2016, 2017 Dapphub
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* Imported as-is from commit 139d8d0ce3b5531d3c7ec284f89d946dfb720016 of:
* * https://github.com/walkerq/evm-cctp-contracts/blob/139d8d0ce3b5531d3c7ec284f89d946dfb720016/src/TokenMessenger.sol
* Changes applied post-import:
* * Removed a majority of code from this contract and converted the needed function signatures in this interface.
*/
interface ITokenMessenger {
/**
* @notice Deposits and burns tokens from sender to be minted on destination domain.
* Emits a `DepositForBurn` event.
* @dev reverts if:
* - given burnToken is not supported
* - given destinationDomain has no TokenMessenger registered
* - transferFrom() reverts. For example, if sender's burnToken balance or approved allowance
* to this contract is less than `amount`.
* - burn() reverts. For example, if `amount` is 0.
* - MessageTransmitter returns false or reverts.
* @param amount amount of tokens to burn
* @param destinationDomain destination domain
* @param mintRecipient address of mint recipient on destination domain
* @param burnToken address of contract to burn deposited tokens, on local domain
* @return _nonce unique nonce reserved by message
*/
function depositForBurn(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken
) external returns (uint64 _nonce);
/**
* @notice Minter responsible for minting and burning tokens on the local domain
* @dev A TokenMessenger stores a TokenMinter contract which extends the TokenController contract.
* https://github.com/circlefin/evm-cctp-contracts/blob/817397db0a12963accc08ff86065491577bbc0e5/src/TokenMessenger.sol#L110
* @return minter Token Minter contract.
*/
function localMinter() external view returns (ITokenMinter minter);
}
// Source: https://github.com/circlefin/evm-cctp-contracts/blob/63ab1f0ac06ce0793c0bbfbb8d09816bc211386d/src/v2/TokenMessengerV2.sol#L138C1-L166C15
interface ITokenMessengerV2 {
/**
* @notice Deposits and burns tokens from sender to be minted on destination domain.
* Emits a `DepositForBurn` event.
* @dev reverts if:
* - given burnToken is not supported
* - given destinationDomain has no TokenMessenger registered
* - transferFrom() reverts. For example, if sender's burnToken balance or approved allowance
* to this contract is less than `amount`.
* - burn() reverts. For example, if `amount` is 0.
* - maxFee is greater than or equal to `amount`.
* - MessageTransmitterV2#sendMessage reverts.
* @param amount amount of tokens to burn
* @param destinationDomain destination domain to receive message on
* @param mintRecipient address of mint recipient on destination domain
* @param burnToken token to burn `amount` of, on local domain
* @param destinationCaller authorized caller on the destination domain, as bytes32. If equal to bytes32(0),
* any address can broadcast the message.
* @param maxFee maximum fee to pay on the destination domain, specified in units of burnToken
* @param minFinalityThreshold the minimum finality at which a burn message will be attested to.
*/
function depositForBurn(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller,
uint256 maxFee,
uint32 minFinalityThreshold
) external;
}
/**
* A TokenMessenger stores a TokenMinter contract which extends the TokenController contract. The TokenController
* contract has a burnLimitsPerMessage public mapping which can be queried to find the per-message burn limit
* for a given token:
* https://github.com/circlefin/evm-cctp-contracts/blob/817397db0a12963accc08ff86065491577bbc0e5/src/TokenMinter.sol#L33
* https://github.com/circlefin/evm-cctp-contracts/blob/817397db0a12963accc08ff86065491577bbc0e5/src/roles/TokenController.sol#L69C40-L69C60
*
*/
interface ITokenMinter {
/**
* @notice Supported burnable tokens on the local domain
* local token (address) => maximum burn amounts per message
* @param token address of token contract
* @return burnLimit maximum burn amount per message for token
*/
function burnLimitsPerMessage(address token) external view returns (uint256);
}
/**
* IMessageTransmitter in CCTP inherits IRelayer and IReceiver, but here we only import sendMessage from IRelayer:
* https://github.com/circlefin/evm-cctp-contracts/blob/377c9bd813fb86a42d900ae4003599d82aef635a/src/interfaces/IMessageTransmitter.sol#L25
* https://github.com/circlefin/evm-cctp-contracts/blob/377c9bd813fb86a42d900ae4003599d82aef635a/src/interfaces/IRelayer.sol#L23-L35
*/
interface IMessageTransmitter {
/**
* @notice Sends an outgoing message from the source domain.
* @dev Increment nonce, format the message, and emit `MessageSent` event with message information.
* @param destinationDomain Domain of destination chain
* @param recipient Address of message recipient on destination domain as bytes32
* @param messageBody Raw bytes content of message
* @return nonce reserved by message
*/
function sendMessage(
uint32 destinationDomain,
bytes32 recipient,
bytes calldata messageBody
) external returns (uint64);
}
"
},
"contracts/interfaces/IOFT.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/**
* @notice This file contains minimal copies of relevant structs / interfaces for OFT bridging. Source code link:
* https://github.com/LayerZero-Labs/LayerZero-v2/blob/9a4049ae3a374e1c0ef01ac9fb53dd83f4257a68/packages/layerzero-v2/evm/oapp/contracts/oft/interfaces/IOFT.sol
* It's also published as a part of an npm package: @layerzerolabs/oft-evm. The published code is incompatible with
* our compiler version requirements, so we copy it here instead
*/
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/
struct SendParam {
uint32 dstEid; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT receipt information.
*/
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/
interface IOFT {
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/
function token() external view returns (address);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}
"
},
"contracts/libraries/OFTTransportAdapterWithStore.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import { OFTTransportAdapter } from "./OFTTransportAdapter.sol";
import { AdapterStore, MessengerTypes } from "../AdapterStore.sol";
/**
* @dev A wrapper of `OFTTransportAdapter` to be used by chain-specific adapters
* @custom:security-contact bugs@across.to
*/
contract OFTTransportAdapterWithStore is OFTTransportAdapter {
/** @notice Helper storage contract to keep track of token => IOFT relationships */
AdapterStore public immutable OFT_ADAPTER_STORE;
/**
* @notice Initializes the OFTTransportAdapterWithStore contract
* @param _oftDstEid The endpoint ID that OFT protocol will transfer funds to
* @param _feeCap Fee cap checked before sending messages to OFTMessenger
* @param _adapterStore Address of the AdapterStore contract
*/
constructor(uint32 _oftDstEid, uint256 _feeCap, address _adapterStore) OFTTransportAdapter(_oftDstEid, _feeCap) {
OFT_ADAPTER_STORE = AdapterStore(_adapterStore);
}
/**
* @notice Retrieves the OFT messenger address for a given token
* @param _token Token address to look up messenger for
* @return Address of the OFT messenger for the token
*/
function _getOftMessenger(address _token) internal view returns (address) {
return OFT_ADAPTER_STORE.crossChainMessengers(MessengerTypes.OFT_MESSENGER, OFT_DST_EID, _token);
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// 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);
}
"
},
"node_modules/@openzeppelin/contracts/utils/Address.sol": {
"content": "// 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);
}
}
}
"
},
"contracts/libraries/AddressConverters.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library Bytes32ToAddress {
/**************************************
* ERRORS *
**************************************/
error InvalidBytes32();
function toAddress(bytes32 _bytes32) internal pure returns (address) {
checkAddress(_bytes32);
return address(uint160(uint256(_bytes32)));
}
function toAddressUnchecked(bytes32 _bytes32) internal pure returns (address) {
return address(uint160(uint256(_bytes32)));
}
function checkAddress(bytes32 _bytes32) internal pure {
if (uint256(_bytes32) >> 160 != 0) {
revert InvalidBytes32();
}
}
}
library AddressToBytes32 {
function toBytes32(address _address) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_address)));
}
}
"
},
"contracts/libraries/OFTTransportAdapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IOFT, SendParam, MessagingFee, OFTReceipt } from "../interfaces/IOFT.sol";
import { AddressToBytes32 } from "../libraries/AddressConverters.sol";
/**
* @notice Facilitate bridging tokens via LayerZero's OFT.
* @dev This contract is intended to be inherited by other chain-specific adapters and spoke pools.
* @custom:security-contact bugs@across.to
*/
contract OFTTransportAdapter {
using SafeERC20 for IERC20;
using AddressToBytes32 for address;
/** @notice Empty bytes array used for OFT messaging parameters */
bytes public constant EMPTY_MSG_BYTES = new bytes(0);
/**
* @notice Fee cap checked before sending messages to OFTMessenger
* @dev Conservative (high) cap to not interfere with operations under normal conditions
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 public immutable OFT_FEE_CAP;
/**
* @notice The destination endpoint id in the OFT messaging protocol.
* @dev Source https://docs.layerzero.network/v2/developers/evm/technical-reference/deployed-contracts.
*/
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint32 public immutable OFT_DST_EID;
/** @notice Thrown when OFT fee exceeds the configured cap */
error OftFeeCapExceeded();
/** @notice Thrown when contract has insufficient balance to pay OFT fees */
error OftInsufficientBalanceForFee();
/** @notice Thrown when LayerZero token fee is not zero (only native fees supported) */
error OftLzFeeNotZero();
/** @notice Thrown when amount received differs from expected amount */
error OftIncorrectAmountReceivedLD();
/** @notice Thrown when amount sent differs from expected amount */
error OftIncorrectAmountSentLD();
/**
* @notice intiailizes the OFTTransportAdapter contract.
* @param _oftDstEid the endpoint ID that OFT protocol will transfer funds to.
* @param _feeCap a fee cap we check against before sending a message with value to OFTMessenger as fees.
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(uint32 _oftDstEid, uint256 _feeCap) {
OFT_DST_EID = _oftDstEid;
OFT_FEE_CAP = _feeCap;
}
/**
* @notice transfer token to the other dstEid (e.g. chain) via OFT messaging protocol
* @dev the caller has to provide both _token and _messenger. The caller is responsible for knowing the correct _messenger
* @param _token token we're sending on current chain.
* @param _messenger corresponding OFT messenger on current chain.
* @param _to address to receive a transfer on the destination chain.
* @param _amount amount to send.
*/
function _transferViaOFT(IERC20 _token, IOFT _messenger, address _to, uint256 _amount) internal {
(SendParam memory sendParam, MessagingFee memory fee) = _buildOftTransfer(_messenger, _to, _amount);
_sendOftTransfer(_token, _messenger, sendParam, fee);
}
/**
* @notice Build OFT send params and quote the native fee.
* @dev Sets `minAmountLD == amountLD` to disallow silent deductions (e.g. dust removal) by OFT.
* The fee is quoted for payment in native token.
* @param _messenger OFT messenger contract on the current chain for the token being sent.
* @param _to Destination address on the remote chain.
* @param _amount Amount of tokens to transfer.
* @return sendParam The encoded OFT send parameters.
* @return fee The quoted MessagingFee required for the transfer.
*/
function _buildOftTransfer(
IOFT _messenger,
address _to,
uint256 _amount
) internal view returns (SendParam memory, MessagingFee memory) {
bytes32 to = _to.toBytes32();
SendParam memory sendParam = SendParam(
OFT_DST_EID,
to,
/**
* _amount, _amount here specify `amountLD` and `minAmountLD`. Setting `minAmountLD` equal to `amountLD` protects us
* from any changes to the sent amount due to internal OFT contract logic, e.g. `_removeDust`. Meaning that if any
* dust is subtracted, the `.send()` should revert
*/
_amount,
_amount,
/**
* EMPTY_MSG_BYTES, EMPTY_MSG_BYTES, EMPTY_MSG_BYTES here specify `extraOptions`, `composeMsg` and `oftCmd`.
* These can be set to empty bytes arrays for the purposes of sending a simple cross-chain transfer.
*/
EMPTY_MSG_BYTES,
EMPTY_MSG_BYTES,
EMPTY_MSG_BYTES
);
// `false` in the 2nd param here refers to `bool _payInLzToken`. We will pay in native token, so set to `false`
MessagingFee memory fee = _messenger.quoteSend(sendParam, false);
return (sendParam, fee);
}
/**
* @notice Execute an OFT transfer using pre-built params and fee.
* @dev Verifies fee bounds and equality of sent/received amounts. Pays native fee from this contract.
* @param _token ERC-20 token to transfer.
* @param _messenger OFT messenger contract on the current chain for `_token`.
* @param sendParam Pre-built OFT send parameters.
* @param fee Quoted MessagingFee to pay for this transfer.
*/
function _sendOftTransfer(
IERC20 _token,
IOFT _messenger,
SendParam memory sendParam,
MessagingFee memory fee
) internal {
// Create a stack variable to optimize gas usage on subsequent reads
uint256 nativeFee = fee.nativeFee;
if (nativeFee > OFT_FEE_CAP) revert OftFeeCapExceeded();
if (nativeFee > address(this).balance) revert OftInsufficientBalanceForFee();
if (fee.lzTokenFee != 0) revert OftLzFeeNotZero();
// Approve the exact _amount for `_messenger` to spend. Fee will be paid in native token
uint256 _amount = sendParam.amountLD;
_token.forceApprove(address(_messenger), _amount);
(, OFTReceipt memory oftReceipt) = _messenger.send{ value: nativeFee }(sendParam, fee, address(this));
// The HubPool expects that the amount received by the SpokePool is exactly the sent amount
if (_amount != oftReceipt.amountReceivedLD) revert OftIncorrectAmountReceivedLD();
// Also check the amount sent on origin chain to harden security
if (_amount != oftReceipt.amountSentLD) revert OftIncorrectAmountSentLD();
}
}
"
},
"contracts/AdapterStore.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.18;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOFT } from "./interfaces/IOFT.sol";
/**
* @title MessengerTypes
* @notice Library containing messenger type constants
* @custom:security-contact bugs@across.to
*/
library MessengerTypes {
/** @notice Identifier for OFT (Omni-chain Fungible Token by LayerZero) messenger type */
bytes32 public constant OFT_MESSENGER = bytes32("OFT_MESSENGER");
}
/**
* @dev A helper contract for chain adapters on the hub chain that support OFT messaging. Handles
* @dev token => messenger mapping storage. Adapters can't store this themselves as they're called
* @dev via `delegateCall` and their storage is not part of available context.
* @custom:security-contact bugs@across.to
*/
contract AdapterStore is Ownable {
/** @notice Maps messenger type and destination domain to token-messenger pairs */
mapping(bytes32 messengerType => mapping(uint256 dstDomainId => mapping(address srcChainToken => address messengerAddress)))
public crossChainMessengers;
/**
* @notice Emitted when a messenger is set for a specific token and destination
* @param messengerType Type of messenger being set
* @param dstDomainId Destination domain ID
* @param srcChainToken Source chain token address
* @param srcChainMessenger Source chain messenger address
*/
event MessengerSet(
bytes32 indexed messengerType,
uint256 indexed dstDomainId,
address indexed srcChainToken,
address srcChainMessenger
);
/** @notice Thrown when array lengths don't match in batch operations */
error ArrayLengthMismatch();
/** @notice Thrown when IOFT messenger's token doesn't match expected token */
error IOFTTokenMismatch();
/** @notice Thrown when messenger type is not supported */
error NonExistentMessengerType();
/**
* @notice Sets a messenger for a specific token and destination domain
* @param messengerType Type of messenger to set
* @param dstDomainId Destination domain ID
* @param srcChainToken Source chain token address
* @param srcChainMessenger Source chain messenger address
*/
function setMessenger(
bytes32 messengerType,
uint256 dstDomainId,
address srcChainToken,
address srcChainMessenger
) external onlyOwner {
_setMessenger(messengerType, dstDomainId, srcChainToken, srcChainMessenger);
}
/**
* @notice Sets multiple messengers in a single transaction
* @param messengerTypes Array of messenger types
* @param dstDomainIds Array of destination domain IDs
* @param srcChainTokens Array of source chain token addresses
* @param srcChainMessengers Array of source chain messenger addresses
*/
function batchSetMessengers(
bytes32[] calldata messengerTypes,
uint256[] calldata dstDomainIds,
address[] calldata srcChainTokens,
address[] calldata srcChainMessengers
) external onlyOwner {
if (
messengerTypes.length != dstDomainIds.length ||
messengerTypes.length != srcChainTokens.length ||
messengerTypes.length != srcChainMessengers.length
) {
revert ArrayLengthMismatch();
}
for (uint256 i = 0; i < dstDomainIds.length; i++) {
_setMessenger(messengerTypes[i], dstDomainIds[i], srcChainTokens[i], srcChainMessengers[i]);
}
}
/**
* @notice Internal function to set a messenger with validation
* @param _messengerType Type of messenger to set
* @param _dstDomainId Destination domain ID
* @param _srcChainToken Source chain token address
* @param _srcChainMessenger Source chain messenger address
*/
function _setMessenger(
bytes32 _messengerType,
uint256 _dstDomai
Submitted on: 2025-10-03 19:09:12
Comments
Log in to comment.
No comments yet.