Перейти к содержимому
Проверенный контрактТочноеMIT

VaultTronBridgerV4

Адрес0x21edf8b0584a1b2d645ea3ae2bd3d9bb2e629e5b
Баланс

0 ETH

 

Транзакций

8

 

Компилятор

solc 0.8.24

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 355 824
Транзакция создания
0xc463a67012…b27b9f3436

contracts/vaulttronbridger4.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

    error Bridger4ZeroAddress();
    error Bridger4ZeroAmount();
    error Bridger4NotOperator(address caller);
    error Bridger4OftUsdtMismatch(address oftToken, address usdt);
    error Bridger4SwapTargetHasNoCode(address target);
    error Bridger4UnexpectedSentAmount(uint256 expected, uint256 actual);
    error Bridger4NativeRescueFailed(address to, uint256 amount);
    error Bridger4EthSendFailed(address to, uint256 amount);
    error Bridger4NoExactBridgeAmount(uint256 receivedLD);
    error Bridger4DeliveryMismatch(uint256 expected, uint256 actual);

// ---------------------------------------------------------------------------
// LayerZero V2 / OFT structs, exactly as declared by the canonical IOFT the
// deployed UsdtOFT implements (layerzerolabs/lz-evm-oapp-v2). Byte-identical
// to the copies in vaulttronbridger2.sol / tron/contracts/Usdt0DepositRouter.sol.
// ---------------------------------------------------------------------------

struct SendParam {
    uint32 dstEid;
    bytes32 to;
    uint256 amountLD;
    uint256 minAmountLD;
    bytes extraOptions;
    bytes composeMsg;
    bytes oftCmd;
}

struct MessagingFee {
    uint256 nativeFee;
    uint256 lzTokenFee;
}

struct MessagingReceipt {
    bytes32 guid;
    uint64 nonce;
    MessagingFee fee;
}

struct OFTLimit {
    uint256 minAmountLD;
    uint256 maxAmountLD;
}

struct OFTFeeDetail {
    int256 feeAmountLD;
    string description;
}

struct OFTReceipt {
    uint256 amountSentLD;
    uint256 amountReceivedLD;
}

interface IUsdtOFT {
    function token() external view returns (address);

    function feeBps() external view returns (uint16);

    function credits(uint32 eid) external view returns (uint256);

    function quoteOFT(
        SendParam calldata sendParam
    ) external view returns (OFTLimit memory, OFTFeeDetail[] memory, OFTReceipt memory);

    function quoteSend(
        SendParam calldata sendParam,
        bool payInLzToken
    ) external view returns (MessagingFee memory);

    function send(
        SendParam calldata sendParam,
        MessagingFee calldata fee,
        address refundAddress
    ) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}

/// @notice Uniswap V3 SwapRouter (deadline variant, 0xE592…) — both single-hop
///         entrypoints; the fee leg needs exact-output.
interface ISwapRouterV3 {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
}

interface IWETH9 {
    function withdraw(uint256 wad) external;
}

/// @notice The FreedomVault surface this bridger proxies (local declaration so
///         the compile units stay independent).
interface IFreedomVault {
    function withdrawDai(address to, uint256 amount) external;

    function withdrawAsUsdc(
        address to,
        uint256 usdcAmount,
        uint256 maxDaiIn
    ) external returns (uint256 daiSpent);

    function withdrawAsToken(
        address tokenOut,
        address to,
        uint256 usdcAmount,
        uint256 maxDaiIn,
        uint256 minTokenOut,
        bytes calldata path,
        uint256 deadline
    ) external returns (uint256 amountOut, uint256 daiSpent);

    function sendToken(IERC20 token, address to, uint256 amount) external;

    function admin() external view returns (address);
}

/// @notice V4 of the vault -> Tron periphery: everything V3 does, plus EXACT
///         OUTPUT for the two assets that could only be delivered "at least":
///           withdrawAsEthExact          — precisely `ethOut` of native ETH;
///           withdrawToTronSelfFundedExact — precisely `usdtReceivedLD` USDT
///                                           credited on Tron.
///         Both pull a CEILING of USDC from the vault, buy exact-output on
///         Uniswap, and send every USDC they did not spend BACK to the vault,
///         so the headroom the backend adds against price movement returns
///         as vault inventory instead of reaching the user. The Tron amount
///         handed to the mesh is solved on-chain against the OFT's own quote
///         (bridgeAmountForDelivery), so the fee rounding is the mesh's, not
///         a guess. Activation is the same exclusive vault.setAdmin(thisV4).
/// @notice V3 of the vault -> Tron periphery: everything V2 does, plus
///         withdrawAsEth — vault DAI delivered as NATIVE ETH (the vault swaps
///         to WETH into this contract, which unwraps and forwards plain ETH),
///         so fUSD -> ETH payouts need no wrap on the user's side.
/// @notice V2 of the vault -> Tron periphery. Everything VaultTronBridger does
///         (atomic vault DAI -> USDT -> Tron over USDT0, plus the operator-
///         gated proxy of the FreedomVault's whole admin withdrawal surface),
///         with one addition: SELF-FUNDED bridging. withdrawToTronSelfFunded
///         pays the LayerZero fee out of the withdrawn funds themselves —
///         the operator attaches NO ETH:
///
///           vault.withdrawAsUsdc(this, usdcAmount, maxDaiIn)   PSM, USDC here
///           OFT.quoteSend(...)                     exact fee, this very block
///           USDC -> WETH (exact-output, fee tier)  buy PRECISELY that fee
///           WETH9.withdraw                         unwrap to ETH
///           USDC (all that remains) -> USDT        0.01% pool
///           OFT.send{value: fee}(...)              bridge, guid emitted
///
///         Because the quote and the send happen in one transaction, there is
///         no staleness, no headroom guess, and no refund handling: the
///         contract buys exactly the fee it pays. A revert anywhere unwinds
///         everything — the no-stranded-funds property is preserved.
///
/// @dev  The LayerZero fee for an OFT send is amount-independent (message size
///       is constant), so quoting with the pre-swap USDC amount as a stand-in
///       amountLD is exact; any dust the endpoint doesn't consume refunds to
///       the CALLER. The v1 operator-paid paths (withdrawToTron, bridgeUsdt)
///       are retained unchanged as fallbacks.
///
///       Economics: this moves the ~0.005 ETH LayerZero fee from the operator
///       gas wallet onto the withdrawn amount (mirroring the deposit
///       direction, where users pay the fee in TRX). Small payouts are eaten
///       by the flat fee — the UI must deduct the live fee from the receive
///       estimate and enforce a minimum. maxFeeUsdc caps the fee leg on-chain.
///
///       Tron recipient encoding: T... base58 -> hex (21 bytes, 0x41 prefix),
///       DROP the 0x41, left-pad the 20 bytes to bytes32.
///
///       Deployment (Ethereum mainnet):
///         vault_   0xe30E14B891901471f0B3F1AC042391840555c41e (FreedomVault)
///         usdt_    0xdAC17F958D2ee523a2206206994597C13D831ec7
///         usdc_    0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
///         weth_    0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
///         oft_     0x1F748c76dE468e9D11bd340fA9D5CBADf315dFB0 (Legacy Mesh)
///         univ3_   0xE592427A0AEce92De3Edee1F18E0157C05861564
///         tronEid_ 30420
///       POST-DEPLOY: vault owner calls vault.setAdmin(thisV2) — the vault's
///       admin slot is EXCLUSIVE, so this simultaneously deauthorizes the v1
///       bridger; the backend redirects its calls here. Rollback: setAdmin
///       back to the v1 bridger (or the operator EOA).
contract VaultTronBridgerV4 is Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    IFreedomVault public immutable VAULT;
    IERC20 public immutable USDT;
    IERC20 public immutable USDC;
    IWETH9 public immutable WETH;
    IUsdtOFT public immutable OFT;
    ISwapRouterV3 public immutable UNIV3;
    uint32 public immutable TRON_EID;

    /// @notice Backend operator allowed to trigger withdrawals.
    address public operator;

    event OperatorSet(address indexed operator);
    event ERC20Rescued(address indexed token, address indexed to, uint256 amount);
    event NativeRescued(address indexed to, uint256 amount);

    /// @notice One USDT batch handed to the Legacy Mesh; `guid` reappears in
    ///         the Tron-side delivery.
    event BridgedToTron(
        bytes32 indexed guid,
        bytes32 indexed tronRecipient,
        uint256 amountSentLD,
        uint256 amountReceivedLD,
        uint64 nonce
    );

    /// @notice Companion to BridgedToTron on the self-funded path: what the
    ///         LayerZero fee cost, in ETH and in the USDC that bought it.
    event FeeSelfFunded(bytes32 indexed guid, uint256 nativeFeeWei, uint256 feeUsdcSpent);

    /// @notice One native-ETH payout: what left the vault (DAI) and what the
    ///         recipient received (plain ETH, post-unwrap).
    event WithdrawnAsEth(address indexed to, uint256 ethOut, uint256 daiSpent);

    /// @notice One exact native-ETH payout: what the recipient got, what the
    ///         swap cost, what went back to the vault, and the DAI it all took.
    event WithdrawnAsEthExact(address indexed to, uint256 ethOut, uint256 usdcSpent, uint256 usdcReturned, uint256 daiSpent);

    /// @notice Companion to BridgedToTron on the exact path: the delivery the
    ///         mesh will credit, the USDC both legs cost, and what went back.
    event BridgedToTronExact(bytes32 indexed guid, uint256 usdtReceivedLD, uint256 usdcSpent, uint256 usdcReturned);

    modifier onlyOperatorOrOwner() {
        if (msg.sender != operator && msg.sender != owner()) {
            revert Bridger4NotOperator(msg.sender);
        }
        _;
    }

    constructor(
        IFreedomVault vault_,
        IERC20 usdt_,
        IERC20 usdc_,
        IWETH9 weth_,
        IUsdtOFT oft_,
        ISwapRouterV3 univ3_,
        uint32 tronEid_,
        address operator_,
        address initialOwner
    ) Ownable(initialOwner) {
        if (address(vault_) == address(0)) revert Bridger4ZeroAddress();
        if (address(usdt_) == address(0)) revert Bridger4ZeroAddress();
        if (address(usdc_) == address(0)) revert Bridger4ZeroAddress();
        if (address(weth_) == address(0)) revert Bridger4ZeroAddress();
        if (address(oft_) == address(0)) revert Bridger4ZeroAddress();

        if (oft_.token() != address(usdt_)) {
            revert Bridger4OftUsdtMismatch(oft_.token(), address(usdt_));
        }
        if (address(univ3_).code.length == 0) {
            revert Bridger4SwapTargetHasNoCode(address(univ3_));
        }

        VAULT = vault_;
        USDT = usdt_;
        USDC = usdc_;
        WETH = weth_;
        OFT = oft_;
        UNIV3 = univ3_;
        TRON_EID = tronEid_;

        _setOperator(operator_);
    }

    /* --------------------------- self-funded bridge --------------------------- */

    struct SelfFundedParams {
        bytes32 tronRecipient; // Tron account, 0x41 prefix dropped, left-padded
        uint256 usdcAmount; // total USDC pulled from the vault, 6 decimals
        uint256 maxDaiIn; // cap on the DAI spent in the PSM leg
        uint256 maxFeeUsdc; // cap on the USDC spent buying the fee ETH
        uint256 minUsdtOut; // floor on the USDT from the remaining USDC
        uint24 ethPoolFee; // USDC/WETH Uniswap tier for the fee leg (500)
        uint24 usdtPoolFee; // USDC/USDT Uniswap tier for the main leg (100)
        uint256 deadline; // bounds both Uniswap legs
        uint256 minAmountReceivedLD; // floor on USDT credited on Tron; 0 = exact-out at quote
    }

    /// @notice Withdraw vault DAI, pay the LayerZero fee out of the withdrawn
    ///         funds, and bridge the rest to Tron as USDT — one transaction,
    ///         NO ETH attached. The fee is quoted, bought, and spent in this
    ///         same transaction, so it is exact by construction.
    function withdrawToTronSelfFunded(
        SelfFundedParams calldata p
    )
        external
        onlyOperatorOrOwner
        nonReentrant
        returns (bytes32 guid, uint256 amountSentLD, uint256 amountReceivedLD, uint256 feeUsdcSpent)
    {
        if (p.minUsdtOut == 0) revert Bridger4ZeroAmount();

        VAULT.withdrawAsUsdc(address(this), p.usdcAmount, p.maxDaiIn);

        // The exact fee, quoted in this very block. amountLD is a stand-in
        // (the pre-swap USDC amount): OFT send fees are amount-independent.
        MessagingFee memory fee = OFT.quoteSend(
            SendParam({
                dstEid: TRON_EID,
                to: p.tronRecipient,
                amountLD: p.usdcAmount,
                minAmountLD: 0,
                extraOptions: "",
                composeMsg: "",
                oftCmd: ""
            }),
            false
        );

        // Fee leg: buy PRECISELY fee.nativeFee of WETH, unwrap to ETH.
        USDC.forceApprove(address(UNIV3), p.maxFeeUsdc);

        feeUsdcSpent = UNIV3.exactOutputSingle(
            ISwapRouterV3.ExactOutputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(WETH),
                fee: p.ethPoolFee,
                recipient: address(this),
                deadline: p.deadline,
                amountOut: fee.nativeFee,
                amountInMaximum: p.maxFeeUsdc,
                sqrtPriceLimitX96: 0
            })
        );

        WETH.withdraw(fee.nativeFee);

        // Main leg: everything still here goes to USDT (balance-based, so any
        // stray USDC is swept along instead of resting).
        uint256 usdcForUsdt = USDC.balanceOf(address(this));

        USDC.forceApprove(address(UNIV3), usdcForUsdt);

        uint256 usdtOut = UNIV3.exactInputSingle(
            ISwapRouterV3.ExactInputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(USDT),
                fee: p.usdtPoolFee,
                recipient: address(this),
                deadline: p.deadline,
                amountIn: usdcForUsdt,
                amountOutMinimum: p.minUsdtOut,
                sqrtPriceLimitX96: 0
            })
        );

        USDC.forceApprove(address(UNIV3), 0);

        (guid, amountSentLD, amountReceivedLD) = _bridge(
            p.tronRecipient,
            usdtOut,
            p.minAmountReceivedLD,
            fee.nativeFee
        );

        emit FeeSelfFunded(guid, fee.nativeFee, feeUsdcSpent);
    }

    /* ---------------------- v1 (operator-paid) entrypoints ---------------------- */

    /// @notice v1 path: vault swaps to USDT itself, the operator attaches the
    ///         LayerZero fee as msg.value (excess refunds to the caller).
    function withdrawToTron(
        bytes32 tronRecipient,
        uint256 usdcAmount,
        uint256 maxDaiIn,
        uint256 minUsdtOut,
        bytes calldata path,
        uint256 deadline,
        uint256 minAmountReceivedLD
    )
        external
        payable
        onlyOperatorOrOwner
        nonReentrant
        returns (bytes32 guid, uint256 amountSentLD, uint256 amountReceivedLD)
    {
        (uint256 usdtOut, ) = VAULT.withdrawAsToken(
            address(USDT),
            address(this),
            usdcAmount,
            maxDaiIn,
            minUsdtOut,
            path,
            deadline
        );

        return _bridge(tronRecipient, usdtOut, minAmountReceivedLD, msg.value);
    }

    /// @notice Bridge USDT already sitting on THIS contract; fee via msg.value.
    function bridgeUsdt(
        bytes32 tronRecipient,
        uint256 amountLD,
        uint256 minAmountReceivedLD
    )
        external
        payable
        onlyOperatorOrOwner
        nonReentrant
        returns (bytes32 guid, uint256 amountSentLD, uint256 amountReceivedLD)
    {
        if (amountLD == 0) revert Bridger4ZeroAmount();

        return _bridge(tronRecipient, amountLD, minAmountReceivedLD, msg.value);
    }

    function _bridge(
        bytes32 tronRecipient,
        uint256 amountLD,
        uint256 minAmountReceivedLD,
        uint256 nativeFeeWei
    ) private returns (bytes32 guid, uint256 amountSentLD, uint256 amountReceivedLD) {
        if (tronRecipient == bytes32(0)) revert Bridger4ZeroAddress();

        SendParam memory sendParam = SendParam({
            dstEid: TRON_EID,
            to: tronRecipient,
            amountLD: amountLD,
            minAmountLD: 0,
            extraOptions: "",
            composeMsg: "",
            oftCmd: ""
        });

        if (minAmountReceivedLD == 0) {
            (, , OFTReceipt memory quoted) = OFT.quoteOFT(sendParam);
            minAmountReceivedLD = quoted.amountReceivedLD;
        }
        sendParam.minAmountLD = minAmountReceivedLD;

        USDT.forceApprove(address(OFT), amountLD);

        (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) = OFT.send{value: nativeFeeWei}(
            sendParam,
            MessagingFee({nativeFee: nativeFeeWei, lzTokenFee: 0}),
            msg.sender
        );

        USDT.forceApprove(address(OFT), 0);

        if (oftReceipt.amountSentLD != amountLD) {
            revert Bridger4UnexpectedSentAmount(amountLD, oftReceipt.amountSentLD);
        }

        emit BridgedToTron(
            msgReceipt.guid,
            tronRecipient,
            oftReceipt.amountSentLD,
            oftReceipt.amountReceivedLD,
            msgReceipt.nonce
        );

        return (msgReceipt.guid, oftReceipt.amountSentLD, oftReceipt.amountReceivedLD);
    }

    /// @notice Fee/ceiling quote for a bridge of `amountLD` USDT. The backend
    ///         (or swapv3 UI, via any RPC) uses nativeFee to price the fee
    ///         deduction; on the self-funded path the USDC cost of that fee is
    ///         set by the live USDC/WETH price at execution, capped by
    ///         maxFeeUsdc.
    function quoteWithdrawToTron(
        bytes32 tronRecipient,
        uint256 amountLD
    ) external view returns (uint256 nativeFee, uint256 amountReceivedLD, uint256 maxAmountLD) {
        SendParam memory sendParam = SendParam({
            dstEid: TRON_EID,
            to: tronRecipient,
            amountLD: amountLD,
            minAmountLD: 0,
            extraOptions: "",
            composeMsg: "",
            oftCmd: ""
        });

        (OFTLimit memory limit, , OFTReceipt memory receipt) = OFT.quoteOFT(sendParam);

        sendParam.minAmountLD = receipt.amountReceivedLD;

        MessagingFee memory fee = OFT.quoteSend(sendParam, false);

        return (fee.nativeFee, receipt.amountReceivedLD, limit.maxAmountLD);
    }

    /* ---------------------------- native-ETH payout ---------------------------- */

    /// @notice Withdraw vault DAI delivered as NATIVE ETH, atomically:
    ///         vault DAI -> PSM USDC -> WETH (Uniswap V3, into this contract)
    ///         -> WETH9.withdraw -> plain ETH to `to`. A revert anywhere
    ///         unwinds everything; nothing rests in this contract.
    /// @param minWethOut Floor on the Uniswap leg (vault-enforced), 18 dp.
    /// @param wethPoolFee USDC/WETH tier for the swap leg (500 = the deep 0.05% pool).
    function withdrawAsEth(
        address payable to,
        uint256 usdcAmount,
        uint256 maxDaiIn,
        uint256 minWethOut,
        uint24 wethPoolFee,
        uint256 deadline
    ) external onlyOperatorOrOwner nonReentrant returns (uint256 ethOut, uint256 daiSpent) {
        if (to == address(0)) revert Bridger4ZeroAddress();

        bytes memory path = abi.encodePacked(address(USDC), wethPoolFee, address(WETH));
        (ethOut, daiSpent) = VAULT.withdrawAsToken(
            address(WETH),
            address(this),
            usdcAmount,
            maxDaiIn,
            minWethOut,
            path,
            deadline
        );

        WETH.withdraw(ethOut);

        (bool ok, ) = to.call{value: ethOut}("");
        if (!ok) revert Bridger4EthSendFailed(to, ethOut);

        emit WithdrawnAsEth(to, ethOut, daiSpent);
    }

    /* ------------------------------ exact output ------------------------------ */

    /// @notice The USDT to hand the mesh so that EXACTLY `receivedLD` is credited
    ///         on Tron. The fee (feeBps of the amount, rounded the OFT's way) and
    ///         any dust rule are the OFT's own, so the candidate from the fee
    ///         formula is checked against quoteOFT and nudged one unit at a time
    ///         until the receipt names the target. Reverts when none does.
    function bridgeAmountForDelivery(uint256 receivedLD) public view returns (uint256 amountLD) {
        if (receivedLD == 0) revert Bridger4ZeroAmount();
        uint256 bps = OFT.feeBps();
        amountLD = (receivedLD * 10_000 + (10_000 - bps - 1)) / (10_000 - bps);
        for (uint256 i = 0; i < 8; i++) {
            uint256 got = _quotedDelivery(amountLD);
            if (got == receivedLD) return amountLD;
            if (got > receivedLD) amountLD -= 1;
            else amountLD += 1;
        }
        revert Bridger4NoExactBridgeAmount(receivedLD);
    }

    function _quotedDelivery(uint256 amountLD) private view returns (uint256) {
        (, , OFTReceipt memory quoted) = OFT.quoteOFT(
            SendParam({
                dstEid: TRON_EID,
                to: bytes32(uint256(1)),
                amountLD: amountLD,
                minAmountLD: 0,
                extraOptions: "",
                composeMsg: "",
                oftCmd: ""
            })
        );
        return quoted.amountReceivedLD;
    }

    /// @notice Exactly `ethOut` of native ETH to `to`, paid from vault DAI: the
    ///         vault buys `usdcMax` USDC at the PSM into this contract, Uniswap
    ///         exact-output buys precisely `ethOut` of WETH out of it, the WETH
    ///         is unwrapped and forwarded, and every USDC not spent goes back
    ///         to the vault. Nothing rests here; a revert anywhere unwinds all.
    /// @param usdcMax Ceiling on the USDC the swap may spend (and what the vault buys).
    function withdrawAsEthExact(
        address payable to,
        uint256 ethOut,
        uint256 usdcMax,
        uint256 maxDaiIn,
        uint24 wethPoolFee,
        uint256 deadline
    ) external onlyOperatorOrOwner nonReentrant returns (uint256 usdcSpent, uint256 usdcReturned, uint256 daiSpent) {
        if (to == address(0)) revert Bridger4ZeroAddress();
        if (ethOut == 0 || usdcMax == 0) revert Bridger4ZeroAmount();

        daiSpent = VAULT.withdrawAsUsdc(address(this), usdcMax, maxDaiIn);

        USDC.forceApprove(address(UNIV3), usdcMax);
        usdcSpent = UNIV3.exactOutputSingle(
            ISwapRouterV3.ExactOutputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(WETH),
                fee: wethPoolFee,
                recipient: address(this),
                deadline: deadline,
                amountOut: ethOut,
                amountInMaximum: usdcMax,
                sqrtPriceLimitX96: 0
            })
        );
        USDC.forceApprove(address(UNIV3), 0);

        WETH.withdraw(ethOut);
        (bool ok, ) = to.call{value: ethOut}("");
        if (!ok) revert Bridger4EthSendFailed(to, ethOut);

        usdcReturned = _returnUsdcToVault();
        emit WithdrawnAsEthExact(to, ethOut, usdcSpent, usdcReturned, daiSpent);
    }

    struct SelfFundedExactParams {
        bytes32 tronRecipient; // Tron account, 0x41 prefix dropped, left-padded
        uint256 usdtReceivedLD; // what the mesh must credit on Tron, 6 decimals
        uint256 usdcMax; // ceiling on the USDC pulled from the vault for both legs; the rest returns
        uint256 maxDaiIn; // cap on the DAI spent in the PSM leg
        uint256 maxFeeUsdc; // cap on the USDC spent buying the fee ETH
        uint24 ethPoolFee; // USDC/WETH Uniswap tier for the fee leg (500)
        uint24 usdtPoolFee; // USDC/USDT Uniswap tier for the main leg (100)
        uint256 deadline; // bounds both Uniswap legs
    }

    /// @notice The self-funded bridge with the DELIVERY fixed: solves the mesh
    ///         amount for `usdtReceivedLD`, buys exactly that USDT and exactly
    ///         the LayerZero fee out of the vault's USDC, bridges, and returns
    ///         the unspent USDC to the vault. The OFT receipt must name the
    ///         target or the whole transaction reverts.
    function withdrawToTronSelfFundedExact(
        SelfFundedExactParams calldata p
    )
        external
        onlyOperatorOrOwner
        nonReentrant
        returns (bytes32 guid, uint256 amountSentLD, uint256 usdcSpent, uint256 usdcReturned)
    {
        if (p.usdtReceivedLD == 0 || p.usdcMax == 0) revert Bridger4ZeroAmount();
        uint256 amountLD = bridgeAmountForDelivery(p.usdtReceivedLD);

        VAULT.withdrawAsUsdc(address(this), p.usdcMax, p.maxDaiIn);

        MessagingFee memory fee = OFT.quoteSend(
            SendParam({
                dstEid: TRON_EID,
                to: p.tronRecipient,
                amountLD: amountLD,
                minAmountLD: 0,
                extraOptions: "",
                composeMsg: "",
                oftCmd: ""
            }),
            false
        );

        USDC.forceApprove(address(UNIV3), p.usdcMax);
        uint256 feeUsdcSpent = UNIV3.exactOutputSingle(
            ISwapRouterV3.ExactOutputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(WETH),
                fee: p.ethPoolFee,
                recipient: address(this),
                deadline: p.deadline,
                amountOut: fee.nativeFee,
                amountInMaximum: p.maxFeeUsdc,
                sqrtPriceLimitX96: 0
            })
        );
        WETH.withdraw(fee.nativeFee);

        uint256 usdtUsdcSpent = UNIV3.exactOutputSingle(
            ISwapRouterV3.ExactOutputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(USDT),
                fee: p.usdtPoolFee,
                recipient: address(this),
                deadline: p.deadline,
                amountOut: amountLD,
                amountInMaximum: USDC.balanceOf(address(this)),
                sqrtPriceLimitX96: 0
            })
        );
        USDC.forceApprove(address(UNIV3), 0);
        usdcSpent = feeUsdcSpent + usdtUsdcSpent;

        uint256 receivedLD;
        (guid, amountSentLD, receivedLD) = _bridge(p.tronRecipient, amountLD, p.usdtReceivedLD, fee.nativeFee);
        if (receivedLD != p.usdtReceivedLD) revert Bridger4DeliveryMismatch(p.usdtReceivedLD, receivedLD);

        usdcReturned = _returnUsdcToVault();
        emit FeeSelfFunded(guid, fee.nativeFee, feeUsdcSpent);
        emit BridgedToTronExact(guid, p.usdtReceivedLD, usdcSpent, usdcReturned);
    }

    /// @dev Every USDC still here goes back to the vault as inventory.
    function _returnUsdcToVault() private returns (uint256 returned) {
        returned = USDC.balanceOf(address(this));
        if (returned > 0) USDC.safeTransfer(address(VAULT), returned);
    }

    /* ------------------------- vault admin passthroughs ------------------------- */

    function withdrawDai(address to, uint256 amount) external onlyOperatorOrOwner nonReentrant {
        VAULT.withdrawDai(to, amount);
    }

    function withdrawAsUsdc(
        address to,
        uint256 usdcAmount,
        uint256 maxDaiIn
    ) external onlyOperatorOrOwner nonReentrant returns (uint256 daiSpent) {
        return VAULT.withdrawAsUsdc(to, usdcAmount, maxDaiIn);
    }

    function withdrawAsToken(
        address tokenOut,
        address to,
        uint256 usdcAmount,
        uint256 maxDaiIn,
        uint256 minTokenOut,
        bytes calldata path,
        uint256 deadline
    ) external onlyOperatorOrOwner nonReentrant returns (uint256 amountOut, uint256 daiSpent) {
        return VAULT.withdrawAsToken(tokenOut, to, usdcAmount, maxDaiIn, minTokenOut, path, deadline);
    }

    function sendToken(IERC20 token, address to, uint256 amount) external onlyOperatorOrOwner nonReentrant {
        VAULT.sendToken(token, to, amount);
    }

    /* ---------------------------- owner controls ---------------------------- */

    function setOperator(address newOperator) external onlyOwner {
        _setOperator(newOperator);
    }

    function _setOperator(address newOperator) private {
        if (newOperator == address(0)) revert Bridger4ZeroAddress();

        operator = newOperator;

        emit OperatorSet(newOperator);
    }

    function rescueERC20(IERC20 token, address to, uint256 amount) external onlyOwner nonReentrant {
        if (address(token) == address(0)) revert Bridger4ZeroAddress();
        if (to == address(0)) revert Bridger4ZeroAddress();
        if (amount == 0) revert Bridger4ZeroAmount();

        token.safeTransfer(to, amount);

        emit ERC20Rescued(address(token), to, amount);
    }

    function rescueNative(address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert Bridger4ZeroAddress();
        if (amount == 0) revert Bridger4ZeroAmount();

        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert Bridger4NativeRescueFailed(to, amount);

        emit NativeRescued(to, amount);
    }

    /// @dev Receives the WETH9.withdraw unwrap and any endpoint fee refunds.
    receive() external payable {}
}

@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/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 _safeTransfer(token, to, value, false);
    }

    /**
     * @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 _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@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;
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

import {StorageSlot} from "./StorageSlot.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @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);
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.