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/Arbitrum_Adapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./interfaces/AdapterInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IOFT } from "../interfaces/IOFT.sol";
import "../external/interfaces/CCTPInterfaces.sol";
import "../libraries/CircleCCTPAdapter.sol";
import { OFTTransportAdapterWithStore } from "../libraries/OFTTransportAdapterWithStore.sol";
import { ArbitrumInboxLike as ArbitrumL1InboxLike, ArbitrumL1ERC20GatewayLike } from "../interfaces/ArbitrumBridge.sol";
/**
* @notice Contract containing logic to send messages from L1 to Arbitrum.
* @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.
*/
// solhint-disable-next-line contract-name-camelcase
contract Arbitrum_Adapter is AdapterInterface, CircleCCTPAdapter, OFTTransportAdapterWithStore {
using SafeERC20 for IERC20;
// Amount of ETH allocated to pay for the base submission fee. The base submission fee is a parameter unique to
// retryable transactions; the user is charged the base submission fee to cover the storage costs of keeping their
// ticket’s calldata in the retry buffer. (current base submission fee is queryable via
// ArbRetryableTx.getSubmissionPrice). ArbRetryableTicket precompile interface exists at L2 address
// 0x000000000000000000000000000000000000006E.
uint256 public constant L2_MAX_SUBMISSION_COST = 0.01e18;
// L2 Gas price bid for immediate L2 execution attempt (queryable via standard eth*gasPrice RPC)
uint256 public constant L2_GAS_PRICE = 5e9; // 5 gWei
// Native token expected to be sent in L2 message. Should be 0 for only use case of this constant, which
// includes is sending messages from L1 to L2.
uint256 public constant L2_CALL_VALUE = 0;
// Gas limit for L2 execution of a cross chain token transfer sent via the inbox.
uint32 public constant RELAY_TOKENS_L2_GAS_LIMIT = 300_000;
// Gas limit for L2 execution of a message sent via the inbox.
uint32 public constant RELAY_MESSAGE_L2_GAS_LIMIT = 2_000_000;
address public constant L1_DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// This address on L2 receives extra ETH that is left over after relaying a message via the inbox.
address public immutable L2_REFUND_L2_ADDRESS;
// Inbox system contract to send messages to Arbitrum. Token bridges use this to send tokens to L2.
// https://github.com/OffchainLabs/nitro-contracts/blob/f7894d3a6d4035ba60f51a7f1334f0f2d4f02dce/src/bridge/Inbox.sol
ArbitrumL1InboxLike public immutable L1_INBOX;
// Router contract to send tokens to Arbitrum. Routes to correct gateway to bridge tokens. Internally this
// contract calls the Inbox.
// Generic gateway: https://github.com/OffchainLabs/token-bridge-contracts/blob/main/contracts/tokenbridge/ethereum/gateway/L1ArbitrumGateway.sol
ArbitrumL1ERC20GatewayLike public immutable L1_ERC20_GATEWAY_ROUTER;
/**
* @notice Constructs new Adapter.
* @param _l1ArbitrumInbox Inbox helper contract to send messages to Arbitrum.
* @param _l1ERC20GatewayRouter ERC20 gateway router contract to send tokens to Arbitrum.
* @param _l2RefundL2Address L2 address to receive gas refunds on after a message is relayed.
* @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(
ArbitrumL1InboxLike _l1ArbitrumInbox,
ArbitrumL1ERC20GatewayLike _l1ERC20GatewayRouter,
address _l2RefundL2Address,
IERC20 _l1Usdc,
ITokenMessenger _cctpTokenMessenger,
address _adapterStore,
uint32 _oftDstEid,
uint256 _oftFeeCap
)
CircleCCTPAdapter(_l1Usdc, _cctpTokenMessenger, CircleDomainIds.Arbitrum)
OFTTransportAdapterWithStore(_oftDstEid, _oftFeeCap, _adapterStore)
{
L1_INBOX = _l1ArbitrumInbox;
L1_ERC20_GATEWAY_ROUTER = _l1ERC20GatewayRouter;
L2_REFUND_L2_ADDRESS = _l2RefundL2Address;
}
/**
* @notice Send cross-chain message to target on Arbitrum.
* @notice This contract must hold at least getL1CallValue() amount of ETH to send a message via the Inbox
* successfully, or the message will get stuck.
* @param target Contract on Arbitrum that will receive message.
* @param message Data to send to target.
*/
function relayMessage(address target, bytes memory message) external payable override {
uint256 requiredL1CallValue = _contractHasSufficientEthBalance(RELAY_MESSAGE_L2_GAS_LIMIT);
L1_INBOX.createRetryableTicket{ value: requiredL1CallValue }(
target, // destAddr destination L2 contract address
L2_CALL_VALUE, // l2CallValue call value for retryable L2 message
L2_MAX_SUBMISSION_COST, // maxSubmissionCost Max gas deducted from user's L2 balance to cover base fee
L2_REFUND_L2_ADDRESS, // excessFeeRefundAddress maxgas * gasprice - execution cost gets credited here on L2
L2_REFUND_L2_ADDRESS, // callValueRefundAddress l2Callvalue gets credited here on L2 if retryable txn times out or gets cancelled
RELAY_MESSAGE_L2_GAS_LIMIT, // maxGas Max gas deducted from user's L2 balance to cover L2 execution
L2_GAS_PRICE, // gasPriceBid price bid for L2 execution
message // data ABI encoded data of L2 message
);
emit MessageRelayed(target, message);
}
/**
* @notice Bridge tokens to Arbitrum.
* @notice This contract must hold at least getL1CallValue() amount of ETH to send a message via the Inbox
* successfully, or the message will get stuck.
* @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, // l2Token is unused for Arbitrum.
uint256 amount,
address to
) external payable override {
address oftMessenger = _getOftMessenger(l1Token);
// Check if the token needs to use any of the custom bridge solutions first
if (_isCCTPEnabled() && l1Token == address(usdcToken)) {
_transferUsdc(to, amount);
} else if (oftMessenger != address(0)) {
_transferViaOFT(IERC20(l1Token), IOFT(oftMessenger), to, amount);
}
// If not, we can use the Arbitrum gateway
else {
uint256 requiredL1CallValue = _contractHasSufficientEthBalance(RELAY_TOKENS_L2_GAS_LIMIT);
// Approve the gateway, not the router, to spend the hub pool's balance. The gateway, which is different
// per L1 token, will temporarily escrow the tokens to be bridged and pull them from this contract.
address erc20Gateway = L1_ERC20_GATEWAY_ROUTER.getGateway(l1Token);
IERC20(l1Token).safeIncreaseAllowance(erc20Gateway, amount);
// `outboundTransfer` expects that the caller includes a bytes message as the last param that includes the
// maxSubmissionCost to use when creating an L2 retryable ticket: https://github.com/OffchainLabs/arbitrum/blob/e98d14873dd77513b569771f47b5e05b72402c5e/packages/arb-bridge-peripherals/contracts/tokenbridge/ethereum/gateway/L1GatewayRouter.sol#L232
bytes memory data = abi.encode(L2_MAX_SUBMISSION_COST, "");
// Note: Legacy routers don't have the outboundTransferCustomRefund method, so default to using
// outboundTransfer(). Legacy routers are used for the following tokens that are currently enabled:
// - DAI: the implementation of `outboundTransfer` at the current DAI custom gateway
// (https://etherscan.io/address/0xD3B5b60020504bc3489D6949d545893982BA3011#writeContract) sets the
// sender as the refund address so the aliased HubPool should receive excess funds. Implementation here:
// https://github.com/makerdao/arbitrum-dai-bridge/blob/11a80385e2622968069c34d401b3d54a59060e87/contracts/l1/L1DaiGateway.sol#L109
if (l1Token == L1_DAI) {
// This means that the excess ETH to pay for the L2 transaction will be sent to the aliased
// contract address on L2, which we'd have to retrieve via a custom adapter, the Arbitrum_RescueAdapter.
// To do so, in a single transaction: 1) setCrossChainContracts to Arbitrum_RescueAdapter, 2) relayMessage
// with function data = abi.encode(amountToRescue), 3) setCrossChainContracts back to this adapter.
L1_ERC20_GATEWAY_ROUTER.outboundTransfer{ value: requiredL1CallValue }(
l1Token,
to,
amount,
RELAY_TOKENS_L2_GAS_LIMIT,
L2_GAS_PRICE,
data
);
} else {
L1_ERC20_GATEWAY_ROUTER.outboundTransferCustomRefund{ value: requiredL1CallValue }(
l1Token,
L2_REFUND_L2_ADDRESS,
to,
amount,
RELAY_TOKENS_L2_GAS_LIMIT,
L2_GAS_PRICE,
data
);
}
}
emit TokensRelayed(l1Token, l2Token, amount, to);
}
/**
* @notice Returns required amount of ETH to send a message via the Inbox.
* @param l2GasLimit L2 gas limit for the message.
* @return amount of ETH that this contract needs to hold in order for relayMessage to succeed.
*/
function getL1CallValue(uint32 l2GasLimit) public pure returns (uint256) {
return L2_MAX_SUBMISSION_COST + L2_GAS_PRICE * l2GasLimit;
}
function _contractHasSufficientEthBalance(uint32 l2GasLimit) internal view returns (uint256) {
uint256 requiredL1CallValue = getL1CallValue(l2GasLimit);
require(address(this).balance >= requiredL1CallValue, "Insufficient ETH balance");
return requiredL1CallValue;
}
}
"
},
"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;
}
"
},
"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/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/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/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/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);
}
}
"
},
"contracts/interfaces/ArbitrumBridge.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/**
* @title Staging ground for incoming and outgoing messages
* @notice Unlike the standard Eth bridge, native token bridge escrows the custom ERC20 token which is
* used as native currency on upper layer.
* @dev Fees are paid in this token. There are certain restrictions on the native token:
* - The token can't be rebasing or have a transfer fee
* - The token must only be transferrable via a call to the token address itself
* - The token must only be able to set allowance via a call to the token address itself
* - The token must not have a callback on transfer, and more generally a user must not be able to make a transfer to themselves revert
* - The token must have a max of 2^256 - 1 wei total supply unscaled
* - The token must have a max of 2^256 - 1 wei total supply when scaled to 18 decimals
*/
interface ArbitrumERC20Bridge {
/**
* @notice Returns token that is escrowed in bridge on the lower layer and minted on the upper layer as native currency.
* @dev This function doesn't exist on the generic Bridge interface.
* @return address of the native token.
*/
function nativeToken() external view returns (address);
/**
* @dev number of decimals used by the native token
* This is set on bridge initialization using nativeToken.decimals()
* If the token does not have decimals() method, we assume it have 0 decimals
*/
function nativeTokenDecimals() external view returns (uint8);
}
/**
* @title Inbox for user and contract originated messages
* @notice Messages created via this inbox are enqueued in the delayed accumulator
* to await inclusion in the SequencerInbox
*/
interface ArbitrumInboxLike {
/**
* @dev we only use this function to check the native token used by the bridge, so we hardcode the interface
* to return an ArbitrumERC20Bridge instead of a more generic Bridge interface.
* @return address of the bridge.
*/
function bridge() external view returns (ArbitrumERC20Bridge);
/**
* @notice Put a message in the inbox that can be reexecuted for some fixed amount of time if it reverts
* @dev Gas limit and maxFeePerGas should not be set to 1 as that is used to trigger the RetryableData error
* @dev Caller must set msg.value equal to at least `maxSubmissionCost + maxGas * gasPriceBid`.
* all msg.value will deposited to callValueRefundAddress on the upper layer
* @dev More details can be found here: https://developer.arbitrum.io/arbos/l1-to-l2-messaging
* @param to destination contract address
* @param callValue call value for retryable message
* @param maxSubmissionCost Max gas deducted from user's (upper layer) balance to cover base submission fee
* @param excessFeeRefundAddress gasLimit x maxFeePerGas - execution cost gets credited here on (upper layer) balance
* @param callValueRefundAddress callvalue gets credited here on upper layer if retryable txn times out or gets cancelled
* @param gasLimit Max gas deducted from user's upper layer balance to cover upper layer execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param maxFeePerGas price bid for upper layer execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param data ABI encoded data of message
* @return unique message number of the retryable transaction
*/
function createRetryableTicket(
address to,
uint256 callValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
bytes calldata data
) external payable returns (uint256);
/**
* @notice Put a message in the source chain inbox that can be reexecuted for some fixed amount of time if it reverts
* @dev Same as createRetryableTicket, but does not guarantee that submission will succeed by requiring the needed
* funds come from the deposit alone, rather than falling back on the user's balance
* @dev Advanced usage only (does not rewrite aliases for excessFeeRefundAddress and callValueRefundAddress).
* createRetryableTicket method is the recommended standard.
* @dev Gas limit and maxFeePerGas should not be set to 1 as that is used to trigger the RetryableData error
* @param to destination contract address
* @param callValue call value for retryable message
* @param maxSubmissionCost Max gas deducted from user's source chain balance to cover base submission fee
* @param excessFeeRefundAddress gasLimit x maxFeePerGas - execution cost gets credited here on source chain balance
* @param callValueRefundAddress callvalue gets credited here on source chain if retryable txn times out or gets cancelled
* @param gasLimit Max gas deducted from user's balance to cover execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param maxFeePerGas price bid for execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param data ABI encoded data of the message
* @return unique message number of the retryable transaction
*/
function unsafeCreateRetryableTicket(
address to,
uint256 callValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
bytes calldata data
) external payable returns (uint256);
}
/**
* @notice Interface which extends ArbitrumInboxLike with functions used to interact with bridges that use a custom gas token.
*/
interface ArbitrumCustomGasTokenInbox is ArbitrumInboxLike {
/**
* @notice Put a message in the inbox that can be reexecuted for some fixed amount of time if it reverts
* @notice Overloads the `createRetryableTicket` function but is not payable, and should only be called when paying
* for message using a custom gas token.
* @dev all tokenTotalFeeAmount will be deposited to callValueRefundAddress on upper layer
* @dev Gas limit and maxFeePerGas should not be set to 1 as that is used to trigger the RetryableData error
* @dev In case of native token having non-18 decimals: tokenTotalFeeAmount is denominated in native token's decimals. All other value params - callValue, maxSubmissionCost and maxFeePerGas are denominated in child chain's native 18 decimals.
* @param to destination contract address
* @param callValue call value for retryable message
* @param maxSubmissionCost Max gas deducted from user's upper layer balance to cover base submission fee
* @param excessFeeRefundAddress the address which receives the difference between execution fee paid and the actual execution cost. In case this address is a contract, funds will be received in its alias on upper layer.
* @param callValueRefundAddress callvalue gets credited here on upper layer if retryable txn times out or gets cancelled. In case this address is a contract, funds will be received in its alias on upper layer.
* @param gasLimit Max gas deducted from user's balance to cover execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param maxFeePerGas price bid for execution. Should not be set to 1 (magic value used to trigger the RetryableData error)
* @param tokenTotalFeeAmount amount of fees to be deposited in native token to cover for retryable ticket cost
* @param data ABI encoded data of message
* @return unique message number of the retryable transaction
*/
function createRetryableTicket(
address to,
uint256 callValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
uint256 tokenTotalFeeAmount,
bytes calldata data
) external returns (uint256);
}
/**
* @notice Generic gateway contract for bridging standard ERC20s to/from Arbitrum-like networks.
* @notice These function signatures are shared between the L1 and L2 gateway router contracts.
*/
interface ArbitrumL1ERC20GatewayLike {
/**
* @notice Deprecated in favor of outboundTransferCustomRefund but still used in custom bridges
* like the DAI bridge.
* @dev Refunded to aliased address of sender if sender has code on source chain, otherwise to to sender's EOA on destination chain.
* @param _sourceToken address of ERC20
* @param _to Account to be credited with the tokens at the destination (can be the user's account or a contract),
* not subject to aliasing. This account, or its alias if it has code in the source chain, will also be able to
* cancel the retryable ticket and receive callvalue refund
* @param _amount Token Amount
* @param _maxGas Max gas deducted from user's balance to cover execution
* @param _gasPriceBid Gas price for execution
* @param _data encoded data from router and user
* @return res abi encoded inbox sequence number
*/
function outboundTransfer(
address _sourceToken,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
) external payable returns (bytes memory);
/**
* @notice get ERC20 gateway for token.
* @param _token ERC20 address.
* @return address of ERC20 gateway.
*/
function getGateway(address _token) external view returns (address);
/**
* @notice Deposit ERC20 token from Ethereum into Arbitrum-like networks.
* @dev Upper layer address alias will not be applied to the following types of addresses on lower layer:
* - 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
* @param _sourceToken address of ERC20 on source chain.
* @param _refundTo Account, or its alias if it has code on the source chain, to be credited with excess gas refund at destination
* @param _to Account to be credited with the tokens in the L3 (can be the user's L3 account or a contract),
* not subject to aliasing. This account, or its alias if it has code on the source chain, will also be able to
* cancel the retryable ticket and receive callvalue refund
* @param _amount Token Amount
* @param _maxGas Max gas deducted from user's balance to cover execution
* @param _gasPriceBid Gas price for execution
* @param _data encoded data from router and user
* @return res abi encoded inbox sequence number
*/
function outboundTransferCustomRefund(
address _sourceToken,
address _refundTo,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
) external payable returns (bytes memory);
}
interface ArbitrumL2ERC20GatewayLike {
/**
* @notice Fetches the l2 token address from the gateway router for the input l1 token address
* @param _l1Erc20 address of the l1 token.
*/
function calculateL2TokenAddress(address _l1Erc20) external view returns (address);
/**
* @notice Withdraws a specified amount of an l2 token to an l1 token.
* @param _l1Token address of the token to withdraw on L1.
* @param _to address on L1 which will receive the tokens upon withdrawal.
* @param _amount amount of the token to withdraw.
* @param _data encoded data to send to the gateway router.
*/
function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
bytes calldata _data
) external payable returns (bytes memory);
}
"
},
"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-func
Submitted on: 2025-10-03 19:28:54
Comments
Log in to comment.
No comments yet.