Verified contractExactUNLICENSED
PairPayment
Address0x95d756e79e1cb06a9f91877639bf39affc0c7e86
- Balance
0 ETH
- Transactions
6
- Compiler
solc 0.8.30
- Same code
5 more contracts
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,202,987
- Creation transaction
- 0x42f66d1d9f…d4928eee7a
11 files
- src/PairPayment.solmain15.49 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
src/PairPayment.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @dev The two collector entry points this contract uses. Both book the payment for `creditTo`
/// rather than for `msg.sender`, which is the whole reason they exist: see the note on payers
/// of record below.
interface IPairCollector {
/// @notice `pay`, with the fee booked as `creditTo`'s. Reverts `NothingToPay` on zero and
/// `AlreadySettled` once the launch has landed.
function payFor(bytes32 launchId, address creditTo) external payable;
/// @notice Pulls `amount` of `asset` from `msg.sender` by `transferFrom` and books what actually
/// arrived (its own balance difference) as `creditTo`'s dev buy, on a ledger per asset.
function payDevBuyToken(bytes32 launchId, address asset, uint256 amount, address creditTo) external;
}
/// @title PairPayment
/// @notice One wallet action for a creator whose launch pairs with an ERC-20 asset -- a tokenized
/// stock, say -- rather than the native coin: pay the launch fee in native, and pay the dev
/// buy in native too, swapped here into the asset and booked in the collector as the
/// creator's dev buy in that asset.
///
/// WHY A HELPER AT ALL. The collector's dev buy for an asset pair is held in the ASSET, because that
/// is what the launch's pool is quoted in and what the launch transaction spends. A creator holds
/// native. Asking them to swap first and then pay is two or three wallet actions (swap, approve,
/// pay) and a window in which the price moves between the quote and the payment. Here the swap is
/// made at payment time, in the payment's own transaction, through an aggregator route our web
/// server built off-chain, and the creator signs once.
///
/// THE CREATOR STAYS THE PAYER OF RECORD. The collector keeps every payment per payer, and only a
/// payer can reclaim their own money or be refunded it. If this contract paid with `pay`, the fee
/// would be on THIS contract's line -- mixed with every other creator's who came through here, and
/// reclaimable by nobody, since this contract has no way to reclaim. So the fee goes in through
/// `payFor(launchId, msg.sender)` and the asset through `payDevBuyToken(..., msg.sender)`: the
/// collector's books read exactly as if the creator had paid both themselves, and a refund or a
/// reclaim of either goes to the creator and never through here.
///
/// IT HOLDS NOTHING. Between calls this contract owns no native and no tokens, and has approved
/// nobody. Within a call: the native for the swap goes to the target, the asset comes back and is
/// handed to the collector at once, the one approval it gives (to the collector, for exactly what
/// was received) is used up by the collector's pull and checked to be zero, and every wei of native
/// still here at the end -- whatever the swap did not use -- goes back to the caller. So there is
/// nothing for a swap target to steal: it is never approved for anything, and the helper has
/// nothing to approve it for. (Anything sent here by mistake is not anyone's; `rescue` lets the
/// admin return it.)
///
/// THE SWAP TARGET IS TRUSTED ONLY TO SWAP, AND NOT EVEN FOR THE AMOUNT. Targets are on an admin
/// allowlist -- the aggregators' routers, and nothing else -- because the call to one carries
/// arbitrary calldata from the web. What the swap produced is measured by this contract's own
/// balance of the asset before and after, never read from the target's return data, and must be at
/// least the caller's `minAssetOut`. A target that tries to re-enter is refused by the guard; one
/// that tries `transferFrom` on a token does so as itself, not as this contract.
///
/// FEE-ON-TRANSFER ASSETS ARE REFUSED. The collector books what actually ARRIVES, so a token that
/// skims on transfer would book the creator less than the swap bought -- silently. Here both ends
/// of the hand-over are measured: this contract's balance must fall by exactly `received` and the
/// collector's must rise by exactly `received`, or the whole payment reverts `NotExactTransfer`.
/// (Nothing on chain can tell such a token from a plain one before it moves: the registry cannot
/// detect it, and the admin is trusted not to list one. This check is what catches it, including a
/// token that starts charging after it was listed.)
///
/// ONLY A LISTED ASSET. The asset must be one the chain's pair registry lists -- the registry the
/// attestor reads, fixed here at construction -- so a payment cannot buy something no launch on
/// this chain can pair against. Which listed asset THIS launch's pool will pair against is not
/// known until it launches; a dev buy in a listed asset the pool does not use is reported by the
/// collector at the launch (`DevBuySkipped`, `DevBuyAssetNotThePoolsQuote`) and is the
/// creator's to reclaim at once.
///
/// ONLY FOR A DEV BUY. A launch with a fee and no dev buy pays `collector.pay` directly, where the
/// creator is `msg.sender` and no helper is needed; this refuses a payment with nothing to swap.
/// @dev What PairPayment asks the pair registry.
interface IPairListing {
function isListed(address asset) external view returns (bool);
}
contract PairPayment is ReentrancyGuardTransient {
using SafeERC20 for IERC20;
/// @notice The launch fee collector on this chain. Fixed: a helper that could be repointed
/// could be repointed at a contract that keeps what it is paid.
IPairCollector public immutable collector;
/// @notice The chain's pair registry: the assets a launch may pair against. Fixed, like the
/// collector, and the same one the attestor reads.
IPairListing public immutable registry;
address public admin;
address public pendingAdmin;
/// @notice Aggregator routers this contract may send a swap to.
mapping(address => bool) public isSwapTarget;
/// @param payer the creator: who sent the money, and whose fee and dev buy it was booked as.
/// @param swapped the native sent to `swapTarget`; `received` the asset it produced, all of
/// which was booked; `refunded` the native returned to `payer` at the end.
event PaidWithAssetDevBuy(
bytes32 indexed launchId,
address indexed payer,
address indexed asset,
uint256 fee,
address swapTarget,
uint256 swapped,
uint256 received,
uint256 refunded
);
event SwapTargetSet(address indexed target, bool allowed);
event Rescued(address indexed token, address indexed to, uint256 amount);
event AdminProposed(address indexed from, address indexed to);
event AdminChanged(address indexed from, address indexed to);
error NotAdmin();
error NotPending();
error ZeroAddress();
/// @notice A payment with no fee in it. There are no free launches.
error FeeRequired();
/// @notice `msg.value` does not cover the fee.
error FeeExceedsPayment(uint256 fee, uint256 sent);
/// @notice Nothing left over the fee to swap. A fee-only payment goes to `collector.pay`.
error NothingToSwap();
/// @notice A zero `minAssetOut` would accept any price at all, so it is never meant.
error ZeroMinimum();
error SwapTargetNotAllowed(address target);
/// @notice The target cannot be the asset itself (the call would run as this contract on the
/// asset), the collector, or this contract.
error BadSwapTarget(address target);
/// @notice The swap call reverted; `reason` is its revert data.
error SwapFailed(bytes reason);
error InsufficientOutput(uint256 received, uint256 minimum);
/// @notice The asset did not move exactly `received` from here to the collector: a token that
/// charges on transfer, or a collector that did not pull what it was approved for.
error NotExactTransfer(uint256 received, uint256 leftHere, uint256 reachedCollector);
error RefundFailed();
/// @notice Native sent here outside a payment, which would otherwise sit unowned.
error UnexpectedNative();
/// @notice The asset is not one the pair registry lists: no launch here can pair against it.
error AssetNotListed(address asset);
constructor(IPairCollector collector_, IPairListing registry_, address admin_) {
if (address(collector_) == address(0) || address(registry_) == address(0) || admin_ == address(0)) {
revert ZeroAddress();
}
collector = collector_;
registry = registry_;
admin = admin_;
}
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdmin();
_;
}
/// @notice Pay `launchId`'s fee and a dev buy in `asset`, both in native, in one call.
///
/// @dev `msg.value` is `fee` plus the native to swap. In order:
/// 1. `fee` to `collector.payFor`, booked as the caller's. Never zero: there are no free
/// launches, and the collector books an asset dev buy only for a payer whose fee it holds.
/// 2. `msg.value - fee` to `swapTarget` with `swapData`. The route must deliver the asset
/// HERE: this contract is the swap's recipient, and its balance is what is measured.
/// 3. `received` = this contract's asset balance after minus before; at least `minAssetOut`.
/// 4. The collector approved for exactly `received`, `payDevBuyToken(..., msg.sender)`,
/// the approval checked back to zero (reset if a token left any), and the asset checked
/// to have left here and reached the collector to the unit.
/// 5. All native still here -- what the route did not spend -- returned to the caller.
/// Any failure reverts the lot: there is no state in which the fee is paid and the dev buy
/// is not, or the swap happened and the asset is here.
/// @param fee The part of `msg.value` that is the launch fee, in native. Not zero (`FeeRequired`).
/// @param asset The pair's asset: what the swap buys and the dev buy is booked in.
/// @param swapTarget An allowlisted aggregator router.
/// @param swapData The route, built off-chain with this contract as taker and recipient.
/// @param minAssetOut The least of `asset` the creator accepts for the native swapped.
/// @return received The asset booked as the creator's dev buy.
function payWithAssetDevBuy(
bytes32 launchId,
uint256 fee,
address asset,
address swapTarget,
bytes calldata swapData,
uint256 minAssetOut
) external payable nonReentrant returns (uint256 received) {
if (fee == 0) revert FeeRequired();
if (fee > msg.value) revert FeeExceedsPayment(fee, msg.value);
uint256 swapValue = msg.value - fee;
if (swapValue == 0) revert NothingToSwap();
if (minAssetOut == 0) revert ZeroMinimum();
if (asset == address(0)) revert ZeroAddress();
if (!registry.isListed(asset)) revert AssetNotListed(asset);
if (!isSwapTarget[swapTarget]) revert SwapTargetNotAllowed(swapTarget);
if (swapTarget == asset) revert BadSwapTarget(swapTarget);
collector.payFor{value: fee}(launchId, msg.sender);
IERC20 token = IERC20(asset);
uint256 before = token.balanceOf(address(this));
(bool ok, bytes memory reason) = swapTarget.call{value: swapValue}(swapData);
if (!ok) revert SwapFailed(reason);
received = token.balanceOf(address(this)) - before;
if (received < minAssetOut) revert InsufficientOutput(received, minAssetOut);
_handOver(token, launchId, before, received);
// Everything native here now is the caller's: the fee and the swap have taken theirs, and
// the contract held none before (anything forced in since goes to the caller too, rather
// than staying here).
uint256 refund = address(this).balance;
emit PaidWithAssetDevBuy(launchId, msg.sender, asset, fee, swapTarget, swapValue, received, refund);
if (refund != 0) {
(bool sent,) = payable(msg.sender).call{value: refund}("");
if (!sent) revert RefundFailed();
}
}
/// @dev Give the collector exactly `received` of `token` as the caller's dev buy, and prove it
/// arrived whole: this contract's balance back to `before`, the collector's up by
/// `received`, and no allowance left behind.
function _handOver(IERC20 token, bytes32 launchId, uint256 before, uint256 received) private {
address c = address(collector);
uint256 collectorBefore = token.balanceOf(c);
// forceApprove: a USDT-style token refuses a non-zero approval over a non-zero one and
// returns nothing; this handles both.
token.forceApprove(c, received);
collector.payDevBuyToken(launchId, address(token), received, msg.sender);
if (token.allowance(address(this), c) != 0) token.forceApprove(c, 0);
uint256 after_ = token.balanceOf(address(this));
uint256 reached = token.balanceOf(c) - collectorBefore;
if (after_ != before || reached != received) {
revert NotExactTransfer(received, after_ > before ? after_ - before : 0, reached);
}
}
// ------------------------------------------------------------ admin
/// @notice Allow or disallow an aggregator router as a swap target.
/// @dev Refuses an address with no code (a typo'd or not-yet-deployed router would take the
/// native and swap nothing -- caught by `minAssetOut`, but not worth allowing), the
/// collector, and this contract. Disallowing is always possible.
function setSwapTarget(address target, bool allowed) external onlyAdmin {
if (allowed) {
if (target == address(collector) || target == address(this) || target.code.length == 0) {
revert BadSwapTarget(target);
}
}
isSwapTarget[target] = allowed;
emit SwapTargetSet(target, allowed);
}
/// @notice Return an ERC-20 sent here by mistake. Never anybody's payment: a payment leaves
/// nothing here, so whatever this finds is a stray transfer.
function rescue(address token, address to, uint256 amount) external onlyAdmin nonReentrant {
if (to == address(0)) revert ZeroAddress();
emit Rescued(token, to, amount);
IERC20(token).safeTransfer(to, amount);
}
function proposeAdmin(address to) external onlyAdmin {
if (to == address(0)) revert ZeroAddress();
pendingAdmin = to;
emit AdminProposed(admin, to);
}
function acceptAdmin() external {
if (msg.sender != pendingAdmin) revert NotPending();
emit AdminChanged(admin, msg.sender);
admin = msg.sender;
pendingAdmin = address(0);
}
/// @dev Native comes here only from a swap target returning what its route did not spend, in
/// the middle of a payment, and goes back to the payer before that payment ends. At any
/// other time it would have no owner, so it is refused.
receive() external payable {
if (!_reentrancyGuardEntered()) revert UnexpectedNative();
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
"@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
"@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@uniswap/v4-core/=lib/uniswap-v4-core/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"layerzero/=lib/layerzero/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solmate/=lib/solmate/",
"uniswap-v4-core/=lib/uniswap-v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.