Skip to content
Verified contractExactUNLICENSED

LitePsmSwapHandler

Address0x47ca82eb163cd5ba04dcf387f8455f09cd543eac
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,131,036
Creation transaction
0x0d548150cf…91da949f3d

contracts/router/modules/LitePsmSwapHandler.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "../interfaces/ISwapHandler.sol";
import "../../shared/interfaces/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/HandlerGas.sol";

interface ILitePsm {
    function dai() external view returns (address);
    function gem() external view returns (address);
    function tout() external view returns (uint256);
    function to18ConversionFactor() external view returns (uint256);
    function sellGem(address usr, uint256 gemAmt) external returns (uint256 daiOutWad);
    function buyGem(address usr, uint256 gemAmt) external returns (uint256 daiInWad);
}

/// @title LitePsmSwapHandler
/// @notice Router-side handler for the Maker LitePSM (liquidityType 30,
///         pool_type "lite-psm"). `path.pairAddr` is the PSM contract
///         (0xf6e72Db5… on mainnet); direction is resolved on-chain from
///         psm.gem()/psm.dai() rather than trusted from the path tokens.
///
///         sellGem (gem -> DAI) is gem-denominated on the INPUT, so the
///         routed amount passes straight through. buyGem (DAI -> gem) is
///         gem-denominated on the OUTPUT, so we invert the PSM's own fee
///         math: gemAmt = daiIn * WAD / (to18ConversionFactor * (WAD + tout)),
///         and the sub-1-gem-unit DAI rounding dust is swept back to the
///         calling module. No inner minOut — the module enforces slippage.
contract LitePsmSwapHandler is ISwapHandler, Ownable {
    uint256 private constant WAD = 1e18;

    constructor() Ownable(msg.sender) {}

    /// @dev Zero-first exact approval (see BebopSwapHandler._approveExact):
    ///      USDT-style tokens revert when overwriting a non-zero allowance,
    ///      so every handler resets to 0 before approving the exact amount.
    function _approveExact(address token, address spender, uint256 amount) internal {
        HandlerGas.approveResting(token, spender, amount);
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address, /* from */
        address to
    ) external override returns (uint256 amountOut) {
        // amount == 0 resolves to our own balance — i.e. exactly what the
        // dispatching module transferred in (repo-wide handler convention).
        uint256 amountIn = HandlerGas.inputAmount(path.srcToken, amount);
        require(amountIn > 0, "litepsm: zero input");

        ILitePsm psm = ILitePsm(path.pairAddr);
        address gem = psm.gem();
        address dai = psm.dai();

        if (path.srcToken == gem) {
            // gem (USDC) -> DAI: input-denominated, tin applied by the PSM.
            require(path.dstToken == dai, "litepsm: dst != dai");
            _approveExact(gem, path.pairAddr, amountIn);
            amountOut = psm.sellGem(to, amountIn);
            HandlerGas.settleAllowance(gem, path.pairAddr);
        } else if (path.srcToken == dai) {
            // DAI -> gem (USDC): buyGem is OUTPUT-denominated; invert the
            // PSM fee math to spend at most amountIn.
            require(path.dstToken == gem, "litepsm: dst != gem");
            uint256 tout = psm.tout();
            uint256 to18 = psm.to18ConversionFactor();
            uint256 gemAmt = (amountIn * WAD) / (to18 * (WAD + tout));
            require(gemAmt > 0, "litepsm: zero gem out");

            // Exact DAI the PSM will pull (same rounding as DssLitePsm.buyGem),
            // so the allowance is consumed to zero.
            uint256 daiInWad = gemAmt * to18;
            daiInWad += (daiInWad * tout) / WAD;

            _approveExact(dai, path.pairAddr, daiInWad);
            psm.buyGem(to, gemAmt);
            HandlerGas.settleAllowance(dai, path.pairAddr);

            // Sweep the < 1 gem-unit rounding dust back to the module
            // (the handler's own 1-unit dust stays).
            uint256 remain = HandlerGas.spendable(dai);
            if (remain > 0) {
                TransferHelper.safeTransfer(dai, msg.sender, remain);
            }
            amountOut = gemAmt;
        } else {
            revert("litepsm: src not in psm");
        }
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@uniswap/lib/contracts/libraries/TransferHelper.sol

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeApprove: approve failed'
        );
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeTransfer: transfer failed'
        );
    }

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::transferFrom: transferFrom failed'
        );
    }

    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
    }
}

contracts/router/interfaces/ISwapHandler.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

interface ISwapHandler {
    struct PathDescription {
        address srcToken;
        address dstToken;
        address pairAddr;
        uint256 fee;
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint256 feeSrc;
        uint256 feeDst;
        uint256 liquidityType;
        bytes data;
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address from,
        address to
    ) external returns (uint256 amountOut);
}

contracts/router/libraries/HandlerGas.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "../../shared/interfaces/IERC20.sol";

/// Oku gas upgrade (review items 1-3): handler helpers so that a swap never
/// moves a storage slot 0 -> x -> 0. Such a slot costs 20,000 gas up front
/// and is refunded only at the end of the transaction, and eth_estimateGas
/// (what meta-aggregators rank by) counts the gas before the refund.
///   - allowances rest at 1 unit between swaps (1 -> x -> 1)
///   - balances keep 1 unit (the "dust") when the handler sweeps a token out
library HandlerGas {
    uint256 internal constant RESTING_ALLOWANCE = 1;
    uint256 internal constant DUST = 1;

    /// Lets `spender` pull `amount`, plus the resting unit that stays after
    /// an exact pull.
    function approveResting(address token, address spender, uint256 amount) internal {
        _approve(token, spender, amount + RESTING_ALLOWANCE);
    }

    /// Brings any allowance other than the resting unit back to it (a
    /// partial pull, a spender that does not decrement), so no allowance
    /// above 1 unit outlives the swap.
    function settleAllowance(address token, address spender) internal {
        if (IERC20(token).allowance(address(this), spender) != RESTING_ALLOWANCE) {
            _approve(token, spender, RESTING_ALLOWANCE);
        }
    }

    /// This contract's balance of `token` minus the 1-unit dust it keeps
    /// (0 when it holds only the dust or less).
    function spendable(address token) internal view returns (uint256 amount) {
        amount = IERC20(token).balanceOf(address(this));
        unchecked {
            amount = amount > DUST ? amount - DUST : 0;
        }
    }

    /// The input to spend: `amount`, capped at this contract's balance;
    /// `amount == 0` means the balance minus the dust. The module passes the
    /// exact amount it sent, but a share-rounding token (eETH, aTokens,
    /// cUSDCv3) delivers 1-2 wei less. Spending the full `amount` then took
    /// the shortfall from the dust and, once the dust was gone, reverted every
    /// later swap of that token. Capped, such a swap spends what it holds (the
    /// dust once, then what arrived).
    function inputAmount(address token, uint256 amount) internal view returns (uint256 amountIn) {
        if (amount == 0) return spendable(token);
        amountIn = IERC20(token).balanceOf(address(this));
        if (amount < amountIn) amountIn = amount;
    }

    /// approve(value); for tokens that refuse a nonzero -> nonzero approve
    /// (USDT-style), approve(0) first and retry.
    function _approve(address token, address spender, uint256 value) private {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, value));
        if (ok && (data.length == 0 || abi.decode(data, (bool)))) return;
        TransferHelper.safeApprove(token, spender, 0);
        TransferHelper.safeApprove(token, spender, value);
    }
}

contracts/shared/interfaces/IERC20.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IERC20 {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.