MorphoLiquidationGateway

Description:

ERC20 token contract with Factory capabilities. Standard implementation for fungible tokens on Ethereum.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/interfaces/IERC1363.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/interfaces/IERC165.sol": {
      "content": "// 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";
"
    },
    "@openzeppelin/contracts/interfaces/IERC20.sol": {
      "content": "// 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";
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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);
    }
}
"
    },
    "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        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();
    }
}
"
    },
    "@openzeppelin/contracts/utils/TransientSlot.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}
"
    },
    "contracts/interfaces/IGatewayHelper.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface IGatewayHelper {
    /**
        @notice Build the transaction data for the liquidator
        @param token The token being paid
        @param amount The amount paid by the payer
        @param externalCall The external call data the payer passed to the `MorphoLiquidationGateway`
        @return liquidator The address of the liquidator
        @return txCallData The transaction data for the liquidator
     */
    function buildTxCalldata(
        address token,
        uint256 amount,
        bytes calldata externalCall
    ) external view returns (address liquidator, bytes memory txCallData);
}
"
    },
    "contracts/interfaces/ILiquidationGateway.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface ILiquidationGateway {
    /**
        @notice Returns details of the current payment execution.
        @dev Values are stored in transient storage and are only valid 
             within the scope of the current transaction.
        @return payer Address of the payer
        @return paymentToken Address of the token used for payment
        @return paymentAmount Amount being paid
    */
    function paymentDetails()
        external
        view
        returns (address payer, address paymentToken, uint256 paymentAmount);
}
"
    },
    "contracts/interfaces/IOptimexProtocol.sol": {
      "content": "// SPDX-License-Identifier: None
pragma solidity ^0.8.20;

import "./IProtocol.sol";

interface IOptimexProtocol is IProtocol {
    /**
        @notice Checks whether the specified `account` has been granted the given `role`.
        @param role The role to check, represented as a `bytes32` value.
        @param account The address of the account to check.
        @return `true` if the `account` has been granted the `role`, otherwise `false`.
    */
    function hasRole(
        bytes32 role,
        address account
    ) external view returns (bool);
}
"
    },
    "contracts/interfaces/IProtocol.sol": {
      "content": "// SPDX-License-Identifier: None
pragma solidity ^0.8.20;

interface IProtocol {
    /**
        @notice Returns the address of the current owner.
        @return The address of the contract owner.
    */
    function owner() external view returns (address);

    /**
        @notice Returns the current address of the Protocol Fee Receiver.
        @return The protocol fee receiver's address.
    */
    function pFeeAddr() external view returns (address);
}
"
    },
    "contracts/libraries/ErrorLib.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

/// @title ErrorLib
/// @notice Provides common error messages for the Optimex protocol
/// @dev Designed as a library to be used by other Optimex contracts
library ErrorLib {
    error AccessDenied(bytes32 positionId);
    error AuthorizerMismatch();
    error DeadlineExpired();
    error InvalidAmount();
    error InvalidAPM();
    error InvalidAuthorizerSig();
    error InvalidOwnerSig();
    error InvalidPositionId(bytes32 positionId);
    error InvalidPubkey();
    error InvalidValidator(address validator);
    error MarketMismatch(bytes32 expected, bytes32 actual);
    error RecipientNotPermitted(address recipient);
    error StateAlreadySet();
    error TokenMismatch(address expected, address actual);
    error Unauthorized(address sender);
    error ZeroAddress();
    error ZeroAmount();
    error InvalidBorrowShares();
    error IncompleteConsumption();
    error InvalidThreshold();
    error InvalidLIF();
    error Liquidatable();
    error NotPreLiquidatable();
    error PreLiqDisabled(bytes32 marketId);
    error NoHelper();
}
"
    },
    "contracts/libraries/TokenUtils.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title TokenUtils
/// @notice Provides utility functions for token operations
/// @dev Designed as a library to be used by other Optimex contracts
library TokenUtils {
    using SafeERC20 for IERC20;

    /**
        @notice Approves the spender to spend a specific amount of tokens
        @dev Use SafeERC20 to deal with legacy ERC20 tokens
        @param token The address of the token
        @param spender The address of the spender
        @param amount The amount of tokens to approve
    */
    function approval(IERC20 token, address spender, uint256 amount) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);

        if (oldAllowance > amount) {
            token.safeDecreaseAllowance(spender, oldAllowance - amount);
        } else if (oldAllowance < amount) {
            token.safeIncreaseAllowance(spender, amount - oldAllowance);
        }
    }
}
"
    },
    "contracts/libraries/UtilLib.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

/// @title UtilLib
/// @notice Utility library for the Optimex Protocol
/// @dev Implements the same low-level revert pattern as Morpho's Bundler3 contract to bubble up error messages:
/// - https://github.com/morpho-org/bundler3/blob/e6fdcbcd2a59fe5fe9cbd9e0cf7d45f5d2aa3f49/src/libraries/UtilsLib.sol#L8
library UtilLib {
    /// @dev Bubbles up the revert reason / custom error encoded in `returnData`.
    /// @dev Assumes `returnData` is the return data of any kind of failing CALL to a contract.
    function lowLevelRevert(bytes memory returnData) internal pure {
        assembly ("memory-safe") {
            revert(add(32, returnData), mload(returnData))
        }
    }
}
"
    },
    "contracts/MorphoLiquidationGateway.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";

import "./interfaces/IOptimexProtocol.sol";
import "./interfaces/IGatewayHelper.sol";
import "./interfaces/ILiquidationGateway.sol";
import "./protocol/OptimexAdminGuard.sol";
import "./protocol/OptimexDomain.sol";
import "./libraries/TokenUtils.sol";
import "./libraries/ErrorLib.sol";
import "./libraries/UtilLib.sol";

/// @title MorphoLiquidationGateway
/// @notice A gateway contract that routing liquidation payments inside the Optimex Protocol:
///   - Validates and redirects payments to authorized liquidator contracts
///   - Acts as a single entry point for all liquidation operations
contract MorphoLiquidationGateway is
    OptimexAdminGuard,
    OptimexDomain,
    ReentrancyGuardTransient,
    ILiquidationGateway
{
    using SafeERC20 for IERC20;
    using TokenUtils for IERC20;

    /**
        @notice Emitted when the gateway helper is updated
        @param operator The address performs the update
        @param newHelper The address of the new gateway helper
        @dev Related function: `updateGatewayHelper()`
    */
    event HelperUpdated(address indexed operator, address indexed newHelper);

    /**
        @notice Emitted when a payment is successfully executed
        @param payer The address that made the payment
        @param liquidator The address of the liquidator contract
        @param token The token being paid
        @param amount The amount being paid
        @dev Related function: `payment()`
    */
    event PaymentExecuted(
        address indexed payer,
        address indexed liquidator,
        address token,
        uint256 amount
    );

    /// @dev Transient storage stores the payer of the payment execution
    address internal transient _payer;
    /// @dev Transient storage stores the token being paid
    address internal transient _paymentToken;
    /// @dev Transient storage stores the amount being paid
    uint256 internal transient _paymentAmount;

    /// @dev The helper contract that helps to build the transaction data for the liquidation
    IGatewayHelper public gatewayHelper;

    constructor(
        address initProtocol,
        string memory name,
        string memory symbol
    )
        OptimexDomain(name, symbol)
        OptimexAdminGuard(IOptimexProtocol(initProtocol))
    {
        require(initProtocol != address(0), ErrorLib.ZeroAddress());
    }

    function setHelper(address newHelper) external onlyAdmin {
        require(newHelper != address(0), ErrorLib.ZeroAddress());
        gatewayHelper = IGatewayHelper(newHelper);

        emit HelperUpdated(msg.sender, newHelper);
    }

    /**
        @notice Gateway for liquidators to make payments to the designated liquidator
        @param amount The amount paid by the liquidator
        @param token The token being paid
        @param externalCall Encoded call data: (address liquidator, bytes data)
        @dev ⚠️ WARNING ⚠️  
            Only liquidators selected by the Optimex Protocol can redeem locked BTC.  
            Unauthorized liquidators will pay the debt but receive nothing in return,  
            as oBTC has no redeemable value and is transferred back to the ERC-20 contract, 
            effectively removing it from circulation. This may result in permanent loss of funds.
    */
    function payment(
        address token,
        uint256 amount,
        bytes calldata externalCall
    ) external nonReentrant {
        /// Ensure the following:
        /// - The token is not the zero address
        /// - The amount is greater than 0
        /// - The helper is set
        require(token != address(0), ErrorLib.ZeroAddress());
        require(amount > 0, ErrorLib.ZeroAmount());
        require(address(gatewayHelper) != address(0), ErrorLib.NoHelper());

        /// Snapshot balance before execution to ensure none remain after
        uint256 initialBalance = IERC20(token).balanceOf(address(this));

        /// Store these value into transient storage that can be used later by the liquidator
        _payer = msg.sender;
        _paymentToken = token;
        _paymentAmount = amount;
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);

        (address liquidator, bytes memory txCallData) = gatewayHelper
            .buildTxCalldata(token, amount, externalCall);
        IERC20(token).approval(liquidator, amount);

        /// @dev This execution pattern follows Morpho's Bundler3 contract approach:
        /// - https://github.com/morpho-org/bundler3/blob/e6fdcbcd2a59fe5fe9cbd9e0cf7d45f5d2aa3f49/src/Bundler3.sol#L63
        (bool success, bytes memory returnData) = liquidator.call(txCallData);
        if (!success) {
            UtilLib.lowLevelRevert(returnData);
        }

        /// @dev Verifies token and amount validity by comparing balances before and after.
        /// Ensures the liquidator contract consumes the exact amount, leaving no unused tokens.
        require(
            IERC20(token).balanceOf(address(this)) == initialBalance,
            ErrorLib.IncompleteConsumption()
        );

        emit PaymentExecuted(msg.sender, liquidator, token, amount);
    }

    /**
        @notice Returns details of the current payment execution.
        @dev Values are stored in transient storage and are only valid 
             within the scope of the current transaction.
        @return payer Address of the payer
        @return paymentToken Address of the token used for payment
        @return paymentAmount Amount being paid
 */
    function paymentDetails()
        external
        view
        returns (address payer, address paymentToken, uint256 paymentAmount)
    {
        payer = _payer;
        paymentToken = _paymentToken;
        paymentAmount = _paymentAmount;
    }
}
"
    },
    "contracts/protocol/OptimexAdminGuard.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import "../libraries/ErrorLib.sol";
import "../interfaces/IOptimexProtocol.sol";

/// @title OptimexAdminGuard
/// @notice Access control contract that provides admin-only functionality.
/// @dev This contract serves as a base contract for other Optimex contracts that need admin access control.
contract OptimexAdminGuard {
    /// @dev Address of the OptimexProtocol contract
    IOptimexProtocol internal _protocol;

    /**
        @notice Emitted when the OptimexProtocol address is updated.
        @param operator The address of the caller (owner) who performed the update.
        @param newProtocol The new OptimexProtocol contract address.
        @dev Related function: `setProtocol()`
    */
    event ProtocolUpdated(
        address indexed operator,
        address indexed newProtocol
    );

    modifier onlyAdmin() {
        address sender = msg.sender;
        if (sender != _getProtocol().owner())
            revert ErrorLib.Unauthorized(sender);
        _;
    }

    constructor(IOptimexProtocol protocol) {
        _protocol = protocol;
    }

    /**
        @notice Returns the current address of the OptimexProtocol contract.
        @dev Can be called by anyone.
        @return protocol The OptimexProtocol address.
    */
    function getProtocol() external view returns (address protocol) {
        protocol = address(_getProtocol());
    }

    /** 
        @notice Updates the OptimexProtocol contract to a new address.
        @dev Caller must be the current Admin of the OptimexProtocol contract.
        @param newProtocol The new OptimexProtocol contract address.
    */
    function setProtocol(address newProtocol) external onlyAdmin {
        if (newProtocol == address(0)) revert ErrorLib.ZeroAddress();

        _protocol = IOptimexProtocol(newProtocol);

        emit ProtocolUpdated(msg.sender, newProtocol);
    }

    function _isAuthorized(
        bytes32 role,
        address account
    ) internal view virtual returns (bool) {
        return _getProtocol().hasRole(role, account);
    }

    function _getProtocol() internal view virtual returns (IOptimexProtocol) {
        return _protocol;
    }
}
"
    },
    "contracts/protocol/OptimexDomain.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

/// @title Optimex Domain Information
/// @notice Provides a standardized way to expose the contract's name and version.
/// @dev Designed as an abstract base contract to be inherited by other Optimex contracts.
abstract contract OptimexDomain {
    /// @notice The name identifier for the Optimex contract domain.
    string internal _name;

    /// @notice The version identifier for the Optimex contract domain.
    string internal _version;

    constructor(string memory name, string memory version) {
        _name = name;
        _version = version;
    }

    /**
        @notice Returns the domain information of the Optimex contract.
        @dev Can be called by anyone
        @return name The name of the contract.
        @return version The current version of the contract.
    */
    function optimexDomain()
        external
        view
        virtual
        returns (string memory name, string memory version)
    {
        name = _name;
        version = _version;
    }
}
"
    }
  },
  "settings": {
    "viaIR": true,
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "evmVersion": "cancun",
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  }
}}

Tags:
ERC20, ERC165, Token, Factory|addr:0x4be396e85c09972728c114f781aa0e84a5f908e5|verified:true|block:23587195|tx:0x58238c9b835c8acc0cdab7289cd5858e85ec2c3391fa78972da128a4043f6e32|first_check:1760604536

Submitted on: 2025-10-16 10:48:59

Comments

Log in to comment.

No comments yet.