Skip to content
Verified contractExactMIT

SKChainflipVault4626_V2

Address0x73ab06be684092743327f59bbae994dd4f63b4f5
Balance

0 ETH

 

Transactions

7

 

Compiler

solc 0.8.22

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.22+commit.4fc1097e
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,171,959
Creation transaction
0x4bdcf694db…e4950c2649

project/src/contracts/aggregators/chainflip/SKChainflipVault4626_V2.sol

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

import {Owners} from "../../../lib/Owners.sol";
import {SafeTransferLib} from "../../../lib/SafeTransferLib.sol";
import {IChainflipReceiver} from "../../../interfaces/IChainflipReceiver.sol";
import {IChainflipVault} from "../../../interfaces/IChainflipVault.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {IERC20} from "../../../interfaces/IERC20.sol";
import {SKAggregator_V1} from "../../abstract/SKAggregator_V1.sol";
import {SKChainflipAggregator_V1} from "../../abstract/SKChainflipAggregator_V1.sol";

/// @title SKChainflipVault4626_V2
/// @notice Chainflip CCM <-> Kiln ERC-4626 vault aggregator (Ledger "Swap to Earn").
/// @dev DEPOSIT (earn): Chainflip swaps any asset -> USDC/USDT and delivers it to this
///      contract with a CCM `message`; `cfReceive` decodes {vault, recipient, minShares}
///      and deposits into the ERC-4626 vault, minting shares directly to the recipient.
/// @dev WITHDRAW: user redeems vault shares -> underlying -> Chainflip `xSwapToken` out to
///      any asset, in a single signature.
/// @dev The `cfReceive` path is deliberately NON-REVERTING: a revert on the Chainflip
///      callback would strand user funds, so on any failure funds are swept to the
///      recipient (or `lostFundsCollector` when the payload can't be decoded). This
///      mirrors the professional-engineer-authored `cf-evm-agg/Receiver.sol` reference.
/// @dev V2 vs V1: clears the spending allowance after the ERC-4626 deposit and after the
///      Chainflip `xSwapToken`, so a spender that pulls less than it was approved for
///      leaves no standing allowance behind (PeckShield PVE-001). V1 is unchanged and
///      stays deployed; see audits/PeckShield-Audit-Report-Swapkit-ChainflipVault-v1.0rc.pdf.
contract SKChainflipVault4626_V2 is
    Owners,
    IChainflipReceiver,
    SKAggregator_V1,
    SKChainflipAggregator_V1
{
    using SafeTransferLib for address;

    /// @dev Address Chainflip uses to signal the native asset.
    address private constant _CF_NATIVE_ADDR =
        0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /// @notice CCM payload delivered on the source chain and decoded on arrival.
    /// @param vault The ERC-4626 vault to deposit the delivered asset into.
    /// @param recipient Address that receives the minted vault shares.
    /// @param minShares Slippage guard: minimum shares that must be minted.
    struct CCMVaultDeposit {
        address vault;
        address recipient;
        uint256 minShares;
    }

    /// @notice Catch-all recipient when there is no valid user address (undecodable payload).
    address public lostFundsCollector;

    /// @notice Owner-managed vault allowlist (defense-in-depth on top of the asset() check).
    mapping(address => bool) public allowedVaults;

    /// @notice When true, deposits only succeed into allowlisted vaults.
    bool public enforceVaultAllowlist;

    event VaultDeposit(
        uint32 srcChain,
        bytes srcAddress,
        address indexed vault,
        address indexed recipient,
        address token,
        uint256 amount,
        uint256 sharesMinted
    );
    event VaultDepositFallback(
        address indexed recipient,
        address token,
        uint256 amount,
        string reason
    );
    event VaultRedeem(
        address indexed from,
        address indexed vault,
        uint256 shares,
        address underlying,
        uint256 underlyingOut,
        uint32 dstChain,
        uint32 dstToken
    );
    event SweptFunds(address indexed to, address token, uint256 amount);
    event VaultAllowed(address indexed vault, bool allowed);
    event EnforceVaultAllowlistSet(bool enforced);
    event LostFundsCollectorSet(address indexed collector);

    /// @notice CREATE2-compatible constructor.
    /// @dev TTP / Permit2 are set post-deployment via setters (chain-specific).
    /// @param _feeRecipient Address to receive protocol fees (cross-chain constant).
    /// @param _cfVault Chainflip Vault address (can be updated via `updateCfVault`).
    /// @param _lostFundsCollector Catch-all for undecodable-payload funds.
    constructor(
        address _feeRecipient,
        address _cfVault,
        address _lostFundsCollector
    )
        SKAggregator_V1(address(0), _feeRecipient)
        SKChainflipAggregator_V1(_cfVault)
    {
        _setOwner(tx.origin, true);
        require(_lostFundsCollector != address(0), "invalid collector");
        lostFundsCollector = _lostFundsCollector;
        enforceVaultAllowlist = true;
    }

    //////////////////////////////////////////////////////////////
    //                    Chainflip receiver                    //
    //////////////////////////////////////////////////////////////

    /// @notice Chainflip CCM entry point. Only callable by the Chainflip Vault.
    /// @dev For ERC-20, Chainflip transfers `amount` of `token` to this contract before the call.
    /// @param srcChain Source chain id (provenance only).
    /// @param srcAddress Source address (provenance only).
    /// @param message ABI-encoded `CCMVaultDeposit`.
    /// @param token The delivered token (USDC/USDT), or the native sentinel.
    /// @param amount The delivered amount.
    function cfReceive(
        uint32 srcChain,
        bytes calldata srcAddress,
        bytes calldata message,
        address token,
        uint256 amount
    ) external payable onlyCfVault nonReentrant {
        token = token == _CF_NATIVE_ADDR ? address(0) : token;

        // The asset is already in the contract; snapshot the pre-delivery balance.
        uint256 initialBalance = _getAssetBalance(token) - amount;

        // Non-reverting decode: bad payloads route funds to the lostFundsCollector.
        CCMVaultDeposit memory dep;
        try this.decodeMessage(message) returns (CCMVaultDeposit memory _dep) {
            dep = _dep;
        } catch {
            _sweepFunds(token, lostFundsCollector, amount);
            emit VaultDepositFallback(lostFundsCollector, token, amount, "decode");
            return;
        }

        address dest = dep.recipient == address(0) ? lostFundsCollector : dep.recipient;

        // Attempt the vault deposit in a try/catch so a failure never reverts the callback.
        try this._depositToVault(dep.vault, token, amount, dest, dep.minShares) returns (
            uint256 sharesMinted
        ) {
            emit VaultDeposit(srcChain, srcAddress, dep.vault, dest, token, amount, sharesMinted);
        } catch {
            // The deposit (incl. fee transfer) rolled back; refund the full delivered amount.
            _sweepFunds(token, dest, amount);
            emit VaultDepositFallback(dest, token, amount, "deposit");
        }

        // Safety net: sweep any residual delivered asset back to the recipient.
        uint256 finalBalance = _getAssetBalance(token);
        if (finalBalance > initialBalance) {
            _sweepFunds(token, dest, finalBalance - initialBalance);
        }
    }

    /// @notice Fee + approve + ERC-4626 deposit. External so `cfReceive` can try/catch it.
    /// @dev Self-only: pulling from the contract balance for an arbitrary receiver would
    ///      otherwise be an open drain of any stuck funds.
    function _depositToVault(
        address vault,
        address token,
        uint256 amount,
        address recipient,
        uint256 minShares
    ) external returns (uint256 sharesMinted) {
        require(msg.sender == address(this), "only self");
        require(IERC4626(vault).asset() == token, "vault asset mismatch");
        if (enforceVaultAllowlist) {
            require(allowedVaults[vault], "vault not allowed");
        }

        uint256 depositAmount = takeFee(token, amount);

        // zero-first approval for USDT-like tokens
        token.safeApprove(vault, 0);
        token.safeApprove(vault, depositAmount);
        sharesMinted = IERC4626(vault).deposit(depositAmount, recipient);
        _clearAllowance(token, vault);

        require(sharesMinted >= minShares, "insufficient shares");
    }

    /// @notice Decode the CCM message. External + pure so `cfReceive` can try/catch it.
    function decodeMessage(
        bytes calldata message
    ) public pure returns (CCMVaultDeposit memory) {
        return abi.decode(message, (CCMVaultDeposit));
    }

    //////////////////////////////////////////////////////////////
    //                    Withdraw (vault -> CF)                //
    //////////////////////////////////////////////////////////////

    /// @notice Redeem ERC-4626 shares to the underlying and swap out via Chainflip.
    /// @dev Shares pulled via the TokenTransferProxy (requires a prior TTP approval).
    /// @param vault The ERC-4626 vault to redeem from.
    /// @param shares Amount of vault shares to redeem.
    /// @param dstChain Chainflip destination chain id.
    /// @param dstAddress Chainflip destination address (chain-encoded).
    /// @param dstToken Chainflip destination asset id.
    /// @param cfParameters Chainflip Fill-or-Kill / broker / affiliate parameters.
    /// @param minOut Minimum underlying out from the redeem (slippage guard).
    function redeemAndSwapOut(
        address vault,
        uint256 shares,
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        bytes calldata cfParameters,
        uint256 minOut
    ) external nonReentrant {
        uint256 sharesReceived = _pullTokens(vault, msg.sender, shares);
        _redeemAndSwapOut(vault, sharesReceived, dstChain, dstAddress, dstToken, cfParameters, minOut);
    }

    /// @notice Same as `redeemAndSwapOut` but pulls shares via Permit2 (single signature).
    function redeemAndSwapOutWithPermit2(
        address vault,
        uint256 shares,
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        bytes calldata cfParameters,
        uint256 minOut,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) external nonReentrant {
        require(permit2 != address(0), "Permit2 not set");
        uint256 sharesReceived = _pullTokensWithPermit2(
            vault,
            msg.sender,
            shares,
            nonce,
            deadline,
            signature
        );
        _redeemAndSwapOut(vault, sharesReceived, dstChain, dstAddress, dstToken, cfParameters, minOut);
    }

    function _redeemAndSwapOut(
        address vault,
        uint256 sharesReceived,
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        bytes calldata cfParameters,
        uint256 minOut
    ) internal {
        address underlying = IERC4626(vault).asset();

        uint256 assetsOut = IERC4626(vault).redeem(sharesReceived, address(this), address(this));
        require(assetsOut >= minOut, "insufficient output");

        uint256 safeAmount = takeFee(underlying, assetsOut);

        underlying.safeApprove(cfVault, 0);
        underlying.safeApprove(cfVault, safeAmount);
        IChainflipVault(cfVault).xSwapToken(
            dstChain,
            dstAddress,
            dstToken,
            IERC20(underlying),
            safeAmount,
            cfParameters
        );
        _clearAllowance(underlying, cfVault);

        emit VaultRedeem(msg.sender, vault, sharesReceived, underlying, safeAmount, dstChain, dstToken);
    }

    //////////////////////////////////////////////////////////////
    //                    Governance & Getters                  //
    //////////////////////////////////////////////////////////////

    function setVaultAllowed(address vault, bool allowed) external isOwner {
        allowedVaults[vault] = allowed;
        emit VaultAllowed(vault, allowed);
    }

    function setEnforceVaultAllowlist(bool enforced) external isOwner {
        enforceVaultAllowlist = enforced;
        emit EnforceVaultAllowlistSet(enforced);
    }

    function setLostFundsCollector(address _lostFundsCollector) external isOwner {
        require(_lostFundsCollector != address(0), "invalid collector");
        lostFundsCollector = _lostFundsCollector;
        emit LostFundsCollectorSet(_lostFundsCollector);
    }

    //////////////////////////////////////////////////////////////
    //                        Utilities                         //
    //////////////////////////////////////////////////////////////

    /// @dev Reset a spender's allowance to zero when it did not consume all of it.
    /// @dev An ERC-4626 vault or the Chainflip Vault normally pulls the exact amount it was
    ///      approved for, leaving nothing behind; one that pulls less (a deposit cap, a
    ///      fee-on-transfer underlying) would otherwise leave a standing allowance. The
    ///      read is a warm SLOAD on the slot just written, so the common zero case costs far
    ///      less than an unconditional `approve(0)`.
    function _clearAllowance(address token, address spender) internal {
        if (IERC20(token).allowance(address(this), spender) != 0) {
            token.safeApprove(spender, 0);
        }
    }

    function _getAssetBalance(address token) internal view returns (uint256) {
        return token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this));
    }

    function _sweepFunds(address token, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (token == address(0)) {
            to.safeTransferETH(amount);
        } else {
            token.safeTransfer(to, amount);
        }
        emit SweptFunds(to, token, amount);
    }
}

project/src/contracts/abstract/SKAggregator_V1.sol

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

import {SafeTransferLib} from "../../lib/SafeTransferLib.sol";
import {ReentrancyGuard} from "../../lib/ReentrancyGuard.sol";
import {Owners} from "../../lib/Owners.sol";
import {SKTokenTransferProxy} from "../misc/SKTokenTransferProxy.sol";
import {IERC20} from "../../interfaces/IERC20.sol";
import {IPermit2} from "../../interfaces/IPermit2.sol";

abstract contract SKAggregator_V1 is Owners, ReentrancyGuard {
    using SafeTransferLib for address;

    event FeeSet(uint256 fee, address feeRecipient);

    uint256 public fee;
    address public feeRecipient;
    SKTokenTransferProxy public tokenTransferProxy;
    address public permit2;

    constructor(address _tokenTransferProxy, address _feeRecipient) {
        _setOwner(tx.origin, true);
        tokenTransferProxy = SKTokenTransferProxy(_tokenTransferProxy);
        feeRecipient = _feeRecipient;
    }

    // Needed for the swap router to be able to send back ETH
    receive() external payable {}

    function setFee(uint256 _fee, address _feeRecipient) external isOwner {
        require(_fee <= 1000, "fee can not be more than 10%");
        fee = _fee;
        feeRecipient = _feeRecipient;
        emit FeeSet(_fee, _feeRecipient);
    }

    /// @dev Take fee from amount, handles both gas (asset = address(0)) and tokens
    /// @param asset The asset address (address(0) for native gas asset)
    /// @param amount The amount to take fee from
    /// @return Amount after fee deduction
    function takeFee(address asset, uint256 amount) internal returns (uint256) {
        uint256 amountFee = getFee(amount);
        if (amountFee > 0) {
            if (asset == address(0)) {
                feeRecipient.safeTransferETH(amountFee);
            } else {
                asset.safeTransfer(feeRecipient, amountFee);
            }
            amount -= amountFee;
        }
        return amount;
    }

    /// @dev Take fee with custom fee basis points and recipient
    /// @param asset The asset address (address(0) for native gas asset)
    /// @param amount The amount to take fee from
    /// @param feeBps Fee in basis points (1 = 0.01%, 100 = 1%)
    /// @param recipient Address to receive the fee
    /// @return Amount after fee deduction
    function takeFee(
        address asset,
        uint256 amount,
        uint256 feeBps,
        address recipient
    ) internal returns (uint256) {
        if (feeBps == 0 || recipient == address(0)) {
            return amount;
        }
        uint256 feeAmount = (amount * feeBps) / 10000;
        if (feeAmount > 0) {
            if (asset == address(0)) {
                recipient.safeTransferETH(feeAmount);
            } else {
                asset.safeTransfer(recipient, feeAmount);
            }
            amount -= feeAmount;
        }
        return amount;
    }

    function getFee(uint256 amount) internal view returns (uint256) {
        if (fee != 0) {
            return (amount * fee) / 10000;
        }
        return 0;
    }

    /// @notice Set TokenTransferProxy address (one-time, for CREATE2 compatibility)
    /// @dev Can only be called if TTP was not set in constructor (address(0))
    function setTokenTransferProxy(address _ttp) external isOwner {
        require(address(tokenTransferProxy) == address(0), "TTP already set");
        require(_ttp != address(0), "Invalid TTP");
        tokenTransferProxy = SKTokenTransferProxy(_ttp);
    }

    /// @notice Set Permit2 address (one-time, for CREATE2 compatibility)
    /// @dev Permit2 canonical address: 0x000000000022D473030F116dDEE9F6B43aC78BA3
    function setPermit2(address _permit2) external isOwner {
        require(permit2 == address(0), "Permit2 already set");
        require(_permit2 != address(0), "Invalid Permit2");
        permit2 = _permit2;
    }

    /// @dev Pull tokens from user via TTP, returns actual amount received
    /// @dev Handles fee-on-transfer tokens by checking balance difference
    function _pullTokens(
        address token,
        address from,
        uint256 amount
    ) internal returns (uint256 received) {
        uint256 balanceBefore = IERC20(token).balanceOf(address(this));
        tokenTransferProxy.transferTokens(token, from, address(this), amount);
        received = IERC20(token).balanceOf(address(this)) - balanceBefore;
    }

    /// @dev Pull tokens from user via Permit2, returns actual amount received
    /// @dev Handles fee-on-transfer tokens by checking balance difference
    function _pullTokensWithPermit2(
        address token,
        address from,
        uint256 amount,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) internal returns (uint256 received) {
        uint256 balanceBefore = IERC20(token).balanceOf(address(this));
        IPermit2(permit2).permitTransferFrom(
            IPermit2.PermitTransferFrom({
                permitted: IPermit2.TokenPermissions({
                    token: token,
                    amount: amount
                }),
                nonce: nonce,
                deadline: deadline
            }),
            IPermit2.SignatureTransferDetails({
                to: address(this),
                requestedAmount: amount
            }),
            from,
            signature
        );
        received = IERC20(token).balanceOf(address(this)) - balanceBefore;
    }

    // Aggregator contracts are not meant to hold any funds
    // This is just in case assets get stuck in the contract
    function rescueFunds(
        address asset,
        uint256 amount,
        address destination
    ) public isOwner {
        if (asset == address(0)) {
            payable(destination).transfer(amount);
        } else {
            asset.safeTransfer(destination, amount);
        }
    }
}

project/src/contracts/abstract/SKChainflipAggregator_V1.sol

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

import {SafeTransferLib} from "../../lib/SafeTransferLib.sol";
import {Owners} from "../../lib/Owners.sol";
import {TSAggregatorTokenTransferProxy} from "../misc/TSAggregatorTokenTransferProxy.sol";

abstract contract SKChainflipAggregator_V1 is Owners {
    using SafeTransferLib for address;

    address public cfVault;

    constructor(address _cfVault) {
        cfVault = _cfVault;
    }

    function updateCfVault(address _cfVault) external isOwner {
        cfVault = _cfVault;
    }

   /// @dev Check that the sender is the Chainflip's Vault.
    modifier onlyCfVault() {
        require(msg.sender == cfVault, "CFReceiver: caller not Chainflip sender");
        _;
    }
}

project/src/contracts/misc/SKTokenTransferProxy.sol

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

import {SafeTransferLib} from "../../lib/SafeTransferLib.sol";
import {Executors} from "../../lib/Executors.sol";
import {IERC20} from "../../interfaces/IERC20.sol";

/// @title SKTokenTransferProxy
/// @notice Token transfer proxy for SwapKit aggregators
/// @dev Aggregators register as executors and call transferTokens to pull tokens from users.
///      Owners can add/remove executors and pause/unpause the contract.
///      Always returns actual received amount to handle fee-on-transfer tokens.
contract SKTokenTransferProxy is Executors {
    using SafeTransferLib for address;

    event Paused(address indexed by);
    event Unpaused(address indexed by);

    bool public paused;

    modifier whenNotPaused() {
        require(!paused, "Paused");
        _;
    }

    constructor() {
        _setOwner(tx.origin, true);
    }

    /// @notice Transfer tokens from user to destination, returning actual amount received
    /// @param token Token address to transfer
    /// @param from Source address (must have approved this contract)
    /// @param to Destination address
    /// @param amount Amount to transfer
    /// @return received Actual amount received (may differ for fee-on-transfer tokens)
    function transferTokens(
        address token,
        address from,
        address to,
        uint256 amount
    ) external isExecutor whenNotPaused returns (uint256 received) {
        require(from == tx.origin, "Invalid from");

        uint256 balanceBefore = IERC20(token).balanceOf(to);
        token.safeTransferFrom(from, to, amount);
        received = IERC20(token).balanceOf(to) - balanceBefore;
    }

    /// @notice Pause all transfers (emergency stop)
    function pause() external isOwner {
        paused = true;
        emit Paused(msg.sender);
    }

    /// @notice Resume transfers
    function unpause() external isOwner {
        paused = false;
        emit Unpaused(msg.sender);
    }
}

project/src/contracts/misc/TSAggregatorTokenTransferProxy.sol

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

import {SafeTransferLib} from "../../lib/SafeTransferLib.sol";
import {Owners} from "../../lib/Owners.sol";

/// @title TSAggregatorTokenTransferProxy
/// @notice Token transfer proxy for THORSwap aggregators (legacy TS prefix)
/// @dev Aggregators register as owners and call transferTokens to pull tokens from users
contract TSAggregatorTokenTransferProxy is Owners {
    using SafeTransferLib for address;

    constructor() {
        _setOwner(msg.sender, true);
    }

    function transferTokens(
        address token,
        address from,
        address to,
        uint256 amount
    ) external isOwner {
        require(from == tx.origin || _isContract(from), "Invalid from address");
        token.safeTransferFrom(from, to, amount);
    }

    function _isContract(address account) internal view returns (bool) {
        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }
}

project/src/interfaces/IChainflipReceiver.sol

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

/**
 * @dev Minimal interface for Chainflip vault or router to call cfReceive
 *      In practice, Chainflip's official interface will call this function
 *      on your contract, delivering the swapped tokens.
 */
interface IChainflipReceiver {
    function cfReceive(
        uint32 srcChain,
        bytes calldata srcAddress,
        bytes calldata message,
        address token,
        uint256 amount
    ) external payable;
}

project/src/interfaces/IChainflipVault.sol

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

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

interface IChainflipVault {
    event SwapNative(
        uint32 dstChain,
        bytes dstAddress,
        uint32 dstToken,
        uint256 amount,
        address indexed sender,
        bytes cfParameters
    );
    event SwapToken(
        uint32 dstChain,
        bytes dstAddress,
        uint32 dstToken,
        address srcToken,
        uint256 amount,
        address indexed sender,
        bytes cfParameters
    );
    event XCallNative(
        uint32 dstChain,
        bytes dstAddress,
        uint32 dstToken,
        uint256 amount,
        address indexed sender,
        bytes message,
        uint256 gasAmount,
        bytes cfParameters
    );
    event XCallToken(
        uint32 dstChain,
        bytes dstAddress,
        uint32 dstToken,
        address srcToken,
        uint256 amount,
        address indexed sender,
        bytes message,
        uint256 gasAmount,
        bytes cfParameters
    );

    function xSwapNative(
        uint32 dstChain,
        bytes memory dstAddress, // 32 bytes expected by chainflip
        uint32 dstToken,
        bytes calldata cfParameters
    ) external payable;

    function xSwapToken(
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        IERC20 srcToken,
        uint256 amount,
        bytes calldata cfParameters
    ) external;

    function xCallNative(
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        bytes calldata message,
        uint256 gasAmount,
        bytes calldata cfParameters
    ) external payable;

    function xCallToken(
        uint32 dstChain,
        bytes calldata dstAddress,
        uint32 dstToken,
        bytes calldata message,
        uint256 gasAmount,
        IERC20 srcToken,
        uint256 amount,
        bytes calldata cfParameters
    ) external;
}

project/src/interfaces/IERC20.sol

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

interface IERC20 {
    function decimals() external view returns (uint8);

    function totalSupply() external view returns (uint256);

    function balanceOf(address account) external view returns (uint256);

    function transfer(
        address recipient,
        uint256 amount
    ) external returns (bool);

    function allowance(
        address owner,
        address spender
    ) external view returns (uint256);

    function approve(address spender, uint256 amount) external returns (bool);

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);
}

project/src/interfaces/IERC4626.sol

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

interface IERC4626 {
    function asset() external view returns (address assetTokenAddress);

    function totalAssets() external view returns (uint256 totalManagedAssets);

    function convertToShares(
        uint256 assets
    ) external view returns (uint256 shares);

    function convertToAssets(
        uint256 shares
    ) external view returns (uint256 assets);

    function maxDeposit(
        address receiver
    ) external view returns (uint256 maxAssets);

    function previewDeposit(
        uint256 assets
    ) external view returns (uint256 shares);

    function deposit(
        uint256 assets,
        address receiver
    ) external returns (uint256 shares);

    function maxMint(
        address receiver
    ) external view returns (uint256 maxShares);

    function previewMint(uint256 shares) external view returns (uint256 assets);

    function mint(
        uint256 shares,
        address receiver
    ) external returns (uint256 assets);

    function maxWithdraw(
        address owner
    ) external view returns (uint256 maxAssets);

    function previewWithdraw(
        uint256 assets
    ) external view returns (uint256 shares);

    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    function maxRedeem(address owner) external view returns (uint256 maxShares);

    function previewRedeem(
        uint256 shares
    ) external view returns (uint256 assets);

    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);

    event Deposit(
        address indexed caller,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );
    event Withdraw(
        address indexed caller,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );
}

project/src/interfaces/IPermit2.sol

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

/// @title IPermit2
/// @notice Minimal interface for Uniswap's Permit2 SignatureTransfer
/// @dev Permit2 canonical address: 0x000000000022D473030F116dDEE9F6B43aC78BA3
interface IPermit2 {
    /// @notice Token and amount for a permit
    struct TokenPermissions {
        address token;
        uint256 amount;
    }

    /// @notice The permit data for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        uint256 nonce;
        uint256 deadline;
    }

    /// @notice Details for the transfer recipient
    struct SignatureTransferDetails {
        address to;
        uint256 requestedAmount;
    }

    /// @notice Transfer tokens using a signed permit
    /// @param permit The permit data signed by the owner
    /// @param transferDetails The recipient and amount to transfer
    /// @param owner The owner of the tokens
    /// @param signature The signature over the permit data
    function permitTransferFrom(
        PermitTransferFrom calldata permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;
}

project/src/lib/Executors.sol

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

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

abstract contract Executors is Owners {
    event ExecutorSet(address indexed executor, bool active);

    mapping(address => bool) public executors;

    modifier isExecutor() {
        require(executors[msg.sender], "Unauthorized");
        _;
    }

    function _setExecutor(address executor, bool active) internal virtual {
        executors[executor] = active;
        emit ExecutorSet(executor, active);
    }

    function setExecutor(address owner, bool active) external virtual isOwner {
        _setExecutor(owner, active);
    }
}

project/src/lib/Owners.sol

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

abstract contract Owners {
    event OwnerSet(address indexed owner, bool active);

    mapping(address => bool) public owners;

    modifier isOwner() {
        require(owners[msg.sender], "Unauthorized");
        _;
    }

    function _setOwner(address owner, bool active) internal virtual {
        owners[owner] = active;
        emit OwnerSet(owner, active);
    }

    function setOwner(address owner, bool active) external virtual isOwner {
        _setOwner(owner, active);
    }
}

project/src/lib/ReentrancyGuard.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

project/src/lib/SafeTransferLib.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
    /*///////////////////////////////////////////////////////////////
                            ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool callStatus;

        assembly {
            // Transfer the ETH and store if it succeeded or not.
            callStatus := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(callStatus, "ETH_TRANSFER_FAILED");
    }

    /*///////////////////////////////////////////////////////////////
                           ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool callStatus;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata to memory piece by piece:
            mstore(
                freeMemoryPointer,
                0x23b872dd00000000000000000000000000000000000000000000000000000000
            ) // Begin with the function selector.
            mstore(
                add(freeMemoryPointer, 4),
                and(from, 0xffffffffffffffffffffffffffffffffffffffff)
            ) // Mask and append the "from" argument.
            mstore(
                add(freeMemoryPointer, 36),
                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
            ) // Mask and append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.

            // Call the token and store if it succeeded or not.
            // We use 100 because the calldata length is 4 + 32 * 3.
            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
        }

        require(
            didLastOptionalReturnCallSucceed(callStatus),
            "TRANSFER_FROM_FAILED"
        );
    }

    function safeTransfer(address token, address to, uint256 amount) internal {
        bool callStatus;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata to memory piece by piece:
            mstore(
                freeMemoryPointer,
                0xa9059cbb00000000000000000000000000000000000000000000000000000000
            ) // Begin with the function selector.
            mstore(
                add(freeMemoryPointer, 4),
                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
            ) // Mask and append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.

            // Call the token and store if it succeeded or not.
            // We use 68 because the calldata length is 4 + 32 * 2.
            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
        }

        require(
            didLastOptionalReturnCallSucceed(callStatus),
            "TRANSFER_FAILED"
        );
    }

    function safeApprove(address token, address to, uint256 amount) internal {
        bool callStatus;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata to memory piece by piece:
            mstore(
                freeMemoryPointer,
                0x095ea7b300000000000000000000000000000000000000000000000000000000
            ) // Begin with the function selector.
            mstore(
                add(freeMemoryPointer, 4),
                and(to, 0xffffffffffffffffffffffffffffffffffffffff)
            ) // Mask and append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.

            // Call the token and store if it succeeded or not.
            // We use 68 because the calldata length is 4 + 32 * 2.
            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
        }

        require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
    }

    /*///////////////////////////////////////////////////////////////
                         INTERNAL HELPER LOGIC
    //////////////////////////////////////////////////////////////*/

    function didLastOptionalReturnCallSucceed(
        bool callStatus
    ) private pure returns (bool success) {
        assembly {
            // Get how many bytes the call returned.
            let returnDataSize := returndatasize()

            // If the call reverted:
            if iszero(callStatus) {
                // Copy the revert message into memory.
                returndatacopy(0, 0, returnDataSize)

                // Revert with the same message.
                revert(0, returnDataSize)
            }

            switch returnDataSize
            case 32 {
                // Copy the return data into memory.
                returndatacopy(0, 0, returnDataSize)

                // Set success to whether it returned true.
                success := iszero(iszero(mload(0)))
            }
            case 0 {
                // There was no return data.
                success := 1
            }
            default {
                // It returned some malformed input.
                success := 0
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.